简体   繁体   中英

How to run a Powershell script with Rename-Computer in it using C#

I need to run a Powershell Script using C# with "Rename-Computer" in it on a Windows 2016 Server.

The Problem is that it is not working or executing correctly. The remote Computer doesn't get renamed and also not in the AD. When Executing there are no Errors. Only thing i know is that ps.HadErrors is true.

When I run the script nothing happens.

Expected Result would be the renamed Computer

预期结果

Actual Result is that the computername stays the same as before实际结果

I already tried executing the Powershell Script on the Windows Server and it worked as it is supposed to. I also tried Executing a other Powershell Script in C# that is writing to a File and it worked. Another thing i tried is to add the Module and the Command to Runspace, but it also did not change anything.

This is the Code i tried:

    public static readonly string script = $@"

    Import-Module ActiveDirectory
    $password = ConvertTo-SecureString ""passwort"" -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential(""Administrator"", $password)
    Rename-Computer -ComputerName ""Computer01"" -NewName ""NewComputer01"" -DomainCredential 
    $credential -Force";

    public static void Main(string[] args)
    {
        try
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            Runspace rs = RunspaceFactory.CreateRunspace(iss);
            rs.Open();
            PowerShell ps = PowerShell.Create();
            ps.Runspace = rs;
            ps.AddScript(script);
            ps.Invoke();
        }
        catch (Exception e)
        {
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }

I hope you can help and everything is clear.

The Problem was that I used an.Net Core Application so I had to use Powershell Core. Somehow it cannot make the WMI Connection when using Powershell Core, but it worked with Windows Powershell. So I had to reconfigure WMI on the Windows 10 Client and it worked!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM