This never happens either.
Here is my code block modified for simplicity. NB In the actual code, “Ampersand” is a real ampersand, not the word “Ampersand”
function LoseIt($fruitBasket, $name)
{
“Ampersand”{
$numKumquats = 0
$fruitList = $fruitBasket.split(“,”)
foreach ($fruit in $fruitList)
{
$fruitname = $fruit + $name
$serv = get-wmiobject Win32_Service | where {$.name -eq $fruitName}
if ($serv.State -eq “Running”)
{
numKumquats += 1
}
write-host “Inside Loop numKumquats is ” $numKumquats
}
}
trap
{
#Exception getting Win32_Service
#scream and cry
}
write-host “Outside Loop numKumquats is ” $numKumquats
if ($numKumquats > 0)
{
MakeKumquatJam $numKumquats
}
}
The thing was, inside the loop $numKumquats was being incremented and printing out the correct values in write-host, but outside the loop, $numKumquats was always null, with the result that the function MakeKumquatJam was never called. Sob.
I “fixed” it by removing the declaration of $numKumquts outside the for loop and moving the call to MakeKumquatJam above the trap. Like so:
function KeepIt($fruitBasket, $name)
{
$numKumquats = 0
“Ampersand”{
$fruitList = $fruitBasket.split(“,”)
foreach ($fruit in $fruitList)
{
$fruitname = $fruit + $name
$serv = get-wmiobject Win32_Service | where {$.name -eq $fruitName}
if ($serv.State -eq “Running”)
{
numKumquats += 1
}
write-host “Inside Loop numKumquats is ” $numKumquats
}
}write-host “Outside Loop numKumquats is ” $numKumquats
if ($numKumquats > 0)
{
MakeKumquatJam $numKumquats
}trap
{
#Exception getting Win32_Service
#scream and cry
}
write-host “Outside Loop numKumquats is ” $numKumquats
if ($numKumquats > 0)
{
MakeKumquatJam $numKumquats
}
}
With the above changes the function MakeKumquatJam was called… but it had nothing to do with the for loop.
The real problem was that originally I had actually declared two variables called $numKumquats, each with different scope. The scope of the first $numKumquats was global to the entire function, the scope of the second $numKumquats variable was local to the try/trap block commencing with
“Ampersand”
Originally I thought I had declared ONE instance of the variable $numKumquats which was mysteriously losing its value after the for loop completed. No No No. I had actually declared TWO variables with different scope. What a Powershell noob boner! It would never happen to you, right?
Kumquats. Beware. They make you do stuff.