有没有办法保存我的凭据,所以它不会继续询问每个循环?比如,将它隔离在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
" "
}
答案 0 :(得分:3)
是的,请使用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
" "
}
答案 1 :(得分:2)
您可以在循环外定义凭据。 我编辑了你的脚本,如下所示
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
" "
}