2017-10-02 17 views
0

私はスクリプトをpowershellで書いていますが、scripsはリモートホスト上のDHCPサービスなど、いくつかのシステムサービスの状態に関する情報を収集します。リモートホストへの接続に問題があり、WMIから情報を収集することがあります。以下 WMIコマンド:Powershell - リモート接続によるWMIエラー

$DHCP = Get-WmiObject win32_service -ComputerName $server 2>>$logerror2 | 
Where-Object -FilterScript {$_.Name -eq "dhcp"} 

は、私は2つのプロパティを持つオブジェクトを作成:出力は.csvファイルに向けられている

   [pscustomobject][ordered]@{ 
       ServerName = $server 
       DHCP = $DHCP.State 
       } 

、ファイルの内容は次のようになります。

"ServerName","DHCP" 
"srv1","Running" 
"srv2",, 
"srv3",, 

"srv2"と "srv3"という名前のホストでは、リモートホストWMIからの接続と情報の収集に問題があります。私は、「WMIの問題」とは、例えば、いくつかの情報を与える代わりに、空白の希望、およびファイルの内容は次のようになります必要があります。

"ServerName","DHCP" 
"srv1","Running" 
"srv2",WMI Problem, 
"srv3",WMI Problem,  

答えて

1

は、[OK]をする必要があり、これを試してみてください:

## Clear the Error variable incase the last server had an error ## 
if ($error) 
{ 
    $error.clear() 
} 

## Attempt to do the WMI command ## 
try 
{ 
    $DHCP = Get-WmiObject win32_service -ComputerName $server -erroraction stop | Where-Object {$_.Name -eq "dhcp"} 
} 
Catch 
{ 
    $errormsg = $_.Exception.Message 
} 

## If the WMI command errored then do this ## 
if ($error) 
{ 
    [pscustomobject][ordered]@{ 
    ServerName = $server 
    DHCP = $errormsg 
    } 
} 

## If the WMI command was successful do this ## 
Else 
{ 
    [pscustomobject][ordered]@{ 
    ServerName = $server 
    DHCP = $DHCP.State 
    } 
} 
0

@ Dizzyの答えから1ページを取る。

$CSV = Foreach ($Server in $ServerList) 
{ 
    $ServerObj = [pscustomobject][ordered]@{ 
     ServerName = $server 
     DHCP = $null 
    } 

    ## Attempt to do the WMI command ## 
    try 
    { 
     $DHCP = Get-WmiObject win32_service -ComputerName $server -erroraction stop | Where-Object {$_.Name -eq "dhcp"} 
     [String]$ServerObj.DHCP = $DHCP.State 
    } 
    Catch 
    { 
     $errormsg = $_.Exception.Message 
     [String]$ServerObj.DHCP = $errormsg 
    } 
    $ServerObj 
} 
$CSV | Export-Csv .\result.csv -NoTypeInformation 
関連する問題