Search code examples
powershellasp.net-coreexchangewebservices

ASP.NET core 5 web api connect exchange via powershell script


In my asp.net core 5 project I want to execute the ps script below. This script can be executed in a native powershell without errors. And I can run simple ps scripts in my project context. But if I run this script via IIS Express (same machine as native powershell) then it thrwos the following error msg:

Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.

The msg belongs to the Import-PSSession command. How to run the script in asp.net core project context?

$Username = 'user'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass

$ExchangeFQDN = 'exchange.domain'
$ConnectionURI = "http://$($ExchangeFQDN)/powershell"
try{
    $mSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ConnectionURI -Credential $Cred -Authentication Kerberos
    Import-PSSession $mSession -DisableNameChecking
}catch{
    echo $_
}

Solution

  • After translating the script to c# commands as you can see below (the code snippet was adapted from here) I gpt the following error msg:

    System.Management.Automation.Remoting.PSRemotingDataStructureException HResult=0x80131501 Message = An error has occurred which PowerShell cannot handle. A remote session might have ended. ... Inner Exception 1: NotSupportedException: BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.

    And I found a solution for it here.

    <EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
    

    Just add the line above to your project file into section <PropertyGroup>.

            string username = @"domain\username";
            string password = "password";
            SecureString ssPassword = new SecureString();
            foreach (char x in password)
                ssPassword.AppendChar(x);
            PSCredential credentials = new PSCredential(username, ssPassword);
            var connInfo = new WSManConnectionInfo(new Uri(@"http://servername/powershell"), @"http://schemas.microsoft.com/powershell/Microsoft.Exchange", credentials);
            connInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
            connInfo.SkipCACheck = true;
            connInfo.SkipCNCheck = true;
    
            var runspace = RunspaceFactory.CreateRunspace(connInfo);
            runspace.Open();
            Pipeline plPileLine = runspace.CreatePipeline();
            Command smGetMailboxForward = new Command("get-mailbox");
            smGetMailboxForward.Parameters.Add("Identity", "john.doe");
            plPileLine.Commands.Add(smGetMailboxForward);
            Collection<PSObject> result = plPileLine.Invoke();
            plPileLine.Stop();
            runspace.Close();
            runspace.Dispose();