【问题标题】:How to define a function in a Powershell runspace and execute it如何在 Powershell 运行空间中定义函数并执行它
【发布时间】:2016-08-04 08:00:21
【问题描述】:

我想在 powershell 中定义一个函数并在不同的运行空间中执行它。 我试过这个:

Function Add-Message {
    param(
    [parameter(mandatory=$true)][String]$pMessage
    )   
    ("--$pMessage--") | Out-File -FilePath "D:\Temp\test.log" -Append           
}

$initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::Create()
$definition = Get-Content Function:\Add-Message -ErrorAction Stop   
$addMessageSessionStateFunction = New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList 'Add-Message', $definition
$initialSessionState.Commands.Add($addMessageSessionStateFunction)

$newRunspace = [runspacefactory]::CreateRunspace($initialSessionState)
$newRunspace.ThreadOptions = "ReuseThread"  
$newRunspace.Open()
$newPowershell = [PowerShell]::Create()
$newPowershell.AddScript({  
    Add-Message -pMessage "New runspace"
}) | Out-Null
$newPowershell.Runspace = $newRunspace
$newPowershell.BeginInvoke() | Out-Null

文件 test.log 中未出现消息“New runspace” 有什么建议可以做这样的事情吗? 谢谢

【问题讨论】:

  • 这是我尽量避免的。我创建了很多运行空间,不想多次实现该功能

标签: powershell runspace


【解决方案1】:

在创建初始会话状态时,使用 CreateDefault 方法而不是 Create。如果您不这样做,您需要进行更多配置以使该会话状态可行。

$initialSessionState = [InitialSessionState]::CreateDefault()

克里斯

编辑:添加了一个示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-29
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多