且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 C# 中的参数调用 PowerShell 脚本文件

更新时间:2023-01-23 10:03:07

你可以使用我刚刚测试过的这段代码.

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();
}

这是我的测试脚本,位于 c:\test\test.ps1.

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

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

仅供参考,请确保您启动 32 位 (x86) PowerShell,并将执行策略设置为不受限制.Visual Studio 是一个 32 位进程,默认调用 32 位 PowerShell 引擎.

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.