如何通过在c#中传递属性来调用Power Shell脚本文件。 我正在使用下面的代码通过传递输入来调用ps1文件,但在调用附近却出错。 错误消息:
System.Management.Automation.CommandNotFoundException:'术语 'Get-Childitem C:\ samplemm.ps1'不被识别为 cmdlet,函数,脚本文件或可操作程序。检查 名称的拼写,或者如果包含路径,请验证路径 是正确的,然后重试。'
namespace SCOMWebAPI.Services
{
public class MaintennceModeService
{
private static IEnumerable<PSObject> results;
internal static string post(MaintenanceMode value)
{
// create Powershell runspace
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command("Get-Childitem C:\\samplemm.ps1");
CommandParameter testParam = new CommandParameter("mgmtserver", "NodeName");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
results = pipeline.Invoke();
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
}
}
答案 0 :(得分:3)
在Powershell中键入命令Get-ChildItem C:\\samplemm.ps1
时,实际上是将文本C:\\samplemm.ps1
绑定到默认参数Path
。
代码的问题在于,您已将第一个参数作为命令名的一部分包含在内。只需将其分开即可。
代替
Command myCommand = new Command("Get-Childitem C:\\samplemm.ps1");
分隔参数:
Command myCommand = new Command("Get-Childitem");
CommandParameter pathParameter = new CommandParameter("Path", "C:\\samplemm.ps1");
myCommand.Parameters.Add(pathParameter);