Wednesday, November 30, 2011

Powershell Script to connect to a list of PCs and delete a list of unsecure local accounts

I was given a list of PCs and a list of local accounts to delete, both lists were massive.
Came up with this initial script...

$PCname = (Get-Content drive:\filepath) #Load PC list in to array
$local = (Get-Content drive:\filepath) #Load Account list for deletion in to array


#Sets up loop that iterates through list of PCs and connects through ADSI and the WinNT provider


 Foreach ($pc in $PCname) { $Conn = [ADSI]"WinNT://$pc"

#Sets up a loop to iterate through a list of usernames and deletes them, the ADSI:WinNT connection is held #in the variable $Conn
     Foreach ($Acc in $local) { $Conn.Delete("User",$Acc)
  Write-Host "account deleted"
  }
  }

The ADSI or Active Directory Service Interface, is a touch misnamed, because it has Active Directory in it's name most folk think it's for connecting to the Active Directory. It should be considered as a DIRECTORY SERVICE INTERFACE. It is not just for the Active Directory and can actually connect to a few Directory Databases, it will work with standalone servers,PCs, NT40 domains,LDAP and Novell environments.

ADSI uses Providers, each of which can connect to a particular type of directory service.
The line

$Conn = [ADSI]"WinNT://$pc"    {WinNT and LDAP are both case sensitive, winnt or ldap or any mix of upper or lowercase characters will cause the script to fail!!}

Holds an ADSI connection, in variable $Conn using the WinNT provider to connect to a PC that the ForEach loop has loaded, the WinNT connection allows manipulation of local groups on a remote computer! And in the next loop you are deleting a specific list of users from the PCs using the method

$Conn.Delete("User",$Acc)

Baiscally $Conn (=remote PC connection) $Acc is a variable that holds the individual account the loop has loaded, and is used to specify what account to delete off the remote system with the command .Delete("user",$Acc) = action("object_type",name)

As clear as mud!...

ADSI Support is built in to Powershell because Powershell is built on Microsoft's .NET Framework.

I hope you find this not too confusing and of some help?


No comments:

Post a Comment