我已经尝试了以下方法,但似乎没有什么能得到它。未设置注册表项。代码不会抛出错误,它是以管理员身份执行的。
首先是简单的方法
localKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell", true);
localKey.SetValue("ExecutionPolicy", "Unrestricted", RegistryValueKind.String);
localKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell", true);
localKey.SetValue("ExecutionPolicy", "Unrestricted", RegistryValueKind.String);然后使用来自NuGet的系统自动化
using (PowerShell PS = PowerShell.Create())
{
PS.AddCommand("Set-ExecutionPolicy");
PS.AddParameter("ExecutionPolicy", "unrestricted");
PS.Invoke();
}所有这些都是为了执行powershell脚本:
ps.AddScript(ps1_GenComNam + @"\GenerateComputerName.ps1").Invoke();有没有办法使用无限制的执行策略来执行PS脚本?
发布于 2021-04-09 20:32:17
using (PowerShell PS = PowerShell.Create())
{
PS.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicty unrestricted;");
PS.Invoke();
}你能不能试一下,然后告诉我这对你是否有效?我现在不能测试它,不能在好的PC上:D
编辑:
所以,我打开了我的电脑,它为我工作(v7.0.0中的所有NuGet )
当我运行以下命令时:
using (PowerShell PS = PowerShell.Create())
{
PS.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted; Get-ExecutionPolicy");
Collection<PSObject> results = PS.Invoke();
foreach (PSObject obj in results)
{
Console.WriteLine(obj.ToString());
}
}它不受限制地返回,我可以尝试不同的执行策略,结果是相同的,我的进程得到了我需要的执行级别。
运行这个变体(当我执行它时,所有作用域都受到限制):
using (PowerShell PS = PowerShell.Create())
{
PS.AddScript("Get-ExecutionPolicy; Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted; Get-ExecutionPolicy");
Collection<PSObject> results = PS.Invoke();
foreach (PSObject obj in results)
{
Console.WriteLine(obj.ToString());
}
}我得到了
Restricted
Unrestricted
Sortie de .\ConsoleApp1.exe (processus 13532). Code : 0.-Scope进程使其在执行后恢复正常,但我可以有效地执行我的进程。
遗憾的是,我不知道是什么对你不利。
发布于 2021-05-06 23:29:54
这个问题似乎只是一个野餐错误。我编译了32位而不是64位的代码。它将其设置为32位PowerShell。一旦我为64位编译了它,它就工作得很好。
谢谢你们所有人。
https://stackoverflow.com/questions/67020249
复制相似问题