Created
September 22, 2020 21:19
-
-
Save rdc-112/db592a30c299818fb32c404b8b6abfd1 to your computer and use it in GitHub Desktop.
Update SQL Server Firewall Rule Using Powershell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param | |
([Parameter(Mandatory)][string]$resourceGroupName, | |
[Parameter(Mandatory)][string]$sqlServerName, | |
[Parameter(Mandatory)][string]$ruleName) | |
<# | |
TODO: | |
- Add option to create firewall rule if it doesn't exist already | |
- Wrap wxternal method calls in try/catch blocks | |
- Add option to use PC name as rule name. Reduces the number of params that need to be provided | |
- Improve log messages | |
#> | |
#Get-ComputerInfo | Select -Property CsUSerName | |
echo "Getting public IP address" | |
$ip = Invoke-RestMethod http://ipinfo.io/json | Select -exp ip | |
#Had to wrap ConvertFromJson in parenthesis, see here: https://stackoverflow.com/questions/55500059/read-multiple-json-files-into-an-array-of-powershell-objects-and-filter-out-thos | |
#COuld hav for-eached or reassigned va but didn't want to | |
echo "Getting existing firewall rules" | |
#Specity the variable as an array type to simplify checking the result. If a single result is returned from Where-Object we get an object, if > 1 results we get an array. | |
#By declaring the var as an array now, no matter the results returned we simplify the comparison later | |
[array]$rules = (az sql server firewall-rule list -g $resourceGroupName -s $sqlServerName | ConvertFrom-Json) | Where-Object { $_.name -eq $ruleName } | |
#Need a check if result is null - have to create | |
#If result greater than 1 > exception | |
if ($rules.Count -ne 1) { | |
throw "Too many rules returned. Check the search string"} | |
#update rule | |
echo "Updating existing firewall rule" | |
$result = az sql server firewall-rule update -g $resourceGroupName -s $sqlServerName -n $rules[0].name --start-ip-address $ip --end-ip-address $ip | |
echo $result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment