【问题标题】:PowerShell - Username existence checkPowerShell - 用户名存在检查
【发布时间】:2014-04-09 23:26:50
【问题描述】:

我在使用 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"
  }

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您正在尝试比较不同的对象类型。

    首先要注意的是FTFormat-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 而不是 -eqFormat-Table 不是创建 [System.String] 对象,这是你正在寻找的对象,你正在使用 powershell 所以不要混入 echo 之类的命令。 Cmldet Write-Output 在这种情况下更合适。

    【讨论】:

    • 无论如何,您的问题源于对 PowerShell 工作原理的一些误解。您可能会发现通过阅读 PowerShell 入门书籍可以节省时间和金钱。我喜欢在一个月的午餐中学习 PowerShell。你可以在一两周内完成它,它确实克服了 shell 的许多怪癖。你学到的重要教训是不要相信你在 shell 中看到的东西。如有疑问,请检查对象类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多