This shows you the differences between two versions of the page.
windows:powershell:insertinstance [2014/06/16 20:00] haidong Refactoring, more test cases |
windows:powershell:insertinstance [2018/05/14 22:00] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | Here is a PowerShell script to discover SQL Server instances installed on the server hosts in the Host table. Please create a SQL Server Agent job for this. The domain account that this job runs under needs to in the local administrator's group on the host whose metrics it is trying to get. | ||
- | This information should be fairly static. Depending on your situation, scheduling this to run weekly, monthly, or quarterly, or whatever. You can always manually kick off this job if needed. | ||
- | |||
- | ** Remember to change "sql1" to your host instance name ** | ||
- | |||
- | <code powershell insertInstance.ps1> | ||
- | function getSqlInstanceName($ComputerName) { | ||
- | $SqlInstances = Get-Service -ComputerName $ComputerName | where {($_.Name -like | ||
- | 'mssql$*') -or ($_.Name -eq 'mssqlserver')} | ||
- | $instanceArray = @() | ||
- | if ($SqlInstances -ne $null) { | ||
- | $SqlInstances | foreach { | ||
- | $sqlName = $_.Name | ||
- | $service = Get-WmiObject win32_service -ComputerName $ComputerName | where {$_.Name -eq $sqlName} | ||
- | if ($sqlName -eq 'mssqlserver') { | ||
- | $instanceArray = $instanceArray + @(@{InstanceName=$ComputerName; StartupAcct=$service.StartName; Status=$_.Status})} | ||
- | else { | ||
- | $instanceArray = $instanceArray + @(@{InstanceName=$ComputerName + "\" + | ||
- | $sqlName.split("$")[1];StartupAcct=$service.StartName; Status=$_.Status})}}} | ||
- | return $instanceArray} | ||
- | |||
- | function insertInstanceSQL($i, $HostID) { | ||
- | $InstanceName = $i.InstanceName | ||
- | $StartupAcct = $i.StartupAcct | ||
- | if ($InstanceName -ne $null) { | ||
- | if ($i.Status -eq 'running') { | ||
- | $IsActive = "Y"} | ||
- | else {$IsActive = "N"} | ||
- | $sql = "EXEC Windows.Instance_Insert $HostID, '$InstanceName', '$StartupAcct', '$IsActive'" | ||
- | return $sql}} | ||
- | |||
- | $HostList = Invoke-Sqlcmd -ServerInstance "sql1" -Query "EXEC | ||
- | Windows.Host_Select_HostID_HostName" -Database "JiMetrics" | ||
- | $HostList | foreach { | ||
- | $HostID = $_.HostID | ||
- | Try {$SqlInstances = getSqlInstanceName($_.HostName)} | ||
- | Catch {Return} | ||
- | $SqlInstances | foreach { | ||
- | $sql = insertInstanceSQL $_ $HostID | ||
- | Invoke-Sqlcmd -Query $sql -ServerInstance "sql1" -Database "JiMetrics"}} | ||
- | </code> |