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!

3
  • 1
    The statement Write-Host getstate writes getstate. It will not call the function with that name Commented Feb 24, 2019 at 17:19
  • Curious... why cannot one call a function with write-host? Commented Feb 24, 2019 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 Commented Feb 24, 2019 at 21:52

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.