2016-08-04 10 views
1

powershell에서 함수를 정의하고 다른 runspace에서 실행하고 싶습니다. 나는이 시도 :Powershell runspace에서 함수를 정의하고 실행하는 방법

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

이렇게하면 피하려고합니다. 나는 많은 runspace를 생성하고 더 많은 함수를 구현하기를 원하지 않는다. – Vik

답변

0

초기 세션 상태를 만들 때 만들기 대신 CreateDefault 메서드를 사용하십시오. 그렇지 않은 경우 해당 세션 상태를 실행 가능하게 만들기 위해 더 많은 것을 구성해야합니다.

$initialSessionState = [InitialSessionState]::CreateDefault() 

크리스

편집 : 예를 추가했습니다.

+0

그 것이다. 그것은 CreateDefault와 함께 작동합니다. 감사! – Vik