title: Powershell script not running or giving and output
body: <p>I am running the following code with a script that is supposed to change User Principal Names for our Outlook accounts when an employee gets a name change.</p>
  
  <p>The code takes about 30-60 seconds to run when I call <code>ps.Invoke()</code>, then when I inspect the <code>results</code> variable in the debugger it only contains an empty list. I then check to see if the account UPN got changed and it hasn't. However, if I copy and paste the script string in a powershell window, it executes and works just fine.</p>
  
  <p>Does anyone have any ideas?</p>
  
  <h2>The C# code:</h2>
  
  <pre><code>public bool RenameOutlookAccount(string originalEmail, string newEmail)
  {
      bool result = false;
  
      try
      {
          // Set up credentials
          string username = _config.AppSettings.Settings["PowershellUser"].Value;
          string password = _config.AppSettings.Settings["PowershellPassword"].Value;
  
          // Create the PowerShell object
          PowerShell ps = PowerShell.Create();
  
          // Add the script
          string script = String.Format(@"$secpasswd = ConvertTo-SecureString ""{0}"" -AsPlainText -Force; $Cred = New-Object System.Management.Automation.PSCredential (""{1}"", $secpasswd); $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection; Import-PSSession $Session; Import-Module Msonline; Connect-MsolService -Credential $Cred; Set-MsolUserPrincipalName -UserPrincipalName {2} -NewUserPrincipalName {3}; Remove-PSSession $Session", password, username, originalEmail, newEmail);
          ps.AddScript(script);
  
          // Run
          var results = ps.Invoke();
  
          result = true;
      }
      catch (Exception ex)
      {
          result = false;
      }
  
      return result;
  }
  </code></pre>
  
  <h2>The (formatted) powershell command I am running:</h2>
  
  <pre><code>$secpasswd = ConvertTo-SecureString {password} -AsPlainText -Force
  
  $Cred = New-Object System.Management.Automation.PSCredential ({username}, $secpasswd)
  
  $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
  
  Import-PSSession $Session
  
  Import-Module Msonline
  
  Connect-MsolService -Credential $Cred
  
  Set-MsolUserPrincipalName -UserPrincipalName {oldUPN} -NewUserPrincipalName {newUPN}
  
  Remove-PSSession $Session
  </code></pre>