0

Before posting, I looked at PowerShell function doesn't produce output and Function not Returning Data both links didn't help.

I have a function named getState. When I call it, nothing is returned. When I run the debugger, I can see the var $state getting set with "foo" but the getter doesn't return the value of $state.

Here's the code:

$Global:state

function setState {
  param(
    [string]$s
  )
  $state = $s
}

function getState {
  return $state
}

setState ("foo")

Write-host getState

How can I get the line Write-host getState to show foo? Thanks!

MGoBlue93
  • 644
  • 2
  • 14
  • 31
  • 1
    The statement `Write-Host getstate` writes getstate. It will not call the function with that name – Gert Jan Kraaijeveld Feb 24 '19 at 17:19
  • Curious... why cannot one call a function with write-host? – MGoBlue93 Feb 24 '19 at 20:18
  • 1
    It is possible: place the function call between parentheses: `Write-Host (getstate)`. Then `getstate` is interpreted first, as function call, and the return value of the function is used as parameter for Write-Host. Without the parentheses `getstate` is just a string parameter for Write-Host – Gert Jan Kraaijeveld Feb 24 '19 at 21:52

1 Answers1

2

If you want to be sure the global var is used in the functions, specify it as global.

Try this:

$Global:state = $null

function setState {
  param(
    [string]$s
  )
  $Global:state = $s
}

function getState {
  return $Global:state
}

setState ("foo")

getState