2016-08-04 73 views
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中 任何意見,做這樣的事情? 謝謝

+0

這是我試圖避免的。我創建了很多運行空間,並且不想多執行一次該功能。 – Vik

回答

0

當您創建初始會話狀態時,請使用CreateDefault方法而不是Create。如果你沒有更多的配置來使會話狀態可行。

$initialSessionState = [InitialSessionState]::CreateDefault() 

克里斯

編輯:添加了一個例子。

+0

就是這樣。它適用於CreateDefault。謝謝! – Vik

相關問題