tags:

views:

433

answers:

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  A: 

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.

Keith Hill
+1  A: 

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");
Richard
A limitation is that currently do not myRunspace.SessionStateProxy.GetVariable work on remote runspaces, it throws NewNotImplemented
RA