title: powershell session connection cmdlets not work when executed in function
body: <p>I get connected to Exchange in the cloud by issuing a series of powershell commands:</p>
  
  <pre><code>$credential = new-object -typename ... -argumentList ...
  $session = New-PSSession -configurationName ... -connectionUri ... -credential $credential ...
  Import-PSSession $session ...
  </code></pre>
  
  <p>I can then issue commands to do things I need to do, e.g.,</p>
  
  <pre><code>get-mailbox | ? {$_.aliast -like "*[.]*"} | select alias
  
  alias
  -----
  john.public
  jane.doe
  ...
  </code></pre>
  
  <p>However, the cmdlets for obtaining a PSSession are long, and typing them is error-prone even if I could manage to memorize them correctly.  So I saved all the three long command lines verbatim in a function:</p>
  
  <pre><code>function get-365session() {
     $credential = new-object -typename ... -argumentList ...
     $session = New-PSSession -configurationName ... -connectionUri ... -credential $credential ...
     Import-PSSession $session ...
  }
  </code></pre>
  
  <p>But it does not work out as expected:</p>
  
  <pre><code>PS&gt; get-365session
  ModuleType Version    Name             ExportedCommands
  ---------- -------    ----             -----------------
  ...
  
  PS&gt; get-mailbox 
  get-mailbox: The term 'get-mailbox' is not recognized as the name of a cmdlt, function, script file, ....
  </code></pre>
  
  <p>I thought the session was obtained but was gone with the function's "sub-shell" as soon as the function has completed its run.  I therefore tried </p>
  
  <pre><code>PS&gt; . get-365session
  </code></pre>
  
  <p>But it was to no avail.</p>
  
  <p>Hope there is a way and someone can help me out.  Many thanks!</p>