Reputation: 53
I have a simple bit of Powershell code which pings servers if they are up and then disables the local admin account. How can I output the results to a log file so that I have record of what I have disabled.
This is what I have so far
$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
}
}
Upvotes: 2
Views: 74760
Reputation: 200493
Write-Host
writes directly to the console. That output cannot be redirected to a file. Replace it Write-Output
and drop the fancy coloring if you want to redirect the output to a file. Also, I'd pipe the computer list into a ForEach-Object
loop, so you can directly write the output to a file. And Test-Connection
returns a boolean value, so you can use it directly in the conditional:
$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'
Upvotes: 7