views:

126

answers:

2

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

+1  A: 

"Splat" parameters allow you to pass a hash of parameter name-value pairs to a function or cmdlet. This hash can be constructed incrementally...

$extraArgs = @{}
if ($thingsFailed) {
  $extraArgs["foregroundColor"] = "Red"
}

write-host "Message" @extraArgs

If the hash is empty nothing will be added, but if $thingsFailed was set the output will be in red.

Richard
+1  A: 
if ($_.lastrunoutcome = 0)

looks like a mistake; it should be "-eq" operator used, not "=". That is:

if ($_.lastrunoutcome -eq 0)
Roman Kuzmin
If I change the code to from "=" to "-eq" I just get the error "The term '-forgroundcolor' is not recognized as the name of a cmdlet, function, script file, or operable program."
Emo
I know that -eq is a comparative argument, that doesn't work here
Emo
Well...heck...I don' know..ignore my last two comments LOL!
Emo