我正在使用C#来执行PowerShell脚本:
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();
}
当我在PowerShell控制台中运行脚本时,它返回2个字符串值。但是在C#中,results
有2个元素但它们是null。这里有什么问题,为什么在通过C#执行它时行为会有所不同?
答案 0 :(得分:1)
PowerShell.Invoke
仅返回执行的PowerShell命令的返回值的PSObject
个对象。当您使用Write-Output
写入主机时,将没有返回值,因此您无法在results
集合中看到结果。相反,写入的输出将写入PowerShell
对象的Information
stream:
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
}
在PowerShell控制台本身中,您当然会直接看到书面输出,并且通常也会直接显示未收集的返回值。