这个问题已经让我发疯了一段时间,我无法弄清楚。
我有以下 C# 代码:
class Program
{
static void Main()
{
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-StartApps");
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(
"{0,-20} {1}",
result.Members["Name"].Value,
result.Members["AppID"].Value);
}
}
}
这意味着简单地运行 Get-StartApps,它返回一个带有名称和 AppID 的 PSObject ( https://docs.microsoft.com/en-us/powershell/module/startlayout/get-startapps?view=windowsserver2019-ps )。然后在 2 列中打印输出。
但是,尝试在 Visual Studio 中运行时出现以下错误:
System.Management.Automation.CommandNotFoundException:“在模块“StartLayout”中找到“Get-StartApps”命令,但无法加载该模块。有关更多信息,请运行“Import-Module StartLayout”。
UnauthorizedAccessException:文件 C:\Windows\system32\WindowsPowerShell\v1.0\Modules\StartLayout\GetStartApps.psm1 无法加载,因为在此系统上禁用了运行脚本。有关详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkID=135170上的 about_Execution_Policies 。
所以它确实找到了正确的模块,这意味着我不必在代码中手动加载它。但由于某种原因它无法加载它。
我已经通过 GP 在 64 位和 32 位 powershell 上完全启用了脚本。这是它的外观:
get-executionpolicy -list
Scope ExecutionPolicy
----- ---------------
MachinePolicy Unrestricted
UserPolicy Unrestricted
Process Unrestricted
CurrentUser Unrestricted
LocalMachine Unrestricted
有什么想法吗?相同的代码适用于 Get-Process 等 Powershell 命令。