采取以下脚本:
function Do-Test
{
# Do stuff here that relies on PS modules and variables loaded in my current session
Start-Sleep -Seconds 1
}
$scriptBlock = { Do-Test }
Write-Host "Invoking directly"
$scriptBlock.Invoke()
Write-Host "Invoking Via GetPowershell()"
$scriptBlock.GetPowershell().Invoke()
后者导致错误,指出它无法找到Do-Test
函数。有人可以解释为什么这不起作用吗?
答案 0 :(得分:0)
这不起作用,因为GetPowerShell()
创建了一个未定义Do-Test
函数的新运行空间。您需要在新的运行空间中定义该函数。你究竟想做什么?你可以这样做:
$ps = [powershell]::create()
[void]$ps.AddScript(@'
function Do-Test
{
# Do stuff here that relies on PS modules and variables loaded in my current session
Start-Sleep -Seconds 1
"Hello from $($MyInvocation.InvocationName)"
}
Do-Test
“@) $ ps.Invoke()