1
我想要在powershell中定義一個函數並在不同的運行空間中執行它。 我嘗試這樣做:如何在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中 任何意見,做這樣的事情? 謝謝
這是我試圖避免的。我創建了很多運行空間,並且不想多執行一次該功能。 – Vik