Friday 8 February 2019

Powershell function return values


Recently came up against this problem in Powershell where the return value coming back from a function seemed strange. I spent some time debugging it and discovered that the results of commands are outputted from the function as well.

Take a look at the code below, notice that the match command results are returned as well. If we append Out-Null to one of them, it removes it from the return value.

function getCat {
  $result = "Meeow"
  
  "Cats Dogs Mice" -match "Mice"

  "Cats Dogs Mice" -match "C.ts?"

  return $result
}

PS /Users/kungfoowiz> $result = getCat
PS /Users/kungfoowiz> $result
True
True
Meeow

function getCat {
  $result = "Meeow"
  
  "Cats Dogs Mice" -match "Mice" | Out-Null

  "Cats Dogs Mice" -match "C.ts?"

  return $result
}

PS /Users/kungfoowiz> $result = getCat 
PS /Users/kungfoowiz> $result          
True                  
Meeow

The moral of the story, be careful of any commands that return a value:
chkdsk $drive

Instead assign them to a variable to prevent the return value being populated:
$result = chkdsk $drive

If you don't care about storing the value:
"Cats Dogs Mice" -match "Mice"

Just pipe the result to Out-Null:
"Cats Dogs Mice" -match "Mice" | Out-Null

No comments:

Post a Comment