簡體   English   中英

如何從C#中啟動的Powershell腳本塊獲取返回值

[英]How to get the return value from a powershell scriptblock started in c#

我嘗試從以C#中的新Process開始的Powershell腳本塊中獲取返回值。

    Process powershellProcess = null;
try
{
    powershellProcess = new Process();
    powershellProcess.StartInfo.FileName = "powershell.exe";
    powershellProcess.StartInfo.Arguments = string.Format("-EncodedCommand {0}", isEnabledBase64String);
    powershellProcess.StartInfo.RedirectStandardInput = false;
    powershellProcess.StartInfo.RedirectStandardError = false;
    powershellProcess.StartInfo.RedirectStandardOutput = false;
    powershellProcess.StartInfo.UseShellExecute = false;
    powershellProcess.StartInfo.CreateNoWindow = true;
    bool value = powershellProcess.Start();
    powershellProcess.BeginOutputReadLine();
    while (!powershellProcess.HasExited)
    {
        Thread.Sleep(1000);
    }
    powershellProcess.CancelOutputRead();
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    powershellProcess.Close();
}

例如,腳本塊“ isEnabledBase64String”返回一個數字。 我如何獲得電話號碼? 有什么建議嗎? 謝謝

您是否必須啟動一個過程來執行Powershell腳本? 您可以使用System.Management.Automation中的Powershell實例對象。

請參閱Windows Powershell上的示例(來自C# https: //blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

這將使您對腳本的執行,傳遞參數以及讀取輸出有更多控制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM