Change instance level collation of SQL Server using powershell

泄露秘密 提交于 2020-02-07 05:17:26

问题


I want to change the collation of SQL Server instance programmatically using powershell script. Followings are the manual steps:

  1. Stop the SQL Server instance
  2. Go to directory location: "C:\Program Files\Microsoft SQL Server\MSSQL14.SQL2017\MSSQL\Binn"
  3. Execute following command: sqlservr -c -m -T4022 -T3659 -s"SQL2017" -q"SQL_Latin1_General_CP1_CI_AS"
  4. After the execution of the above command, following message displayed: "The default collation was successfully changed."
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!