2013-09-30 140 views
2

我有一個簡單的PowerShell代碼,如果服務器ping通,然後禁用本地管理員帳戶。如何將結果輸出到日誌文件,以便記錄我禁用的內容。PowerShell輸出結果從腳本到日誌文件

這是我迄今爲止

$computers = Get-ADComputer -filter {OperatingSystem -like "Windows Server*"} | 
ForEach ($computer in $computers) {  
    $rtn = Test-Connection -CN $computer -Count 1 -BufferSize 16 -Quiet  
    IF($rtn -match 'True') { 
    write-host -ForegroundColor green $computer | Disable-localUserAccount -ComputerName $computer -username Administrator 
    } ELSE { 
     Write-host -ForegroundColor red $computer 
    }  
} 
+0

你有什麼試圖寫入到文件中試過嗎?這樣做對於PowerShell來說非常容易,並且有多種方式可以實現。 – alroc

+0

我試過這個,但不知道這是做到這一點的正確方法$ outputstring = $ computer $ outputstring -join「,」>> C:\ Create_Adminuser_computers.csv – user2785434

回答

6

Write-Host直接寫入到控制檯。該輸出不能被重定向到文件。如果要將輸出重定向到文件,請將其替換爲Write-Output並放下奇特的顏色。另外,我會將計算機列表導入到ForEach-Object循環中,以便您可以直接將輸出寫入文件。和Test-Connection返回一個布爾值,這樣你就可以直接在有條件使用它:

$computers | % { 
    if (Test-Connection -CN $_ -Count 1 -BufferSize 16 -Quiet) { 
    Write-Output "$_ online" 
    Disable-localUserAccount -ComputerName $_ -username Administrator 
    } else { 
    Write-Output "$_ offline" 
    }  
} | Out-File 'C:\path\to\your.log'