【问题标题】:Running the PowerShell Script from the c#从 c# 运行 PowerShell 脚本
【发布时间】:2021-09-11 07:50:06
【问题描述】:

我正在尝试从 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#代码不行。

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

【问题讨论】:

    标签: c# powershell command-line


    【解决方案1】:

    注意分号,所以这基本上是两个陈述:

    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()。)

    【讨论】:

    • 所以。它只是需要。在那里,它会正常工作吗?
    • 谢谢AddScript(@". K:\Auto\Cases\Location\Commands.ps1")
    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2014-09-12
    • 1970-01-01
    • 2021-08-16
    • 2017-08-17
    • 1970-01-01
    相关资源
    最近更新 更多