如何在另一个会话中使用来自一个会话(Powershell ISE选项卡)的变量?
这是我试图实现的一个基本代码如何在另一个会话中使用来自一个会话(Powershell ISE选项卡)的变量?,powershell,scope,command-prompt,powershell-ise,Powershell,Scope,Command Prompt,Powershell Ise,这是我试图实现的一个基本代码 $destinationDir = "subdir1" #creating tab $newTab = $psise.PowerShellTabs.Add() Do {sleep -m 100} While (!$newTab.CanInvoke) #running required script in tab $newTab.Invoke({ cd $destinationDir}) 由于$destinationDir是在父选项卡
$destinationDir = "subdir1"
#creating tab
$newTab = $psise.PowerShellTabs.Add()
Do
{sleep -m 100}
While (!$newTab.CanInvoke)
#running required script in tab
$newTab.Invoke({ cd $destinationDir})
由于$destinationDir是在父选项卡中初始化的,所以它的作用域仅限于此,我在子选项卡中得到以下错误
cd : Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.
如何克服这个问题并使用子选项卡中的值?简短回答:你不能。PowerShell ISE中的每个选项卡都创建了一个新的运行空间。没有提供将变量注入此运行空间的方法 长话短说:总有解决办法。这里有两个 1。使用invoke脚本块将变量传输到新的运行空间:
$destinationDir = "subdir1"
#creating tab
$newTab = $psise.PowerShellTabs.Add()
Do
{sleep -m 100}
While (!$newTab.CanInvoke)
$scriptblock = "`$destinationDir = `"$($destinationDir)`"
cd `$destinationDir"
#running required script in tab
$newTab.Invoke($scriptblock)
$env:destinationDir = "subdir1"
#creating tab
$newTab = $psise.PowerShellTabs.Add()
Do
{sleep -m 100}
While (!$newTab.CanInvoke)
#running required script in tab
$newTab.Invoke({ cd $env:destinationDir})
2。使用环境变量:
$destinationDir = "subdir1"
#creating tab
$newTab = $psise.PowerShellTabs.Add()
Do
{sleep -m 100}
While (!$newTab.CanInvoke)
$scriptblock = "`$destinationDir = `"$($destinationDir)`"
cd `$destinationDir"
#running required script in tab
$newTab.Invoke($scriptblock)
$env:destinationDir = "subdir1"
#creating tab
$newTab = $psise.PowerShellTabs.Add()
Do
{sleep -m 100}
While (!$newTab.CanInvoke)
#running required script in tab
$newTab.Invoke({ cd $env:destinationDir})
谢谢正是我需要的。您能否解释一下为什么使用
$($destinationDir)
?@SatheeshJM将表达式括在括号中,并在括号前加上美元符号“$(..”),这是一种PowerShell方法,可确保对所括表达式进行求值。有时,在字符串中,变量的计算不正确。特别是当字符串包含特殊字符时。这是一个权力地狱的东西。。。