Vik Vik - 8 months ago 92
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 {
("--$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

$newRunspace = [runspacefactory]::CreateRunspace($initialSessionState)
$newRunspace.ThreadOptions = "ReuseThread"
$newPowershell = [PowerShell]::Create()
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?


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()


Edit: Added an example.