我正在尝试从C#代码运行PowerShell脚本,但是我遇到了一些(可能是环境)问题:
在我尝试运行它的机器上,发生以下情况:
- PowerShell以管理员身份启动并加载
- PowerShell窗口立即关闭(显然)且没有出现错误
注意事项:
- 该脚本可正常工作。当我从ISE中运行它时,它可以无错误地运行。
- 如果我右键单击该脚本并选择“使用PowerShell运行”,即使在脚本中没有更改执行策略,我也会收到执行策略错误。
Set-ExecutionPolicy:Windows PowerShell已成功更新您的执行策略,但该设置被更具体范围定义的策略覆盖。由于覆盖,您的 shell 将保留其当前有效的执行策略 RemoteSigned。键入“Get-ExecutionPolicy -List”查看您的执行策略设置。有关详细信息,请参见“Get-Help Set-ExecutionPolicy”。 在第 1 行第 46 个字符处: + if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy],SecurityException + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Unrestricted
UserPolicy Undefined
Process Bypass
CurrentUser Unrestricted
LocalMachine Unrestricted
我相信这是环境问题,因为:
- 几天前它可以正常运行
- 在其他电脑上也能正常运行
这是我用来调用脚本的代码:
if (File.Exists("Start.ps1"))
{
string strCmdText = Path.Combine(Directory.GetCurrentDirectory(), "Start.ps1");
var process = System.Diagnostics.Process.Start(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe ", strCmdText);
process.WaitForExit();
}
脚本本身并不重要,因为我已将其更改为简单的 。Write-Host "Hello"
$d=Read-Host
我有同样的问题。
-NoProfile -ExecutionPolicy UnRestricted
? - bot_insaneCopy-Item
调用怎么样?这样你就可以跟踪它是否真的有作用了。不幸的是,我无法测试C#代码,但我可以在Powershell中模拟它。编辑:已经模拟过了,在我的电脑上,Powershell-> Powershell使用一个测试脚本是有效的,也就是说,它会等待Read-Host
提供数据。 - Vesper