Vik Vik - 4 months ago 42
PowerShell Question

How to define a function in a Powershell runspace and execute it

I'would like to define a function in a powershell and execute it in a different runspace.
I tried this:

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


The message "New runspace" does not appear in the file test.log
Any advice to do something like this?
Thanks

Answer

Use the CreateDefault method instead of Create when you're creating your initial session state. If you don't you have a lot more to configure to make that session state viable.

$initialSessionState = [InitialSessionState]::CreateDefault()

Chris

Edit: Added an example.