gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:41:15 25 4
gpt4 key购买 nike

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

最佳答案

在创建初始 session 状态时,请使用 CreateDefault 方法而不是 Create。如果不这样做,则需要进行更多配置才能使 session 状态可行。

$initialSessionState = [InitialSessionState]::CreateDefault()

克里斯

编辑:添加了一个示例。

关于powershell - 如何在 Powershell 运行空间中定义函数并执行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38761670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com