以下代码可以处理上述情况:
If($ServerInstanceName -like "*,*")
{
Write-Host "SQL Server Instance Name containts TCP Port Number"
$SQLQuery=@"
SET NOCOUNT ON
Declare @key Varchar(100), @PortNumber varchar(100)
if charindex('\',CONVERT(varchar(200),
SERVERPROPERTY('servername')),0<>0
begin
set @key = 'SOFTWARE\MICROSOFT\Microsoft SQL Server\'+@@servicename+'\MSSQLServer\Supersocketnetlib\TCP'
end
else
begin
set @key = 'SOFTWARE\MICROSOFT\MSSQLServer\MSSQLServer\Supersocketnetlib\TCP'
end
EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key=@key,@value_name='Tcpport',@value=@PortNumber OUTPUT
SELECT CONVERT(varchar(200), SERVERPROPERTY('servername')) AS ServerName
"@
$ServerInstanceName = (Invoke-Sqlcmd -ServerInstance
$ServerInstanceName -Database 'master' -Query $SQLQuery).ServerName
Write-Host "Compatible ServerName (without TCP Port) to change its Collation:" $ServerInstanceName