Search code examples
c#powershelloffice365lync-2013skype-for-business

Getting error when trying to run powershell script from C#


I have a powershell script that runs fine when run in powershell but throws error when trying to run from c#. The powershell script is trying to connect to lync online(skype for business) and list lync online users.

Here is the code that calls powershell script from c#

        public static void ImportLyncUsers()
    {

        RunspaceConfiguration config = RunspaceConfiguration.Create();
        using (Runspace myRs = RunspaceFactory.CreateRunspace(config))
        {
            myRs.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(myRs);
            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

            using (PowerShell powerShellInstance = PowerShell.Create())
            {
                powerShellInstance.Runspace = myRs;

                // Import module.
                powerShellInstance.Commands.AddCommand("Import-Module")
                    .AddArgument(
                        @"C:\Program Files\Common Files\Microsoft Lync Server 2013\Modules\LyncOnlineConnector\LyncOnlineConnector.psd1");
                powerShellInstance.Invoke();
                powerShellInstance.Commands.Clear();
                var filePath = @"F:\PresensoftNewTrunk\Trunk\Lync Archiver\Exchange\Scripts\ImportUsers.ps1";
                powerShellInstance.Commands.AddScript(System.IO.File.ReadAllText(filePath));


                Collection<PSObject> psOutput = powerShellInstance.Invoke(); //Getting exception here.

                // check the other output streams (for example, the error stream)
                if (powerShellInstance.Streams.Error.Count > 0)
                {
                    // error records were written to the error stream.
                    // do something with the items found.
                }
            }
        }

    }

Here is the error which i am getting when trying to run ps script from c#.

Message        : Object reference not set to an instance of an object.
Data           : {}
InnerException : 
TargetSite     : Void .ctor(IDCRLMode)
StackTrace     :    at Microsoft.Rtc.Admin.Authentication.ManagedIdcrl..ctor(IDC
                 RLMode mode)
                    at Microsoft.Rtc.Admin.Authentication.ManagedIdcrl..ctor()
                    at Microsoft.Rtc.Management.LyncOnlineConnector.GetWebTicket
                 Cmdlet.CreateAndInitializeManagedIdcrl()
                    at Microsoft.Rtc.Management.LyncOnlineConnector.GetWebTicket
                 Cmdlet.get_ManagedIdcrl()
                    at Microsoft.Rtc.Management.LyncOnlineConnector.GetWebTicket
                 Cmdlet.GetLiveIdToken(String remoteFqdn, Int32 port, 
                 PSCredential creds)
                    at Microsoft.Rtc.Management.LyncOnlineConnector.GetWebTicket
                 Cmdlet.ConnectToWebTicketService(String fqdn, Int32 port, 
                 PSCredential creds)
                    at Microsoft.Rtc.Management.LyncOnlineConnector.GetWebTicket
                 Cmdlet.BeginProcessing()
                    at System.Management.Automation.Cmdlet.DoBeginProcessing()
                    at 
                 System.Management.Automation.CommandProcessorBase.DoBegin()
HelpLink       : 
Source         : Microsoft.Rtc.Admin.AuthenticationHelper
HResult        : -2147467261

And here is the part of ps script

 $secpasswd = New-Object -TypeName System.Security.SecureString
    $password = [LyncFoundation.Helpers.StringHelper]::Decrypt($exchangeServer.Password);
    $password.ToCharArray() | ForEach-Object { $secpasswd.AppendChar($_) }
    $cred = New-Object System.Management.Automation.PSCredential ($exchangeServer.UserName,$secpasswd)

    #Get Lync Users
    Import-Module LyncOnlineConnector
    try{
    $CSSession = New-CsOnlineSession -Credential $cred
    }
    catch [System.Net.WebException]{

        if ($_.Exception.Message.Contains("Unable to query AutoDiscover")){
            $CSSession = New-CsOnlineSession -Credential $cred -OverridePowershellUri https://admin0a.online.lync.com/OcsPowershellLiveId
        }
        else{
          throw $_.Exception
        }
    }

I am wondering as to why the script runs smoothly when directly executed from powershell but gives me the error when trying to call from c#. What kind of environment do i need to set up to pass through this error?


Solution

  • The code looks OK. I faced a similar issue and since Lync Online from PowerShell is 64-bit you must compile for that platform instead of the default Any CPU.