1

I'm trying to create a Function on my module that will create a PsSession and to import it to my console. The script block itself is ok, but after running the cmdlet, I cannot import the PsSession although the function imports it.

Function ConnectTo-Office365 {
[cmdletbinding()]

$365Credential = Get-Credential -Message "Office365 Credentials";
$365Session = New-PSSession -ConfigurationName Microsoft.Exchange ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $365Credential -Authentication  Basic -AllowRedirection;
Import-PSSession $365Session}

I've read on Global Variables but could not understand how to use it to my purpose.

Thanks!

3
  • Does using $Global:365Session = New-PSSession -ConfigurationName Microsoft.Exchange ConnectionUri outlook.office365.com/powershell-liveid -Credential $365Credential -Authentication Basic -AllowRedirection; Import-PSSession $365Session} have any affect on your function? Commented Mar 19, 2019 at 12:50
  • Possible duplicate of Import-PsSession not available after function completes Commented Mar 19, 2019 at 12:51
  • Using $Global:Sessin did get me the session variable! Commented Mar 20, 2019 at 21:33

1 Answer 1

1

You don't need to use a global variable.

Function ConnectTo-Office365 {
  [cmdletbinding()]
  Param (
    $Credential = (Get-Credential -Message "Office365 Credentials")
  )

  $Session = New-PSSession -ConfigurationName Microsoft.Exchange ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $Credential -Authentication  Basic -AllowRedirection

  Return $Session
}

PS> Import-PSSession (ConnectTo-Office365)

PS> Import-PSSession (ConnectTo-Office356 -Credential $Cred)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.