如何处理for-each和switch条件中的主体/镜像状态

时间:2016-09-19 09:53:54

标签: sql-server sql-server-2008 powershell

# Load SMO extension
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null;

# Servers to check
#$sqlservers = @("$svr", "$svr\$inst");
$sqlservers = Get-Content 'servers.txt'
foreach ($server in $sqlservers) {
  $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $server;
  # Get mirrored databases
  $databases = $srv.Databases | Where-Object {$_.IsMirroringEnabled -eq $true};

  #Write-Host $databases;
  Write-Host "==================================";
  # $test= $databases | Select-Object -Property Name, MirroringStatus | Format-Table -AutoSize;
  $databases | Select-Object -Property  MirroringStatus | Format-Table -AutoSize;
  foreach ($status in $databases) {
    switch ($databases.MirroringPartnerInstance) {
      1 { $status. + "Disconnected" }
      2 { $status. + "Suspended" }
      2 { $status. + "Synchronizing" }
      3 { $status. + "Not Synchronized" }
    }
  }

我想要这样的代码。

1 个答案:

答案 0 :(得分:0)

Below is my code if you do this way you will not get issue 

function mirroring (
[string] $svr,
[string]$inst,
[string] $datastore
)
{

Set-StrictMode -Version 2
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
[Void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")
$Conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection
$SqlConnection = "Server=$svr\$inst;Database=master;Integrated Security=True;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = " SELECT  db_name(sd.[database_id])AS [Database Name]
          ,sd.mirroring_state                  AS [Mirror State]
          ,sd.mirroring_state_desc             AS [Mirror State] 
          ,sd.mirroring_partner_name           AS [Partner Name]
          ,sd.mirroring_role_desc              AS [Mirror Role]  
          ,sd.mirroring_safety_level_desc      AS [Safety Level]
          ,sd.mirroring_witness_name           AS [Witness]
          ,sd.mirroring_connection_timeout AS [Timeout(sec)]
    FROM sys.database_mirroring AS sd
    WHERE mirroring_guid IS NOT null
    ORDER BY [Database Name];" 
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] 
 $datastore = $DataSet.Tables[0].Rows[0][2]            
 write-host $datastore

 if( $datastore -eq "Disconnected")
 {
# test
DisconnectedREMEDIATION

 }
 elseif($datastore -eq "SYNCHRONIZED")
 {

 SYNCHRONIZEDREMEDIATION
 }



}