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

时间:2015-12-14 05:47:17

标签: powershell credentials

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

我试图通过"尝试捕获"来实现这一点。和" 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
    }
}

1 个答案:

答案 0 :(得分:2)

作为最佳做法,请勿尝试猜出正确的帐户。这会在安全日志中产生噪音,并可能导致意外的帐户锁定。

记录每个环境的正确凭据并使用它。您可以将凭证映射存储在哈希表中,如此,

# 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

通过创建另一个存储凭据的哈希表,可以轻松扩展这一点。像这样,

# 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
相关问题