Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Powershell script to delete a couple of LOCAL users from remote computers

Status
Not open for further replies.

TLink

Systems Engineer
Sep 25, 2018
2
IE
I would like to delete a couple of local users (NOT domain users) from remote computers. May I know whether the following code would work?

Regarding the invoke command which one I should use?

Any help highly appreciated...


1. Remove-LocalUser -Name $username}
2. Invoke-Command -ComputerName $computer -ScriptBlock {$username.Delete()}

clear
$hostdetail = Import-CSV C:\Users\jj\Desktop\Test\hosts.csv

ForEach ($item in $hostdetail)
{
$hostname = $($item.hostname)
$username = $($item.username)
$computer = $hostname

#Test network connection and operating system version

If ((!(Test-Connection -comp $computer -count 1 -quiet)) -Or ((Get-WmiObject -ComputerName $computer Win32_OperatingSystem -ea stop).Version -lt 6.0))
{
Write-Warning "$computer is not accessible or The Operating System of the $computer is not supported.`nClient: Vista and above`nServer: Windows 2008 and above."
}
else
{
Invoke-Command -ComputerName $computer -ScriptBlock {Remove-LocalUser -Name $username}
# Invoke-Command -ComputerName $computer -ScriptBlock {$username.Delete()}
}


}
 
I have the script now. but have another requirement. I need to export (append) data to two csv files.

1. If the hostname is not found I need to append the value of $hostname to a csv file named "nohost.csv"

2. Also I would need to append the value of $hostname from which user are successfully deleted, to "successfull.csv".

May I know how to use the "export-csv –append –path" command with each iteration of the for loop?

clear
# Path of the CSV file
$hostdetail = Import-CSV C:\Users\jossy.jacob\Desktop\Test\hosts.csv

$scriptBlock = {
Remove-LocalUser -Name $args[0]
}

ForEach ($item in $hostdetail) {
$hostname = $($item.hostname)
$username = $($item.username)

#Test network connection before making connection and Verify that the OS Version is 6.0 and above
If ((!(Test-Connection -comp $hostname -count 1 -quiet)) -Or ((Get-WmiObject -ComputerName $hostname Win32_OperatingSystem -ea stop).Version -lt 6.0)) {
Write-Warning "$hostname is not accessible or The Operating System of the computer is not supported.`nClient: Vista and above`nServer: Windows 2008 and above."
}
else {
Invoke-Command -ComputerName $hostname -ScriptBlock $scriptBlock -ArgumentList $username
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top