Change write-host output color based on foreach if elseif outcome in Powershell
Posted
by Emo
on Stack Overflow
See other posts from Stack Overflow
or by Emo
Published on 2010-04-26T15:49:53Z
Indexed on
2010/04/26
16:13 UTC
Read the original article
Hit count: 304
I'm trying to change the color of write-host output based on the lastrunoutcome property of SQL Server jobs in Powershell....as in...if a job was successfull, the output of lastrunoutcome is "Success" in green....if failed, then "Failed" in red. I have the script working to get the desired job status...I just don't know how to change the colors.
Here's what I have so far:
# Check for failed SQL jobs on multiple servers
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null
foreach ($svr in get-content "C:\serverlist2.txt")
{
$a = get-date
$BegDate = (Get-Date $a.AddDays(-1) -f d) + " 12:00:00 AM"
$BegDateTrans = [system.datetime]$BegDate
write-host $svr
$srv=New-Object "Microsoft.SqlServer.Management.Smo.Server" "$svr"
$srv.jobserver.jobs | where-object {$_.lastrundate -ge $BegDateTrans -and $_.Name -notlike "????????-????-????-????-????????????"} | format-table name,lastrunoutcome,lastrundate -autosize
foreach ($_.lastrunoutcome in $srv.jobserver.jobs)
{
if ($_.lastrunoutcome = 0)
{
-forgroundcolor red
}
else
{}
}
}
This seems to be the closest I've gotten...but it's giving me an error of ""LastRunOutcome" is a ReadOnly property."
Any help would be greatly appreciated!
Thanks!
Emo
© Stack Overflow or respective owner