查找给定仅包含电子邮件地址的.csv的AD SamAccountName

时间:2018-11-02 16:20:58

标签: powershell

我有一个源.csv文件,其中包含columnA emailaddress和columnB Is this mailbox still in use?

我需要读取文件,根据给定的SamAccountName属性找到ADUser的emailaddress,然后在columnB = NO的地方删除任何AD帐户。如果B列= YES,请更新属性。

第二部分,如果Yes很好用,但是我无法使第一部分正常工作,因为我不确定如何获取然后将SamAccountName传递给Remove-ADUser命令。任何建议都会很棒。

$Users = Import-Csv $SurveyResults
foreach ($user in $users) { 
    if ($($user."Is this mailbox still in use?") -eq "NO") {
        Get-ADUser -Filter "emailaddress -eq '$($user.emailaddress)'" -Property SamAccountName |
            Select-Object -Property emailaddres, samaccountname, wwWHomePage |
            Remove-ADUser -Identity $_.SamAccountName -Confirm:$False
    }
    else {
        Get-ADUser -Filter "emailaddress -eq '$($user.emailaddress)'" -Properties * |
            Set-AdUser -replace @{wWWHomePage = "$($_.wWWHomePage) ACTIVE $(get-date -f yyyy-MM)"}
    }
}

2 个答案:

答案 0 :(得分:1)

Remove-ADUser可以通过管道获取ADUser对象。如果您确定只能从过滤器中获得一个ADUser对象,或者确定要删除所有具有匹配电子邮件地址的用户,则可以将Get-ADUser的结果传递给Remove-ADUser

$Users = Import-Csv $SurveyResults
foreach ($user in $users) { 
   if ($($user."Is this mailbox still in use?") -eq "NO") {
      Get-ADUser -Filter "emailaddress -eq '$($user.emailaddress)'" | Remove-ADUser -Confirm:$False
   } else {
      Get-ADUser -Filter "emailaddress -eq '$($user.emailaddress)'" -Properties * |
         Set-AdUser -replace @{wWWHomePage="$($_.wWWHomePage) ACTIVE $(get-date -f yyyy-MM)"}
   }
}

答案 1 :(得分:0)

乍一看,我会使用以下内容:

添加了编辑*

$Users = Import-Csv $SurveyResults
foreach ($user in $users) 
{
    $getADUser = Get-ADUser -Filter "emailaddress -eq '$($user.emailaddress)'" -Properties *

    if ($($user."Is this mailbox still in use?") -eq "NO")
    {
        $getADUser | Remove-ADUser -Confirm:$false
    }
    else
    {        
        $getADUser | Set-AdUser -replace @{wWWHomePage="$($_.wWWHomePage) ACTIVE $(get-date -f yyyy-MM)"}
    }
}