无法正常执行PowerShell的New-ItemProperty命令,求解决方案
C#调用PowerShell添加注册表项失败问题
我尝试通过C#调用PowerShell脚本添加注册表项,代码如下:
public void ExecuteCommand(string script) { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(script); pipeline.Invoke(); runspace.Close(); } static void Main(string[] args) { ExecuteCommand("New-ItemProperty -Path \"HKLM:\\SOFTWARE\\OpenSSH\" -Name DefaultShell -Value \"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -PropertyType String -Force"); }
该脚本手动在PowerShell中执行正常,但通过上述C#代码调用时无法生效,求解决办法。
尝试改用Command对象调用(仍失败)
按照建议改用Command对象构造命令,代码如下,但问题依旧:
public void ExecuteCommand() { Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command cmd = new Command("New-ItemProperty"); cmd.Parameters.Add("Path", @"HKLM:\SOFTWARE\OpenSSH"); cmd.Parameters.Add("Name", "DefaultShell"); cmd.Parameters.Add("Value", @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"); cmd.Parameters.Add("PropertyType", "String"); cmd.Parameters.Add("Force"); pipeline.Commands.Add(cmd); pipeline.Invoke(); }
错误排查细节
添加
-ErrorAction Stop后捕获到错误:Cannot find path 'HKLM:\SOFTWARE\OpenSSH' because it does not exist.
但该注册表路径实际存在,且程序已以管理员身份运行(注册表编辑器中可确认HKLM:\SOFTWARE\OpenSSH路径存在)。尝试设置执行策略时触发空引用异常:
错误信息:Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
尝试的代码:public void Execute() { using (var runspace = RunspaceFactory.CreateRunspace()) { // 此行引发错误 // runspace.InitialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned; runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript("New-ItemProperty -Path \"HKLM:\\SOFTWARE\\OpenSSH\" -Name DefaultShell -Value \"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -PropertyType String -Force -ErrorAction Stop"); pipeline.Invoke(); } }
内容的提问来源于stack exchange,提问作者BurakBey
相关产品推荐
相关产品推荐

