我正在尝试使用C#运行一个PowerShell脚本,但是一直没有成功。以下是我的函数代码:
我已经创建了以下内容用于模拟身份的函数:
结果是......同样的错误,告诉我无法访问注册表键。
private void ExecutePowerShellCommand(string scriptfile)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke();
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
//CommandParameter testParam = new CommandParameter("key", "value");
//myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
pipeline.Invoke();
}
我遇到的错误如下:
无法访问注册表项 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell'。
我该如何解决这个问题?我看过一些模拟用户身份的想法,但是没有找到好的模拟示例。我希望以管理员身份运行此脚本。
我已经做了以下声明:
[DllImport("advapi32.dll")]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr handle);
public delegate void IncognitoDelegate(params object[] args);
我已经创建了以下内容用于模拟身份的函数:
public static void Impersonate(IncognitoDelegate incognitoDelegate, params object[] args)
{
System.IntPtr token = new IntPtr();
WindowsIdentity wi;
if (LogonUser("myusername", "", "mypassword", 8, 0, ref token))
{
wi = new WindowsIdentity(token);
WindowsImpersonationContext wic = wi.Impersonate();
incognitoDelegate(args);
wic.Undo();
}
CloseHandle(token);
}
我创建了一个函数,用作委托:
private static void GIncognito(params object[] args)
{
RunspaceInvoke scriptInvoker = new RunspaceInvoke();
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
}
我已经修改了我的方法:
private void ExecutePowerShellCommand(string scriptfile)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Impersonate(new Util.IncognitoDelegate(GIncognito));
//RunspaceInvoke scriptInvoker = new RunspaceInvoke();
//scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
//CommandParameter testParam = new CommandParameter("key", "value");
//myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
pipeline.Invoke();
}
结果是......同样的错误,告诉我无法访问注册表键。
Set-ExecutionPolicy
使用的作用域......请参见我下面的答案。 - JaredReisinger