問題描述
在同一範圍內從 c# 調用多個 powershell 命令 (Invoke multiple powershell commands from c# on the same scope)
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.
‑‑‑‑‑
參考解法
方法 1:
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.
方法 2:
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");
(by Edgardo Rossetto、Keith Hill、Richard)