Skip to main content


Showing posts from October, 2011

Redirect PowerShell Output Gotcha

So to run PowerShell jobs, I typically use a PSJob.cmd that executes POWERSHELL.EXE pointing to the passed in script name and redirect output using old DOS semantics (> file.log 2>&1). Well this worked fine for single threaded PowerShell scripts. However, when I started using Start-Job to get a lot of work done faster, I started getting file handle exceptions and some really weird behavior. After a couple hours trying different things, thinking it was my Start-Job script, I decided to change the way I redirected output and switched to use Out-File.

Well, long, painful story brought short is that use Out-File, not DOS output redirection. For your enjoyment, this is my PSJob.cmd script I use to kick off scripts from our enterprise scheduler.
POWERSHELL -NonInteractive -NoLogo -NoProfile -ExecutionPolicy ByPass -Comand "%~dp0%~1.ps1 | Out-File %~dp0%~1.log -Encoding ASCII -Force"EXIT /B %ERRORLEVEL%   I know, amazing right! ;)

Throttling PowerShell Jobs

I needed to multi-thread a task that had a thousand records to process and each one needed a 15 second sleep. Well as I found out, there is no built-in throttling to Start-Job, so I had 1000 powershell.exe try to launch. Not good to say the least. Anyway, after looking online I found throttling code and adapted it to something simple and sweet. All I need to do is inject a call to Throttle-Jobs before I do a Start-Job and it'll wait for the number of running jobs to drop below the maximum.
function Throttle-Jobs {  param( [int] $maximum = 25, [TimeSpan] $interval = [TimeSpan]::FromSeconds(1) )  while ( (Get-Job -State Running | Measure-Object).Count -gt $maximum ) {  Start-Sleep -Milliseconds $interval.TotalMilliseconds      }  }