从 c# 运行 PowerShell 脚本

Kri*_*hna 1 c# powershell command-line

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

我有命令在 PowerShell 上运行它

. .\Commands.ps1; Set-Product -bProduct 'Reg' -IPPoint 'ServerAddress' -Location  'testlocation' -Terminal 3
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试使用 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();
Run Code Online (Sandbox Code Playgroud)

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

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

mar*_*sze 5

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

1.)脚本的点源Commands.ps1

. .\Commands.ps1
Run Code Online (Sandbox Code Playgroud)

2.) 调用 cmdletSet-Product

Set-Product -bProduct 'Reg' -IPPoint 'ServerAddress' -Location  'testlocation' -Terminal 3
Run Code Online (Sandbox Code Playgroud)

所以,你必须这样对待他们。另外,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();
Run Code Online (Sandbox Code Playgroud)

(当然,AddStatement()您也可以将其分成两次调用并调用Invoke()两次。)