處理

2016-09-01 41 views
0

我用一個簡單的net use命令映射網絡驅動器處理

net use \\$HOSTIP $PASSWD /user:$UNAME 

使用PowerShell網使用的錯誤消息我一定要用網使用,而不是新PSDrive來的,因爲腳本運行更多的則400機器在多個實例中,只是不可行。 我要過濾的錯誤信息,那麼網絡使用回像

System error 64 has occurred. 

​​

我怎樣才能做到這一點?

回答

1

你可以做到以下幾點:

#set process startup info (redirect stderr) 
$pinfo = new-object System.Diagnostics.ProcessStartInfo 
$pinfo.Filename = "net.exe" 
$pinfo.UseShellExecute = $false 
$pinfo.Arguments = @("use","\\$($HOSTIP)","$($PASSWD)","/user:$($UNAME)") 
$pinfo.redirectstandardError = $true 
#start process and wait for it to exit 
$p.start() | out-null 
$p.waitforexit() 
#check the returncode 
if($p.exitcode -ne 0){ 
    #rc != 0 so we grab the stderr output 
    $err = $p.standardError.ReadToEnd() 
    #first line of the output contains the string from your question, matching it against regex 
    if($err[0] -match "System error ([0-9]*) has occurred"){ 
     #switching the error code 
     switch($Matches[1]){ 
      64 {do-something64;break;} 
      67 {do-something67;break;} 
     } 
    } 
} 

這應該做的伎倆,雖然我不能做一個關於它是多麼高性能,你將不得不嘗試聲明。如果輸出可能與您在問題中發佈的字符串不同,則必須編寫自己的正則表達式來處理它們。

請記住net的輸出是本地化的,因此我的示例中的正則表達式在系統語言不是英語的系統上不起作用。

希望幫助

0

使用cmd重定向stderrstdout

$log = cmd /c "2>&1" net use \\$HOSTIP $PASSWD /user:$UNAME 

現在變量包含字符串(2文本和2個空)的數組:

系統錯誤53發生。

未找到網絡路徑。

你可以分析它:

$log = cmd /c "2>&1" net use \\$HOSTIP $PASSWD /user:$UNAME 
if ($LASTEXITCODE -and $log -join "`n" -match '^.+?(\d+).+?\n+(.+)') { 
    $errCode = [int]$matches[1] 
    $errMessage = $matches[2] 
}