问题
Below is the script I am using to try and execute my powershell script but whenever i run it i just get a blank command window.
C# Code
static void Main(string[] args)
{
string text = System.IO.File.ReadAllText(@"C:\Program Files (x86)\Backup Reporter\Required\edit_website.ps1");
using (PowerShell PowerShellInstance = PowerShell.Create())
{
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
PowerShellInstance.AddScript(text);
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
foreach (PSObject outputItem in PSOutput)
{
// if null object was dumped to the pipeline during the script then a null
// object may be present here. check for null to prevent potential NRE.
if (outputItem != null)
{
Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
}
}
if (PowerShellInstance.Streams.Error.Count > 0)
{
Console.Write("Error");
}
Console.ReadKey();
}
}
Powershell Script
$text = "test test test"
All I want to do is output test to the command window.
回答1:
You can use Write-Output instead of Write-Host. It works for me while invoking from winform application.
回答2:
You code seems to be correct, however your script does not give any output. So that is why you do not see the output of the script. Add:
Write-Host $text
This will give you output that is printed at the line:
Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
回答3:
Your script does not give any output.You could use the command write-output on your script, to have an output.[As kpundir refer]
Write-Output $text
来源:https://stackoverflow.com/questions/43855697/executing-powershell-scripts-in-c-sharp