【问题标题】:How to use Win32_UserAccount rename method?如何使用 Win32_UserAccount 重命名方法?
【发布时间】:2019-03-21 18:43:29
【问题描述】:

我可以使用Get-CimInstance Win32_UserAccount 列出远程计算机上的用户。获得用户后,我想重命名管理员帐户。下面是代码,但它不起作用。有关使这项工作的任何提示?

$hostname = "SERVER1"
$newname  = "Server_Admin"
$administrator = Get-CimInstance Win32_UserAccount -ComputerName $hostname |
                 where SID -like 'S-1-5-*-500' -ErrorAction SilentlyContinue
$oldname = $administrator.Name

$oldname.Rename($newname)

上述命令因错误而失败

方法调用失败,因为 [System.String] 不包含名为“rename”的方法。

使用Set-CimInstance

Set-CimInstance -InputObject $administrator -Property @{name=$newname} -PassThru

报错

无法修改对象“Win32_UserAccount”的只读属性“名称”

使用的 PowerShell 版本是 5.1。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    使用 PowerShell 5.1 版

    使用 Invoke-CIMMethod 我能够重命名帐户。

    $serverlist = Get-Content C:\Temp\servers.txt
    $newname = "Server_Admin"
    
    foreach ($hostname in $serverlist)
    {
    #Check if server is online.
        if (Test-Connection -ComputerName $hostname -Count 1 -Delay 2 -BufferSize 1452 -Quiet)
        {
    #Get the Administrator user from the remote computer
            $administrator = get-ciminstance win32_useraccount -ComputerName $hostname  | Where-Object SID -Like 'S-1-5-*-500' -ErrorAction SilentlyContinue 
    #Display retrieved account
            write-host $administrator
    #Rename the administrator account
            Invoke-CimMethod -InputObject $administrator -ComputerName $hostname -MethodName "Rename" -Arguments @{name = $newname }
    #Get and display account details for the renamed account
            get-ciminstance win32_useraccount -ComputerName $hostname | Where-Object SID -Like 'S-1-5-*-500' | Select-Object Name,FullName,Status,Disabled,Lockout,Domain,LocalAccount,SID,SIDType,AccountType | sort Status | format-table -groupby Status 
        }
    }
    

    【讨论】:

      【解决方案2】:

      在该用例中,CIM cmdlet 不会返回活动对象。 没有.Rename() 附加到该对象的方法

      但是,WMI cmdlet 确实返回一个带有.Rename() 方法的活动对象。所以...使用Get-WmiObject -Class Win32_UserAccount 而不是Get-CimInstance -ClassName Win32_UserAccount。 [咧嘴一笑]

      【讨论】:

      • 查看下面的答案,使用 CIM 你需要使用 invoke-cimmethod,WMI 也有一个类似的 cmdlet 调用 wmimethod
      • @JeffPatton - 当然!我就是这么说的。我应该在我相当简短的答案中添加更多细节吗?
      • 也许 OP 似乎在谈论 CIM cmdlet 而不是 WMI。更全面的 WMI 答案可能是有益的,但感觉事情正在远离 WMI,而转向 CIM。
      • @JeffPatton - 那么我将保持原样。谢谢您的意见! [咧嘴]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多