如何 运行 使用 C# 在其中重命名计算机的 Powershell 脚本

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

我需要 运行 在 Windows 2016 服务器上使用 C# 并在其中包含“重命名计算机”的 Powershell 脚本。

问题是它没有正常工作或执行。 远程计算机不会重命名,也不在 AD 中。 执行时没有错误。我唯一知道的是 ps.HadErrors 是真的。

当我 运行 脚本没有任何反应。

预期结果将是重命名的计算机

实际结果是计算机名和以前一样

我已经尝试在 Windows 服务器上执行 Powershell 脚本,它按预期工作。我还尝试在 C# 中执行另一个正在写入文件的 Powershell 脚本并且它有效。我尝试的另一件事是将模块和命令添加到运行空间,但它也没有改变任何东西。

这是我试过的代码:

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

希望你能帮忙,一切都清楚了。

问题是我使用了 .Net Core 应用程序,所以我不得不使用 Powershell Core。在使用 Powershell Core 时,它​​无法以某种方式建立 WMI 连接,但它可以与 Windows Powershell 一起使用。所以我不得不在 Windows 10 客户端上重新配置 WMI,它成功了!