如何获取PowerShell脚本以删除其他计算机上的用户?

时间:2018-11-29 00:39:59

标签: powershell scripting virtual-machine

我正在本地测试脚本,以删除VM上的用户帐户。这是脚本:

#This script will do the following actions:
#1.- Get a computer list from a TXT file
#2.- Get a list of users from a TXT to be removed from the local users group
#3.- Do a ping to every computer on the list, if the computer is offline it will skip it and pass to the next one
#4.- If the computer answers the ping it will search into the local users group and if a user matches with a user from the user list it will be removed
#5.- Creates a log with all the transactions

# Log Time Variables
$Date = Get-Date -UFormat %b-%m-%Y
$Hour = (Get-Date).Hour
$Minutes = (Get-Date).Minute
$Log = "C:\Scripts\Remove-LocalAdmins Masive-" + $Date + "-" + $Hour + "-" + $Minutes + ".log"

#Creates a log file for this process
Start-Transcript -Path $Log  -Force 

#List of computers to be check
$ComputerNames = Get-Content "C:\Users\admin\Downloads\User Deletion Scripts\TestLocal.txt"

#Ping the computers on the list
foreach ($ComputerName in $ComputerNames) {

#If theres no ping answer pass to the next one
if ( -not(Test-Connection $ComputerName -Quiet -Count 1 -ErrorAction Continue )) {
Write-Output "Computer $ComputerName not reachable (PING) - Skipping this computer..." }

#If computer does answer the ping
Else { Write-Output "Computer $computerName is online"

#Search into Users
$LocalUsers = "Users"
$Group = [ADSI]("WinNT://$computerName/$localUsers,group")
$Group.Members() |
foreach {
$AdsPath = $_.GetType().InvokeMember('Adspath', 'GetProperty', $null, $_, $null)
$A = $AdsPath.split('/',[StringSplitOptions]::RemoveEmptyEntries)
$Names = $a[-1] 
$Domain = $a[-2]

#Gets the list of users to be removed from a TXT that you specify and checks if theres a match in the local group
foreach ($name in $names) {
Write-Output "Verifying the local users on computer $computerName" 
$localuser = Get-Content "C:\Users\admin\Downloads\User Deletion Scripts\TestUsers.txt"
foreach ($localuser in $localuser) {
if ($name -eq $localuser) {

#If it finds a match it will notify you and then remove the user from the local users group
Write-Output "User $localuser found on computer $computerName ... "
Remove-LocalUser $localuser

Write-Output "Removed" }}}}}

#Passes all the information of the operations made into the log file
}Stop-Transcript

当我对其进行测试时,VM会执行ping操作。但是我明白了:

The following exception occurred while retrieving member "Members": "The 
network path was not found.
"
At C:\Users\admin\Downloads\User Deletion Scripts\Remove-LocalAdmins 
Masive.ps1:39 char:1
+ $Group.Members() |
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemExceptio 
   n
    + FullyQualifiedErrorId : CatchFromBaseGetMember

也许我缺少有关防火墙的信息,但是我需要一种方法来使该脚本从计算机到VM。要删除用户,我需要在脚本中进行哪些修改?

根据下面的评论,我的脚本应该看起来像这样吗?

    $Computer = Get-Content "C:\Users\admin\Downloads\Delete-Users\Computer(s).txt"

Invoke-Command -ComputerName $ComputerName.Trim() -ScriptBlock {

#enable remoting
Enable-PSRemoting -Force

#Get local users from admin group
$LocalUsers = "Users"
$Group = [ADSI]("WinNT://$computerName/$localUsers,group")
$Group.Members() |
foreach {
$AdsPath = $_.GetType().InvokeMember('Adspath', 'GetProperty', $null, $_, $null)
$A = $AdsPath.split('/',[StringSplitOptions]::RemoveEmptyEntries)
$Names = $a[-1] 
$Domain = $a[-2]

$LocalUser = foreach ($name in $names) {
Write-Output "Verifying the local users on computer $computerName" 
$localuser = Get-Content "C:\Users\admin\Downloads\Delete-Users\User(s).txt"
foreach ($localuser in $localuser) {
if ($name -eq $localuser) {

Foreach($User in $LocalUser){
#Check if the user is the one to delete and delete it using Remove-LocalUser
Write-Output "User $localuser found on computer $computerName ... "
Remove-LocalUser $localuser
Write-Output "Removed" 

                    }
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

确保文本文件中不包含任何尾随空格。

我想指出代码中的一些错误。

  • foreach ($localuser in $localuser)不起作用,我相信它是错字,您可以理解。
  • Remove-LocalUser $localuser无法工作,因为$LocalUser是来自VM的用户,并且Remove-LocalUser是在本地计算机上执行的。

您可以像下面这样在Invoke-Command内部进行所有操作。

$Computer = Get-Content "C:\Users\admin\Downloads\User Deletion Scripts\TestLocal.txt"
Invoke-Command -CompuerName $ComputerName.Trim() -ScriptBlock {
    #Get local users from admin group
    $LocalUser = #Get all the local users
    Foreach($User in $LocalUser){
       #Check if the user is the one to delete and delete it using Remove-LocalUser
   }

}

如果您的VM在hyper-V中,则可以使用不依赖于任何网络连接的PowerShell Direct。

查看有关here的更多有关PowerShell Direct的信息。

答案 1 :(得分:1)

您没有说您正在运行什么版本的PowerShell?

v5具有用于本地用户管理的cmdlet,如果您不在,则MS PS Gallery上有一个用于本地用户管理的模型。

您正在尝试访问远程主机,但没有说明如何进行PSRemting设置。这意味着,这是您的工作站和主机所在的域,还是工作组。

您正在尝试在远程主机上使用局部变量,而未设置变量作用域。

  • 必须启用PSRemoting才能使其正常工作。
  • 您必须确定变量的范围以供远程使用。
  • 您将需要使用Invoke-Command在远程上运行此代码 主持人。
  • 您必须是每个远程主机上的管理员。

因此,中间部分应更改为类似的内容...

Else 
{ 
    Write-Output "Computer $computerName is online"

    Invoke-Command -ComputerName $computerName -ScriptBlock {
        # Search into Users
        $LocalUsers = "Users"
        $Group = [ADSI]("WinNT://$Using:computerName/$localUsers,group")

        $Group.Members() |
        foreach 
        {
            $AdsPath = $_.GetType().InvokeMember('Adspath', 'GetProperty', $null, $_, $null)
            $A = $AdsPath.split('/',[StringSplitOptions]::RemoveEmptyEntries)
            $Names = $a[-1] 
            $Domain = $a[-2]


            # Gets the list of users to be removed from a TXT that you specify and 
            # checks if theres a match in the local group

            foreach ($name in $names) 
            {
                Write-Output "Verifying the local users on computer $computerName" 
                $localuser = Get-Content "C:\Users\admin\Downloads\User Deletion Scripts\TestUsers.txt"

                foreach ($localuser in $localuser) 
                {
                    if ($name -eq $localuser) 
                    {

                        # If it finds a match it will notify you and then remove 
                        # the user from the local users group

                        Write-Output "User $localuser found on computer $computerName ... "
                        Remove-LocalUser $localuser

                        Write-Output "Removed" 
                    }
                }
            }
        }
    }