Import-PsSession not available after function completes

Viewed 683

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.

3 Answers

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 }
}
Related