2017-08-09 21 views
0

我目前正在研究从SQL表中提取任务并执行PowerShell脚本的应用程序。我想在开始时运行一个SetUP.ps1来设置像工作目录等变量,最后还要清理一个tearDown.ps1每个运行空间的设置环境

目前我使用:

Using myRunSpace = RunspaceFactory.CreateRunspace 
    myRunSpace.Open() 

    Using ps = PowerShell.Create 
    ps.Runspace = myRunSpace 
    ps.AddScript("Set-ExecutionPolicy -Scope Process RemoteSigned") 
    ps.Invoke() 
    End Using 


    Using ps = PowerShell.Create 
    ps.Runspace = myRunSpace 
    ps.AddScript(Application.StartupPath & "\SetUp.ps1") 
    ps.Invoke() 
    End Using 

    Using ps = PowerShell.Create 
    ps.Runspace = myRunSpace 
    ps.AddScript(task.Script) 
    ReturnValue = PSSerializer.Serialize(ps.Invoke()) 
    End Using 

    Using ps = PowerShell.Create 
    ps.Runspace = myRunSpace 
    ps.AddScript(Application.StartupPath & "\TearDown.ps1") 
    ps.Invoke() 
    End Using 
End Using 

Setup.ps1我当前做:

$env:test = Get-Random 

当我现在用片段作为代码上面运行多线程代码:

Start-Sleep 10; $env:test 

然后所有运行给我相同的价值。 $env:test在每次运行中都是相同的。有什么办法可以将$env:test的范围限制在这一个运行空间吗?

+2

是什么原因为什么你使用环境而不是标准的PowerShell变量? – PetSerAl

回答

0

我认为这是你想完成的事情:让一个线程将随机值写入环境变量,另一个线程读取它?

Remove-Item c:\test.out -force 
Remove-Item Env:\test 
$testfile = "c:\test.out" 

$myRunSpace = [RunspaceFactory]::CreateRunspace() 
$myRunSpace.Open() 

$ps1 = [PowerShell]::Create() 
$ps1.Runspace = $myRunSpace 
$ps1.AddScript("`$env:test = Get-Random") 


$ps1.Invoke() 

$ps2 = [PowerShell]::Create() 
$ps2.Runspace = $myRunSpace 
$ps2.AddScript("Start-Sleep -Seconds 1") 
$ps2.AddScript("`$env:test | Out-File $testfile") 
$ps2.Invoke() 

start-sleep 2 
"variable set to: $env:test" 
"file reads: " + (Get-Content $testfile)