Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import-PsSession not available after function completes

Tags:

powershell

I have a function which creates a remote PS Session. I then import the session and all exported commands are available to other functions while the code runs. When the function completes there is an 'available' PS Session however none of the exported commands are available afterward. Here is an example:

Function DoSomething{
    $lyncsession = New-CsOnlineSession -Credential (Get-Credential -Message "Authenticate to Skype for Business Online")
    $remoteSession = Import-PSSession $lyncsession -AllowClobber | Out-Null
}

If I want to run the function again I need to tear down the old PSSession and create a new one (authenticating all over again).

Is there a way to create a PSSession within a function and make the exported cmdlets available when the function is done?

By the way, this isn't an issue if I run the commands outside a function.

like image 319
Jason Shave Avatar asked Feb 28 '26 05:02

Jason Shave


1 Answers

If you want a function or script to run in the scope of your session you can dot source it. This will place the variables in the current scope, otherwise as you noted they will be in the function scope and be unavailable after the function completes.

. DoSomething

Otherwise you can manually scope your variables inside the function to be in a different scope. Examples scoping into global and scripts scopes

Function DoSomething{
    $script:lyncsession = New-CsOnlineSession -Credential (Get-Credential -Message "Authenticate to Skype for Business Online")
    $global:remoteSession = Import-PSSession $lyncsession -AllowClobber | Out-Null
}
like image 151
BenH Avatar answered Mar 02 '26 18:03

BenH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!