Home > Blockchain >  Cannot Execute Command "New-ItemProperty" Properly
Cannot Execute Command "New-ItemProperty" Properly

Time:12-30

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 regedit screenshot

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();
    }
}

CodePudding user response:

Thanks to zett42, I decided to use .NET registry classes to solve this problem, and the code block below works how I expected.

public void InsertEntry()
{
    RegistryKey localKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"SOFTWARE\OpenSSH", true);

    if (localKey != null)
    {
        localKey.SetValue("DefaultShell", @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe");
        localKey.Close();
        Console.WriteLine("Successful.");
    }
    else
    {
        Console.WriteLine("Null.");
    }
}

  • Related