Call PowerShell script file with parameters in C#

前端 未结 1 1677
失恋的感觉
失恋的感觉 2021-01-23 09:06

Really struggling with this. I have tried various different way, but nothing seems to work.

-using addScript: I get an error telling me that I can\'t call parameters thi

相关标签:
1条回答
  • 2021-01-23 09:58

    You can use this code, which I personally just tested.

    static void Main(string[] args)
    {
        PowerShell ps = PowerShell.Create();
        ps.AddScript(@"c:\test\test.ps1").AddParameter("param1", "paramvalue1");
        ps.Invoke();
    }
    

    Here is my test script, located in c:\test\test.ps1.

    [CmdletBinding()]
    param (
        [string] $param1
    )
    Set-Content -Path $PSScriptRoot\test.txt -Value $param1;
    

    FYI, make sure that you launch 32-bit (x86) PowerShell, and set the execution policy to Unrestricted. Visual Studio is a 32-bit process, and invokes the 32-bit PowerShell engine by default.

    0 讨论(0)
提交回复
热议问题