I have a PowerShell script that does multiple things, and takes in a delay parameter (time in seconds). I want to kick off a background job that plays a sound after a time defined by the delay parameter.
So the user enters something like:
.\RunMyScript -delay 10
In my script, my param block looks like this:
param([int]$delay, [switch] $cleanup)
Now, the $delay parameter works everywhere in my script, but it doesn't work when I use Start-Job. I tried both the following approaches, and neither worked.
APPROACH 1
$PlayStartSound = {
Start-Sleep -s $delay
[System.Media.SystemSounds]::Beep.Play();
}
Start-Job $PlayStartSound
APPROACH 2
Start-Job –Scriptblock {Start-Sleep -s $delay; [System.Media.SystemSounds]::Beep.Play();}
Both approaches play the sound immediately, ignoring the delay. If I replace $delay with a number say like so, then it works:
Start-Job –Scriptblock {Start-Sleep -s 10; [System.Media.SystemSounds]::Beep.Play();}
I'm curious as to why $delay is not in scope, and how I can fix this? Thanks for looking.