如何在Powershell运行空间中定义函数并执行它

如何在Powershell运行空间中定义函数并执行它,powershell,runspace,Powershell,Runspace,我想在powershell中定义一个函数,并在不同的运行空间中执行它。 我试过这个: Function Add-Message { param( [parameter(mandatory=$true)][String]$pMessage ) ("--$pMessage--") | Out-File -FilePath "D:\Temp\test.log" -Append } $initialSessionState = [System

我想在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” 这样做有什么建议吗?
谢谢

在创建初始会话状态时,请使用CreateDefault方法而不是Create。如果您没有,您还有很多要配置的,以使会话状态可行

$initialSessionState = [InitialSessionState]::CreateDefault()
克里斯


编辑:添加了一个示例。

这是我试图避免的。我创建了很多运行空间,不想再实现一次该函数