Change the output color of the master record based on foreach if elseif result in Powershell
I am trying to change the color of the write output based on the lastrunoutcome property of SQL Server jobs in Powershell .... as in ... if the job is successful, the lastrunoutcome output is "Success", in green .... if it failed, then " Failure "in red. I have a script working to get the desired working 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 got ... but it gives me the "LastRunOutcome" error - ReadOnly property.
Any help would be greatly appreciated!
Thanks!
Emo
a source to share
Splat parameters let you pass a hash of parameter pairs of a parameter name to a function or cmdlet. This hash can be built gradually ...
$extraArgs = @{}
if ($thingsFailed) {
$extraArgs["foregroundColor"] = "Red"
}
write-host "Message" @extraArgs
If the hash is empty, nothing will be added, but if it $thingsFailed
was set, the output will be red.
a source to share