如果 AD 中不存在,则通过 powershell 删除名称记事本文件

Remove Name Notepad file if doesnt exist in AD through powershell

$Users = GC "Desktop\Master.txt"

foreach ($user in $users) {

$userobj = $(try {Get-ADUser $user} catch {$Null})

If ($userobj -ne $Null) {

   Write-Host "$User Exists"

} else {

   Write-Host "$User Doesn't Exist"

}}

我正在使用此代码检查用户是否存在于 AD 中。稍后处理此记事本文件以删除文件上的用户。我打算看看是否可以将不存在的用户从列表中删除。如果用户在 AD

中不存在,是否有命令从记事本文件中删除名称为 on 的行

编写一个函数来测试单个用户:

function Test-ADUser {
  param($Identity)

  try {
    $null = Get-ADUser @PSBoundParameters -ErrorAction Stop

    # user must exist if we reached this point
    return $true
  }
  catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{
    return $false
  }
}

现在您可以使用 Where-Object 根据函数确定的内容从文本文件中过滤列表:

# Read list from file, filter out usernames that don't exist
$filteredList = Get-Content "Desktop\Master.txt" |Where-Object { Test-ADUser -Identity $_ }

# Write filtered data back to disk
$filteredList |Set-Content "Desktop\Master.txt" -Force