如何使用Win32_UserAccount重命名方法



我可以使用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 版本 5.1

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

$serverlist = Get-Content C:Tempservers.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 
    }
}
在该

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

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

最新更新