如何在 PowerShell 中将运行空间与字符串变量列表中的命令配合使用

How to use runspaces in PowerShell with commands in a list of strings variable

提问人:davidprogrammercdn 提问时间:9/5/2023 最后编辑:Santiago Squarzondavidprogrammercdn 更新时间:9/5/2023 访问量:51

问:

如何从字符串列表中循环命令以在 PowerShell 中使用 RunSpaces。

这是我正在处理的一个项目的代码。

它适用于普通命令,但我认为它部分不适用于以下命令。 是一个字符串变量,其中包含带有开关参数的命令,有时如下所示:[void]$PowerShell.AddScript$singlefunctionCleanUp -All

iex -Command $singlefunction

代码如下

# Loop for runspaces
foreach ($singlefunction in $listoffunctions)
{
    $PowerShell = [PowerShell]::Create() 
    $PowerShell.RunspacePool = $RunspacePool

    [void]$PowerShell.AddScript({       
        iex -Command $singlefunction
    })
    
    ## start runspace asynchronously so that it does not block this loop
    $handle = $PowerShell.BeginInvoke()

    # Create job
    $job = [pscustomobject]@{ 
        PowerShell = $PowerShell
        Handle = $handle
    }

    # Add first runspace to job list
    $jobs.Add( $job )

}

这些函数通过以下方式添加到初始会话状态:

ForEach($function in $scriptFunctions)
{
    $Definition = $null
    $Definition = Get-Content -Path Function:\$function -ErrorAction Continue
    if( $Definition )
    {
        $SessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList $function , $Definition
        $SessionState.Commands.Add( $SessionStateFunction )     
    }
}
list PowerShell 循环 命令 运行空间

评论


答:

1赞 Santiago Squarzon 9/5/2023 #1

根据猜测,问题的原因是您没有将参数作为参数传递到运行空间:$singlefunction

[void] $PowerShell.AddScript({
    # `$singlefunction` does not exist in this context
    Invoke-Expression -Command $singlefunction
})

如果要将该字符串作为参数传递给,可以使用 .AddArgument.AddParameter.AddParametersInvoke-Expression

例如:

[void] $PowerShell.AddScript({
    Invoke-Expression -Command $args[0]
}).AddArgument($singlefunction)

但是,如果您的意图是执行该字符串中的表达式,则此方法只是过于复杂。AddScript 采用一个字符串,该字符串将被计算为表达式,解决问题可能很简单:

[void] $PowerShell.AddScript($singlefunction)

演示:

using namespace System.Management.Automation.Runspaces

$cleanUpFunc = {
    param([switch] $All, $Foo, $Bar)

    "Called '$($MyInvocation.MyCommand.Name)' with parameters:",
    $PSBoundParameters
}

$iss = [initialsessionstate]::CreateDefault2()
$iss.Commands.Add([SessionStateFunctionEntry]::new(
        'CleanUp', $cleanUpFunc))

$singlefunction = 'CleanUp -All -Foo Hello -Bar World'
$rs = [runspacefactory]::CreateRunspace($iss)
$rs.Open()

$PowerShell = [PowerShell]::Create().
    AddScript($singlefunction)
$PowerShell.Runspace = $rs
$PowerShell.Invoke()

# Outputs:
#
# Called 'CleanUp' with parameters:
#
# Key Value
# --- -----
# All True
# Foo Hello
# Bar World

评论

1赞 davidprogrammercdn 9/5/2023
[void] $PowerShell.AddScript($singlefunction)这就是我需要的。谢谢!