I am trying to insert a registry entry with a PowerShell script using C#. This is my code:
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");
}
The script works properly when I execute it by myself using Powershell but it doesn't work when I try to execute it like this.
How can I fix this problem?
Reply to JosefZ's Comment
The code block below also doesn't work.
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();
}
Reply to mklement0's Comment
I added -ErrorAction Stop
to the script to find where the error occurs, and I found it. The error is Cannot find path 'HKLM:\SOFTWARE\OpenSSH' because it does not exist.
but the path exists. I also started the program as administrator.
I also got an error when I try to set ExecutionPolicy. The error is Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
. This is the new code block I tried:
public void Execute()
{
using (var runspace = RunspaceFactory.CreateRunspace())
{
// Causes Error
// 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();
}
}
Thanks to zett42, I decided to use .NET registry classes to solve this problem, and the code block below works how I expected.