如何在 PowerShell 中執行 LDAP 查詢

  1. 在 PowerShell 中安裝 Active Directory 模組
  2. 使用 PowerShell 過濾器的 Filter 參數
  3. 在 PowerShell 中使用 -LDAPFilter 參數來設定 LDAP 過濾器
如何在 PowerShell 中執行 LDAP 查詢

在使用 PowerShell 查詢 Active Directory 時,最常見的挑戰之一是如何正確構建過濾器語法。

不幸的是,對許多人來說,所有 Active Directory PowerShell 模組 cmdlet 的 Filter 和 LDAP Filter 參數都是一個黑盒子。

本文將深入探討如何使用 Active Directory 過濾器和 LDAP 過濾器。

在 PowerShell 中安裝 Active Directory 模組

在繼續之前,需要一些先決條件。

  • 安裝 PowerShell Active Directory 模組。
  • 加入域的計算機。
  • 成功連接並身份驗證到 Active Directory 域控制器。

通常,執行命令 Install-Module 應該能從遠程 CDN 獲取該包並安裝到您的計算機上。仍然,對於 Active Directory 模組,我們必須建立一個先決包以成功安裝。

我們需要安裝的先決包是 RSAT遠程伺服器管理工具

您可以運行以下 PowerShell 腳本在您的計算機或伺服器上安裝 RSAT

安裝 Windows 10 的 RSAT:

Add-WindowsCapability -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 -Online

安裝 Windows Server 的遠程伺服器管理工具(2008 到 2016 多個版本):

Install-WindowsFeature -Name "RSAT-AD-PowerShell" -IncludeAllSubFeature

在您的機器上安裝遠程伺服器管理工具功能也將安裝 Windows PowerShell 的 Active Directory 模組。

使用 PowerShell 過濾器的 Filter 參數

PowerShell 過濾器使用標準的 Windows PowerShell 表達式語法。這種方法通常稱為 Active Directory 搜索過濾器語法。

這些過濾器與 Filter 參數一起使用。

在過濾器內,您將使用運算符比較各種 AD 對象屬性。例如,Get-ADUser 命令返回一個 Name 屬性。

因此,如果我們想找出所有符合特定名稱的用戶,您可以使用:

Get-ADUser -Filter "Name -eq 'John'"

屬性名稱可以是返回的 Active Directory cmdlet 的 LDAP 名稱或標準名稱。

屬性值通常用單引號或雙引號包裹。唯一接受的通配符是星號 *

我們可以看到上面使用雙引號包圍過濾器,而 John 則用單引號包裹。

在 PowerShell 中使用 -LDAPFilter 參數來設定 LDAP 過濾器

輕量級目錄訪問協議,或稱 LDAP,是一種供應商中立的協議,用於訪問和修改目錄數據。

當聽到目錄這個詞時,我們可能會想到電話簿,但在 Active Directory 的上下文中,這意味著更多的東西。

許多不同的對象類型由 AD 存儲並提供訪問,LDAP 協議在保護這些數據上發揮著作用。由於 AD 可以保留許多不同類型的數據,應用程序和用戶需要輕鬆查詢該目錄。

Active Directory 實現了 LDAP,即輕量級目錄訪問協議。使用 cmdlet 的 -LDAPFilter 參數可以讓您使用 LDAP 過濾器,例如那些在 Active Directory 用戶和計算機中創建的過濾器。

LDAP 搜索過濾器的語法在 RFC 第 4515 號中定義。每個過濾器規則都被括號 () 包圍。

以下是使用 Active Directory 群組過濾器作為基礎開始創建自己的過濾器的一些示例。

  • 所有名稱 (CN) 為 Department 的群組。
`'(cn=Department)'
  • 所有名稱為 Department 且描述為 Prod 的群組。
'(&(cn=Department)(description=Prod))'
  • 所有名稱為 DepartmentShare Access 的群組。
'(|(cn=Professional Services Department)(cn=Share Access))'
  • 所有群組不具有描述為 Prod 的描述,包括那些完全沒有描述字段的群組。
'(!(description=Prod))'
'(!(description=Prod))'
  • 所有描述為 Prod 但名稱不是 Department 的群組。
'(&(description=Prod)(!(cn=Department)))'
'(&(description=Prod)(!(cn=Department)))'
'(description=\5c\5cfileserver1\5cshare)'
  • 所有描述為 \\fileserver1\share 的群組。
'(description=\5c\5cfileserver1\5cshare)'

{{CODE_BLOCK_9}}

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn