在C#脚本中执行PowerShell cmdlet

loading...


0

我想用C#连接交换并返回特定用户的邮箱列表 . 我能够在PowerShell中本地运行它,但是在脚本的上下文中它没有显示我的期望 .

我看到的输出如tmp_1qf14mc3.wiv或tmp_ra1gbenl.ols而不是邮箱列表 .

Additional notes:

  • 我已经设置了对System.Management.Automation的名称空间的引用和导入;

  • 我是通过Visual Studio 2017使用IIS Express构建运行的

  • 这使用.NET Core API项目

.

using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            // Attempt to get the mailbox listing for the user
            PowerShellInstance.AddScript(
                "$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList " + user + ",(ConvertTo-SecureString -String " + pass + " -AsPlainText -Force); " +
                "$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $credential -Authentication Basic -AllowRedirection; " +
                "Import-PSSession $Session -DisableNameChecking; " +
                "Get-Mailbox; " +
                "Remove-PSSession $Session");

            // Invoke execution to collect the output
            Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

            // Go through each output returned
            foreach (PSObject outputItem in PSOutput)
            {
                // Dump the output to see what's coming out.
                if (outputItem != null)
                {
                    return new string[] { outputItem.ToString() };
                }
            }
        }

        return new string[] { "Did not get a powershell outputItem" };

loading...

0回答

No Data

评论

暂时没有评论!