PSSession Termination

This topic contains 13 replies, has 3 voices, and was last updated by Profile photo of Stuart Stuart 3 days, 18 hours ago.

  • Author
    Posts
  • #66555
    Profile photo of Stuart
    Stuart
    Participant

    Hi Guys,

    I have a module with about 6 functions in it. They either call 365 PS or on premise Exchange PS sessions or both.

    I cant see a way to make sure that:

    a) The previous sessions is fully terminated
    b) The old session is revived and used if there, if not a new one established.

    I would prefer to get option b working, then dont have to reload commandlets each time to function is run. Here are two examples of what I have tried:

        Get-PSSession | Remove-PSSession
        $password=get-content "C:\scripts\HMHpw.txt" | ConvertTo-SecureString
        $userid=''
        $UserCredential=New-Object System.Management.Automation.PSCredential $userid,$password
        Import-Module MSOnline
        $O365Cred = Get-Credential
        $O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $UserCredential -Authentication Basic -AllowRedirection
        Import-PSSession $O365Session
        Connect-MsolService –Credential $UserCredential
    

    Also tried above but with this:

    if(Get-PsSession){ } else { #checks if a session is already active!
    $password=get-content C:\scripts\EXpassword.txt | ConvertTo-SecureString
    $userid=''
    $UserCredential=New-Object System.Management.Automation.PSCredential $userid,$password
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http:///PowerShell/ -Authentication Kerberos -Credential $UserCredential
    Import-PSSession $Session
    } # Close PS Session checker
    

    So either get-pssession | remove-pssession at the start or a if to check if a session exists. Neither work well at all.

    Any advice appreciated

    Thanks

  • #66601
    Profile photo of Sam Boutros
    Sam Boutros
    Participant

    Due to an uptick in spam posts, your post or reply may be held for moderation, which can take 24-48 hours. If your post does not show up immediately, please do not re-post – we appreciate your patience.

  • #66667
    Profile photo of Stuart
    Stuart
    Participant

    Can this be approved please

  • #66685
    Profile photo of Stuart
    Stuart
    Participant

    Found this post which answered it:

    THnaks

  • #66598
    Profile photo of Sam Boutros
    Sam Boutros
    Participant

    Stuart,

    First, I would not save passwords in plain text files. I use this function to save passwords in encrypted format – see this blog post for more details.

    I would test for open exchange session as in:

    $Session = Get-PSSession | ? { $_.ConfigurationName -eq 'Microsoft.Exchange' }
    if ($Session.State -eq 'Opened') {
        "Using existing PS session $($Session | Out-String)"
    } else {
        $Session | Remove-PSSession -ErrorAction SilentlyContinue 
        $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http:///PowerShell/ -Authentication Kerberos -Credential $UserCredential
        Import-PSSession $Session -AllowClobber -DisableNameChecking
        "Opened new PS Session $($Session | Out-String)"
    }
    
  • #66853
    Profile photo of Stuart
    Stuart
    Participant

    HI, the passwords are encrypted not saved in plain text. I use this to save the passwords securely:

    Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File "C:\scripts\EXpassword.txt"

    I have found the link I suggested above to be less than satisfactory. I will try your suggestion now, thank you

  • #66933
    Profile photo of Stuart
    Stuart
    Participant

    This does not work

  • #66936
    Profile photo of Stuart
    Stuart
    Participant

    The logic works to some extent (although not if no session exists at all). if not session exists at all, then $Session is null.

    This causes an error on line 5. I have fixed that, but makes me wonder if you have tested this code?

    So once that issue is sorted (added in another IF statement), if there is an existing 'open' session, it tries to use it, but just fails to pickup the session.

    Then the script says, no command found get-mailbox or similar.

    Any ideas? I am in the middle of a large migration and this is just giving me grey hairs. I have to close ISE every dam time and re-open it.

    If you can help I would be v grateful (I posted yesterday on this thread but got blocked by spam, took me ages to type it out, I was thrilled).

  • #66954
    Profile photo of Dudebro
    Dudebro
    Participant

    Not sure what you mean when you say that it fails to pick up the session, but maybe your $Session variable ends up containing more than one session? The following example will make sure there's only one session:

    $Sessions = @( Get-PSSession | Where-Object {
        ( $_.ConfigurationName -EQ 'Microsoft.Exchange' ) -AND ( $_.State -EQ 'Opened' ) } )
    
    If ( $Sessions )
    {
        If ( $Sessions.Count -GT 1 )
        {
            $Session   = $Sessions | Select-Object -First 1
            $LeftOvers = $Sessions | Where-Object { -Not ( $_.Id -EQ $Session.Id ) }
            $LeftOvers | Remove-PSSession -ErrorAction SilentlyContinue | Out-Null
        }
    
        Else { $Session = $Sessions }
    }
    
    Else
    {
        # Create new session.
    }
    
    $Session # Use this.
    
  • #66976
    Profile photo of Stuart
    Stuart
    Participant

    Hi,

    Thanks for this, still doesnt fully work:

    
    $Sessions = @( Get-PSSession | Where-Object {
        ( $_.computername -EQ $ComputerName ) -AND ( $_.State -EQ 'Opened' ) } )
    
        If ( $Sessions )
        {
        If ( $Sessions.Count -GT 1 )
        {
            $Session   = $Sessions | Select-Object -First 1
            $LeftOvers = $Sessions | Where-Object { -Not ( $_.Id -EQ $Session.Id ) }
            $LeftOvers | Remove-PSSession -ErrorAction SilentlyContinue | Out-Null
        }
    
        Else { $Session = $Sessions }
        }
        Else
        {
        # Create new session.
        }
    
        $Session # Use this.
    
    

    It fails to loads to commandlets 'sometimes':

    Get-RemoteMailbox : The term 'Get-RemoteMailbox' is not recognized as the name of a cmdlet, function, 
  • #66979
    Profile photo of Stuart
    Stuart
    Participant

    This is how I call the session:

    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://servernamehere/PowerShell/ -Authentication Kerberos -Credential $UserCredential # Create new session.
    

    Then followed by:

     Import-PSSession $Session # Use this.

    I think its the last line that is the problem. Should I be using enter-pssession at this stage? I want to make sure the open session.

  • #66981
    Profile photo of Stuart
    Stuart
    Participant

    Tried:

    Get-PSSession $Computername | Connect-PSSession

    or

    Get-PSsession $session | enter-pssession

    Nothing seems to let you connect into the 'open' session.

    If I do Get-Pssession I can see its there, its open, why cant I run the commandlets associated to the open session?

  • #66984
    Profile photo of Stuart
    Stuart
    Participant
    Import-PSSession $Session # Use this.

    This doesnt work because the $session is a array.object instead of a system.object.

    How do I convert or deal with that?

  • #66987
    Profile photo of Stuart
    Stuart
    Participant

    Figured it out:

    Import-PSSession $Session[0]

You must be logged in to reply to this topic.