简体   繁体   中英

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

I try to get a return value from a powershell scriptblock started with new Process in c#.

    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();
}

Eg the scriptblock "isEnabledBase64String" returns a number. How do I get to the number? Any advice? Thanks

Do you have to start a process to execute the powershell script? You can use powershell instance object from the System.Management.Automation.

See example at windows powershell from c# https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

this will give you much more control over execution of script, passing the param as well as reading the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM