输入-PSSession,尝试使用多个凭据

Enter-PSSession, try with multiple credentials

我需要创建一个脚本,该脚本需要多个凭据才能建立与计算机的连接。

我曾尝试使用 "try catch" 和 "if else" 来实现此目的,但脚本看起来很丑陋,如果我需要插入更多凭据,则无法扩展。

有没有更好的方法可以达到同样的效果?

#credentiasl for non domain conputers and domain joined
$credential01 = Get-Credential domain 1\administrador
$credentiall02 = Get-Credential domain 2\administrador
$credentiall03 = Get-Credential workgroup\administrador

$error.clear()
#try to establish a remote sesion to the pc with the credentials01
try { etsn -ComputerName sldb04 -Credential $credential01 }

#if there is an error try to establish a remote sesion to the pc with the credentials02
catch 
{
    etsn -ComputerName sldb04 -Credential $credential02 

    #if the second credential is also wrong try the third
    If ($? -eq $false )
    {
        etsn -ComputerName sldb04 -Credential $credential03
    }
}

最佳做法是,不要试图猜测正确的帐户。这会在安全日志中产生噪音,并可能导致意外的帐户锁定。

为每个环境记录正确的凭据并使用它。您可以像这样将凭证映射存储在散列 table 中,

# Add computer names and respective admin accounts into a hash table
$ht =  @{"computer01"="domain1\admin";"computer02"="domain2\admin";"computer03"="group\admin" }

# What's the account for computer01?
$ht["computer01"]
domain1\admin

# Print all computers and admin account names
$ht.GetEnumerator() | % { $("Logon to {0} as {1}" -f $_.name, $_.value) }
Logon to computer01 as domain1\admin
Logon to computer03 as group\admin
Logon to computer02 as domain2\admin

这可以通过创建另一个存储凭据的散列table 轻松扩展。像这样,

# Create empty hashable
$creds = @{}
# Iterate computer/account hashtable and prompt for admin passwords
$ht.GetEnumerator() | % { 
$c= get-credential $_.value
# Add only accounts that don't yet exist on the hashtable
if(-not $creds.Contains($_.value)) {
    $creds.Add($_.value, $c) }
}
# What's the account for domain1\admin?
$creds["domain1\admin"]
UserName                          Password
--------                          --------
domain1\admin System.Security.SecureString