KentMarion
KentMarion

Reputation: 35

How will I save my credentials every loop in Powershell

Is there a way in saving my credentials so it will not keep asking every loop? Like, isolating it outside the foreach loop. I tried removing -credentials and add it outside but it gives me an error of unauthorized access. I can't seem to figure it out. Sorry if this question seem to be stupid, I'm new to Powershell.

Import-Module ActiveDirectory

$ServerList = Get-Content "C:\servers.txt"

foreach($ServerName in $ServerList){

"$ServerName"
"=========="
Get-WmiObject -Class Win32_UserAccount -Computer $ServerName -Filter "LocalAccount='True'" -credential CORPORATE\usmenm03adm| Select Name

" "

}

Upvotes: 1

Views: 1800

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29003

Yes, read the credentials once with Get-Credential and store in a variable:

Import-Module ActiveDirectory

$ServerList = Get-Content "C:\servers.txt"
$MyCredential = Get-Credential -UserName "CORPORATE\usmenm03adm" -Message "Enter WMI credentials"

foreach ($ServerName in $ServerList) {

    "$ServerName"
    "=========="
    Get-WmiObject -Class Win32_UserAccount -Computer $ServerName -Filter "LocalAccount='True'" -Credential $MyCredential | Select-Object Name

    " "
}

Upvotes: 3

Venkatakrishnan
Venkatakrishnan

Reputation: 786

You can define the credential outside the loop. I edited your script like below

Import-Module ActiveDirectory

$ServerList = Get-Content "C:\servers.txt"

$cred=Get-Credential

foreach($ServerName in $ServerList){

"$ServerName"
"=========="
Get-WmiObject -Class Win32_UserAccount -Computer $ServerName -Filter "LocalAccount='True'" -credential $cred | Select Name

" "
}

Upvotes: 3

Related Questions