$userProfiles = Get-CimInstance-Class Win32_UserProfile | # add property "UserName" that translates SID to username Add-Member-MemberType ScriptProperty -Name UserName -Value { ([Security.Principal.SecurityIdentifier]$this.SID).Translate([Security.Principal.NTAccount]).Value } -PassThru | # create a hash table that uses "Username" as key Group-Object-Property UserName -AsHashTable-AsString
现在可以轻松地转储机器上所有带用户配置文件的用户列表了:
1 2 3 4 5 6 7 8 9 10
PS C:\> $userProfiles.Keys | Sort-Object MYDOMAIN\Administrator MYDOMAIN\User01 MYDOMAIN\User02 MYDOMAIN\User03 MYDOMAIN\User12 NT AUTHORITY\LOCAL SERVICE NT AUTHORITY\NETWORK SERVICE NT AUTHORITY\SYSTEM PC10\User
# list of computers to connect to $listOfComputers = 'PC10','TRAIN1','TRAIN2','AD001' # exclude your own computer $listOfComputers = $listOfComputers-ne$env:COMPUTERNAME # code to execute remotely $code = { "Hello" | Out-File-FilePath"c:\users\Public\Desktop\result.txt" } # invoke code on all machines Invoke-Command-ScriptBlock$code-ComputerName$listOfComputers-Throttle1000
# "ping" for PowerShell remoting # tests anonymously whether you can reach the target $IPorNameTargetComputer = 'place name or IP address here' Test-WSMan$IPorNameTargetComputer
# do not store passwords in production solutions, # or you MUST control access permissions to this sensitive data $username = "mydomain\UserName" $password = 'Password' | ConvertTo-SecureString-AsPlainText-Force $domainName = 'NameOfDomain'
# convert username and password to a credential $cred = [PSCredential]::new($username, $password) # join computer Add-Computer-DomainName$domainName-Credential$cred # restart computer Restart-Computer