Home > other >  Running foreach loop in powershell prompts for credentials every loop?
Running foreach loop in powershell prompts for credentials every loop?

Time:07-07

I've implemented a short Powershell snippet to mass rename computers in my Domain. It reads a CSV file with two columns, OldName and NewName, and loops across the list to change the name.

This works on paper, however every time I run the script it gives me a prompt to enter a password for every computer that it loops through. Is there a way to only use my credentials once for the whole script? Thank you.

$a = Import-Csv C:\File.csv -Header OldName, NewName
Foreach ($Computer in $a) {Rename-Computer -ComputerName $Computer.OldName -NewName $Computer.NewName -DomainCredential Domain\Admin01 -Force -Restart}

CodePudding user response:

The simple solution would be to store your PSCredential object before running the loop and feed the cmdlet said object. You can use Get-Credential as an easy alternative to request credentials:

$Csv  = Import-Csv C:\File.csv -Header OldName, NewName
$cred = Get-Credential -Credential Domain\Admin01
foreach($Computer in $Csv) {
    Rename-Computer -ComputerName $Computer.OldName -NewName $Computer.NewName -DomainCredential $cred -Force -Restart
}
  • Related