我将如何在 Powershell 中的每个循环中保存我的凭据

How will I save my credentials every loop in Powershell

有没有办法保存我的凭据,这样它就不会一直询问每个循环?比如,将它隔离在 foreach 循环之外。我尝试删除 -credentials 并将其添加到外部,但它给我一个未经授权访问的错误。我似乎无法弄清楚。对不起,如果这个问题看起来很愚蠢,我是 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

" "

}

是的,使用 Get-Credential 读取凭据一次并存储在变量中:

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

    " "
}

您可以在循环外定义凭据。 我像下面这样编辑了你的脚本

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

" "
}