Jason Shave
Jason Shave

Reputation: 2672

Import-PsSession not available after function completes

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.

Upvotes: 3

Views: 904

Answers (3)

kodean
kodean

Reputation: 1

This is how it should work

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

    if ( $remoteSession ) { return Import-Module -Global $remoteSession }
}

Upvotes: 0

Jason Shave
Jason Shave

Reputation: 2672

Defining a global variable doesn't solve this one. I had to simply re-import the PSSession (if it's healthy and usable).

Upvotes: 1

BenH
BenH

Reputation: 10044

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
}

Upvotes: 1

Related Questions