简体   繁体   English

试图在C#中运行powershell脚本

[英]Trying to run a powershell script in C#

I've got a PS script that adds firewall rules. 我有一个添加防火墙规则的PS脚本。

I'm using Process.Start("powershell.exe", "-File "+"\\"C:\\Program Files (x86)\\blah\\blah\\add-FirewallRule.ps1\\""); 我正在使用Process.Start(“powershell.exe”,“ - File”+“\\”C:\\ Program Files(x86)\\ blah \\ blah \\ add-FirewallRule.ps1 \\“”);

This command works fine on my local machine, but in testing I've been running the program on a Windows Server 2008 R2, and the PS script won't run. 此命令在我的本地计算机上运行正常,但在测试中我一直在Windows Server 2008 R2上运行该程序,并且PS脚本将无法运行。 It runs and works fine if I run it manually from the command line, but my code won't work. 如果我从命令行手动运行它,它运行并正常工作,但我的代码将无法正常工作。 All the file paths are correct (i've already checked that and had a co worker check it). 所有文件路径都是正确的(我已经检查过并且有一个同事检查它)。 When I run the code the PS console doesn't even pop up. 当我运行代码时,PS控制台甚至没有弹出。

Any suggestions? 有什么建议么?

Since you are in C#, I'd recommend using the PowerShell Invoke API rather than Process.Start. 由于您使用的是C#,我建议使用PowerShell Invoke API而不是Process.Start。 The API is easy to use and hopefully will give you a better indication of what is going wrong. API易于使用,希望能更好地指示出现问题。

Turns out that I wasn't accounting for the automatic redirect caused by running a 32-bit app on a 64-bit system. 事实证明,我没有考虑在64位系统上运行32位应用程序导致的自动重定向。 So all I had to do was go in and set the appropriate execution policy for the 32 bit version of powershell. 所以我所要做的就是进入并为32位版本的PowerShell设置适当的执行策略。

Have you tried running as Admin? 你试过以管理员身份运行吗? I believe Process.Start requires elevated privileges that are not available in, say, sandbox mode. 我相信Process.Start需要提升权限,例如沙盒模式中不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM