我遇到了使用PowerShell从Active Directory获取值并将其与字符串进行比较的问题。
$ username_AD = Get-AdUser“JSmith”-Properties SamAccountName | FT SamAccountName
以上值存储在变量中:
echo $username_AD
SamAccountName
--------------
JSmith
因此,当我在下面运行时,条件永远不会成立。用户名JSmith确实存在于AD中。
$username_AD = Get-AdUser "JSmith" -Properties SamAccountName | FT SamAccountName
$username_value = "JSmith"
IF ($username_value -eq $username_AD)
{
echo "Yes the username exists in Active Directory!"
}
else
{
echo "No the username does not exist in Active Directory"
}
答案 0 :(得分:0)
您正在尝试比较不同的对象类型。
要注意的第一件事是FT
或Format-Table
没有产生一堆文字,它会创建一个[Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData]
对象。试试这个:
$username_AD = (Get-AdUser "JSmith" -Properties SamAccountName).SAMAccountName
$username_value = "JSmith"
IF ($username_value -like $username_AD)
{
Write-Output "Yes the username exists in Active Directory!"
}
else
{
Write-Output "No the username does not exist in Active Directory"
}
有几件事要记住,你想要比较字符串所以使用-like
而不是-eq
,Format-Table
没有创建[System.String]
对象,这就是你正在寻找,你正在使用powershell,所以不要像echo这样的命令混合使用。在这种情况下,Cmldet Write-Output
更合适。