问题
I want to change the collation of SQL Server instance programmatically using powershell script. Followings are the manual steps:
- Stop the SQL Server instance
- Go to directory location: "C:\Program Files\Microsoft SQL Server\MSSQL14.SQL2017\MSSQL\Binn"
- Execute following command: sqlservr -c -m -T4022 -T3659 -s"SQL2017" -q"SQL_Latin1_General_CP1_CI_AS"
- After the execution of the above command, following message displayed: "The default collation was successfully changed."
- Then I need to press ctrl+c to stop further execution. How can I do this programmatically?
回答1:
When we execute the command to change the SQL Server Collation, it logs the execution details in event viewer application logs. Using loop we can check the event viewer application logs for SqlServr.exe continuously, and when it generates the following log message: "The default collation was successfully changed", we can kill the process.
#Take the time stamp before execution of Collation Change Command
$StartDateTime=(Get-Date).AddMinutes(-1)
# Execute the Collation Change Process
Write-Host "Executing SQL Server Collation Change Command"
$CollationChangeProcess=Start-Process -FilePath $SQLRootDirectory -ArgumentList
"-c -m -T 4022 -T 3659 -s $JustServerInstanceName -q $NewCollationName" -
NoNewWindow -passthru
Do
{
$log=Get-WinEvent -FilterHashtable @{logname='application';
providername=$SQLServiceName; starttime = $StartDateTime} | Where-Object -
Property Message -Match 'The default collation was successfully changed.'
IF($log.count -gt 0 -and $log.TimeCreated -gt $StartDateTime )
{
Stop-Process -ID $CollationChangeProcess.ID
write-host 'Collation Change Process Completed Successfully.'
break
}
$DateTimeNow=(Get-Date)
$Duration=$DateTimeNow-$StartDateTime
write-host $Duration.totalminutes
Start-Sleep -Seconds 2
IF ($Duration.totalminutes -gt 2)
{
write-host 'Collation Change Process Failed.'
break
}
}while (1 -eq 1)
来源:https://stackoverflow.com/questions/58337969/change-instance-level-collation-of-sql-server-using-powershell