2

Basically what I want to do is:

Step 1) Invoke whatever.ps1 (or a scriptblock), the script is something like: $hello = "world"

Step 2) Invoke Get-Variable -name hello

Step 3) Retrieve the output of Get-Variable

I can't figure out how to do this cleanly, because every time I invoke a scriptblock a differente scope is created.

2 Answers 2

2

You have a couple of options. Easiest is to change the script if you can to:

$global:hello = "world"

However using globals is generally a bad practice. So another approach is to have your script output "Hello" and then capture the output the pipeline invocation. Just change your initial script to this:

"world"

Then invoke it and grab the output of pipeline.Invoke() and grab the first object.

You could also change the way you invoke the script. Pass in a string to CreatePipeline that looks like this:

$hello = foo.ps1 

Then retreive the contents of variable $hello.

Sign up to request clarification or add additional context in comments.

Comments

1

If you still want a global (the other answer covers this) you don't need to use Get-Variable from your host application.

Create a Runspace and execute the script.

You can then access variables from the runspace:

value = myRunspace.SessionStateProxy.GetVariable("name");

2 Comments

A limitation is that currently do not myRunspace.SessionStateProxy.GetVariable work on remote runspaces, it throws NewNotImplemented
Fastforward: not sure when this was finally implemented, but this command works in Powershell 5

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.