如何从内部Powershell作业修改外部变量?
如果我有两个或多个start-job/start-threadjob
,如何共享它们之间的变量? 我想达到以下方案:
$a = 2
Start-ThreadJob -ScriptBlock { $a=$a+1 }
Start-ThreadJob -ScriptBlock {Start-Sleep -Seconds 1; Write-Host $a}
上面的脚本应输出3而不是2。
Powershell是否支持任何功能来修改工作中的外部变量?
If I have two or more Start-Job/Start-ThreadJob
, how do I share variables among them?
I want to achieve the below scenario:
$a = 2
Start-ThreadJob -ScriptBlock { $a=$a+1 }
Start-ThreadJob -ScriptBlock {Start-Sleep -Seconds 1; Write-Host $a}
The above script should output 3 instead of 2.
Does powershell support any functionality to modify outside variables from jobs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好的选择是使用所谓的环境变量。关于如何使用它们的漫长讨论是在“ hion_environment_variobles” 您可以通过遵循链接在线阅读。这也是PowerShell内部的帮助话题。
Windows以及其他作业都可以看到环境可变性中存储的信息。
Your best bet is to use what are called Environment Variables. The long discussion about how to use them is in Help About_Environment_Variables which you can read online by following the link. It's also a help topic inside Powershell.
Information stored in enviorment variaables is visible to windows as well as to other jobs.
我遇到了同样的问题,不幸的是,我无法使环境变量工作。 :(
我认为将值保存到文件可能会起作用,但我不能说我喜欢这个主意。一个更好的解决方案对我来说效果很好,是在运行脚本的用户注册表中保存价值。
但是,当我发现这个信息网站时,我的突破来了。使用 powershell .NET类时,我可以设置环境变量的范围。如果我使用默认范围“ 流程”,则无效。但是,当我使用“ user ”范围时,它像魅力一样工作:
结果正是我所需要的:
据我了解,Start-Job在另一个过程中运行;这就是为什么$ global:variablename或$ env:variablename不起作用。
I faced the same problem, and unfortunately, I couldn't get the environment variable to work. :(
I thought that saving the value to a file might work, but I can't say I liked that idea. A better solution that worked well for me was to save the value in the registry of the user running the script.
However, my breakthrough came when I found this informative site explaining Environmental Variables. When using the PowerShell .NET Class, I could set the scope of the environment variable. If I used the default scope "Process", it didn't work. But when I used the "User" scope, it worked like a charm, like this:
The result was exactly what I needed:
As I understand, Start-Job is running in a different process; that's why $global:variableName or $Env:variableName doesn't work.