JellyfishPirate
JellyfishPirate

Reputation: 13

Running foreach loop in powershell prompts for credentials every loop?

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}

Upvotes: 1

Views: 358

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60315

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
}

Upvotes: 1

Related Questions