试图从c#运行powershell脚本时出现错误

本文关键字:错误 脚本 powershell 运行 | 更新日期: 2023-09-27 17:50:32

我有一个powershell脚本,在powershell中运行时运行良好,但在尝试从c#运行时抛出错误。powershell脚本正在尝试连接到lync online(skype for business)并列出lync online用户。

下面是从c# 调用powershell脚本的代码
        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.
                }
            }
        }
    }

这是我试图从c#运行ps脚本时得到的错误。

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

这里是ps脚本的一部分

 $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
        }
    }

我想知道为什么脚本运行顺利时,直接从powershell执行,但给我错误时,试图从c#调用。我需要设置什么样的环境来通过这个错误?

试图从c#运行powershell脚本时出现错误

代码看起来不错。我遇到了一个类似的问题和,因为来自PowerShell的Lync Online是64位的,你必须编译该平台而不是默认的Any CPU。