Reputation: 137
I am using C# to execute a PowerShell script:
using (PowerShell powerShellInstance = PowerShell.Create())
{
string query = string.Format(@"$server = ""{0}""
$db = ""master""
$sql = ""SELECT DISTINCT hostprocess FROM master.dbo.sysprocesses""
$user = ""{1}""
$pass = ""{2}""
$processId = Invoke-sqlcmd -Server $server -Database $db -Username $user -Password $pass -Query $sql | select -ExpandProperty hostprocess
Write-Output $processId", Server, DbUserName, DbPass);
powerShellInstance.AddScript(query);
var results = powerShellInstance.Invoke();
}
When I run the script in the PowerShell console, it returns 2 string values. But in C#, results
has 2 elements but they are null. What is the problem here and why is the behavior different when executing it via C#?
Upvotes: 1
Views: 517
Reputation: 387667
PowerShell.Invoke
only returns PSObject
objects for the return value of the executed PowerShell commands. When you write to the host using Write-Output
, then there will be no return value, so you cannot see the result within the results
collection. Instead, the written output will be written to the Information
stream of the PowerShell
object:
using (var ps = PowerShell.Create())
{
// commands that writes to the output
ps.AddScript("Write-Host 'output value'");
ps.Invoke();
var output = (ps.Streams.Information.First().MessageData as HostInformationMessage).Message;
Console.WriteLine(output); // output value
}
using (var ps = PowerShell.Create())
{
// command that returns a value, e.g. a string literal
ps.AddScript("'return value'");
var results = ps.Invoke();
string stringResult = results.First().BaseObject as string;
Console.WriteLine(stringResult); // return value
}
Within the PowerShell console itself, of course you will see written output directly and return values that are not collected will also often be displayed directly.
Upvotes: 1