【问题标题】:C# won't run PowerShell script [duplicate]C# 不会运行 PowerShell 脚本 [重复]
【发布时间】:2019-04-24 04:31:14
【问题描述】:

我想从我的 C# 项目中调用 PowerShell 脚本,但它不起作用。

当我运行代码时,我没有收到任何错误(或者我不知道在哪里可以找到它们)。 我还尝试从 cmd 运行脚本并且脚本工作正常。

我的执行策略设置为无限制,所以这不是问题。

我仔细检查了路径,所以这些也没有问题。

C#代码:

string scriptPath = @"C:\Users\jmiha\Desktop\test.ps1";
var parameters = new List<String>();
parameters.Add("test");
PowerShell ps = PowerShell.Create();
ps.AddScript(scriptPath);
ps.AddParameters(parameters);
ps.Invoke();

PowerShell 脚本:

param(
    [Parameter(Mandatory = $true)]
    [String]$param
)
Add-Content 'c:\users\jmiha\desktop\test.txt' $param

当我打开 test.txt 时,它是空的。

【问题讨论】:

  • ps.AddScript(scriptPath); --> ps.AddCommand(scriptPath);
  • @MathiasR.Jessen,那么他们之间的区别是什么?
  • @PrasoonKarunanV: .AddScript() 名字不好; .AddScriptBlock() 会更有意义:你将一个独立的 PowerShell 代码 sn-p 传递给它——包括它们的参数在内的整个命令; .AddCommand() 添加单个命令名称或路径(包括,如果适用,脚本文件),其参数必须单独添加。

标签: c# powershell powershell-sdk


【解决方案1】:

AddScript 用于任意代码,而不是命令/参数语法。你可以使用类似的东西

ps.AddScript("Test-Path C:\temp").Invoke()

它有效。

如果你想绑定参数等,你需要使用AddCommand,它可以让你像对象一样与命令交互,并将绑定你的参数:

using (PowerShell powershell = PowerShell.Create())
    powershell
        .AddCommand(@"C:\Temp\test.ps1")
        .AddParameter("param", "TEST")
        .Invoke()

附言System.Management.Automation.dll 的文档很糟糕。

【讨论】:

  • 问题解决了,谢谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
相关资源
最近更新 更多