Created
May 30, 2021 03:54
-
-
Save kewalaka/4144d7b18286b0b33e426ca6749b4b39 to your computer and use it in GitHub Desktop.
This will fetch the SQL aliases from remote machines, using Invoke-Command, could make it into a cmdlet too...
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
| # | |
| # simple script that gets the SQL Alias info from remote machines | |
| # | |
| [scriptblock]$GetSQLAliases = { | |
| $aliasRegistryPath = 'HKLM:\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo' | |
| If (Test-Path($aliasRegistryPath)) { | |
| $aliases = @() | |
| (Get-Item $aliasRegistryPath).Property | ForEach-Object { | |
| $aliasName = $_ | |
| $aliasTarget = Get-ItemPropertyValue $aliasRegistryPath -Name $aliasName | |
| $aliasTargetType = switch ($aliasTarget.split(',')[0]) { | |
| 'DBNMPNTW' { 'NP' } | |
| 'DBMSSOCN' { 'TCP' } | |
| Default { 'UNKNOWN' } | |
| } | |
| $aliasTargetServer = $aliasTarget.split(',')[1] | |
| $aliasTargetPort = $aliasTarget.split(',')[2] | |
| $aliases += [PSCustomObject][Ordered]@{ | |
| 'AliasName' = $aliasName | |
| 'Protocol' = $aliasTargetType | |
| 'Server' = $aliasTargetServer | |
| 'Port' = $aliasTargetPort | |
| } | |
| } | |
| return $aliases | |
| } | |
| # if the registry key doesn't exist there are no aliases configured | |
| else { return $null } | |
| } | |
| # example usage: | |
| $aliases = Invoke-Command -ScriptBlock $GetSQLAliases -ComputerName LABSQL01, LABSQL02 | |
| # Invoke-Command will return the computer as "PSComputerName" - can rename to "ComputerName" using an expression, e.g: | |
| $aliases | Select-Object @{name = 'ComputerName'; expression = 'PSComputerName' }, AliasName, Protocol, Server, Port | Format-Table -AutoSize | |
| <# | |
| Example output: | |
| ComputerName AliasName Protocol Server Port | |
| ------------ --------- -------- ------ ---- | |
| LABSQL01 myalias TCP labsql02 | |
| LABSQL01 my alias2 TCP labsql02 5353 | |
| LABSQL01 anamedpipe NP \\labsql01\PIPE\sql\query | |
| LABSQL02 labsql02 alias TCP anotherserver 1567 | |
| #> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment