TestLink
TestLink

Reputation: 1

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

I am trying to delete a local user accounts on remote computers, where the hostnames and usernames are in a csv file.

Will the below code would work?

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

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

    #Test network connection before making connection and Verify that the OS Version is 6.0 and above
    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 $scriptBlock
    }
}

$scriptBlock = {
    function Remove-UserProfile {
        Remove-LocalUser -Name $username
    }
    Remove-UserProfile
}

Upvotes: 0

Views: 1855

Answers (1)

ArcSet
ArcSet

Reputation: 6860

Call the $scriptblock before the invoke-command. You should pass the $username by the -ArgumentsList parameter. $Args[0] will be the variable for the first argument in the -ArgumentsList.

Powershell is read from top to bottom. If you put a requested object or function below where its currently being read then powershell wont know it is there.

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

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

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

    #Test network connection before making connection and Verify that the OS Version is 6.0 and above
    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 $scriptBlock -ArgumentList $username
    }
}

Upvotes: 1

Related Questions