运行 来自 c# 的 PowerShell 脚本

Running the PowerShell Script from the c#

我正在尝试从 C# 调用 PowerShell ISE 脚本。

我已收到命令,我正在 运行在 PowerShell

上安装它
. .\Commands.ps1; Set-Product -bProduct 'Reg' -IPPoint 'ServerAddress' -Location  'testlocation' -Terminal 3

现在我正在尝试用 c# 创建命令,我写了一些这样的代码。

//Set Execution Policy to un restrict
            powershell.AddCommand("Set-ExecutionPolicy");
            powershell.AddArgument("unrestricted");
            powershell.Invoke();
            powershell.Commands.Clear();

        

powershell.AddScript("K:\Auto\Cases\Location\Commands.ps1", false);
            powershell.AddArgument("Set-Product").AddParameter("bProduct ", "Reg").
                AddParameter("IPPoint", "ServerAddress").
                AddParameter("Location", "testlocation").AddParameter("Terminal", 3);

            powershell.Invoke();

我可以看到它 运行宁 很好。但它没有更新我的 xml 文件中的值。它应该更新我在文件中的值。当我尝试使用 powershell 运行 它时,它会 运行 并运行文件。但是 c# 代码不起作用。

任何提示或线索将不胜感激。

注意分号,所以这基本上是两个语句:

1.) Dot-sourcing 脚本 Commands.ps1

. .\Commands.ps1

2.) 调用 cmdlet Set-Product

Set-Product -bProduct 'Reg' -IPPoint 'ServerAddress' -Location  'testlocation' -Terminal 3

所以,你必须这样对待他们。此外,AddScript 需要代码,而不是文件名。

powershell
    // dot-source the script
    .AddScript(@". 'K:\Auto\Cases\Location\Commands.ps1'")

    // this is the semicolon = add another statement
    .AddStatement()

    // add the cmdlet
    .AddCommand("Set-Product")
    .AddParameter("bProduct", "Reg")
    .AddParameter("IPPoint", "ServerAddress")
    .AddParameter("Location", "testlocation")
    .AddParameter("Terminal", 3)

    // invoke all statements
    .Invoke();

(或者 AddStatement() 您当然可以将其分成两个调用并调用 Invoke() 两次。)