【问题标题】:Executing scripts with Powershell via C#通过 C# 使用 Powershell 执行脚本
【发布时间】:2012-08-03 07:28:11
【问题描述】:

我需要执行以下脚本: Get-MailboxDatabase -Status |选择服务器名称、名称、数据库大小

我尝试了一些使用 Powershell 和 Command 类的解决方案,但它们不起作用。 我收到的错误: 值参数不能为空。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我认为这会满足您的需求:

    private string RunLocalExchangePowerShell(string script)
    {
        // create the runspace and load the snapin
        RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
        PSSnapInException snapInException = null;
        Runspace runSpace = RunspaceFactory.CreateRunspace(rsConfig);
        runSpace.Open();
        rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
        Pipeline pipeLine = runSpace.CreatePipeline();
    
        // load the script and convert the output to a string
        pipeLine.Commands.AddScript(script);
        pipeLine.Commands.Add("out-string");
    
        // get the results
        Collection<PSObject> results;
        results = pipeLine.Invoke();
    
        // loop through the results and build the output
        StringBuilder sb = new StringBuilder();
        foreach (PSObject obj in results)
        {
            sb.AppendLine(obj.ToString());
        }
    
        // close the pipeline and runspace
        pipeLine.Dispose();
        runSpace.Close();
    
        return sb.ToString();
    }
    

    示例用法:

    Console.WriteLine(prog.RunLocalExchangePowerShell("Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize"));
    

    【讨论】:

    • 你是如何初始化 psExec 变量的?
    • @TimurYaroshenko 抱歉,我已经编辑了上面的内容并进行了测试。
    猜你喜欢
    • 2023-03-10
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2020-08-12
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多