我正在尝试使用 C# 在运行空间中执行带有参数的 Powershell 文件。不幸的是,我得到以下输出:
提示用户的命令失败,因为主机程序或命令类型不支持用户交互。尝试支持用户交互的主机程序,例如 Windows PowerShell 控制台或 Windows PowerShell ISE,并从不支持用户交互的命令类型(例如 Windows PowerShell 工作流)中删除与提示相关的命令。
我能做什么?
当前的 c# 代码。这需要执行将在 PS 文件中的命令,并且需要返回一个 json 字符串。
public string ExecuteCommandDirect(int psId, string psMaster, string psFile)
{
String FullPsFilePath = @"C:\CloudPS\" + psFile + ".ps1";
String PsParameters = FullPsFilePath + " -psId " + psId + " -psMaster " + psMaster + " -NonInteractive";
// Create Powershell Runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
// Create pipeline and add commands
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(PsParameters);
// Execute Script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
// Close runspace
runspace.Close();
//Script results to string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
Debug.WriteLine(obj);
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
PS代码:
param([int]$psId = 0, [string]$psMaster = 'localhost');
$date = Get-Date -Format 'h:m:s' | ConvertTo-Json;
Write-Host $date;
exit;