使用PowerShell通过CSV删除AD用户并输出结果

ny6fqffe  于 2023-07-31  发布在  Shell
关注(0)|答案(1)|浏览(124)

我想通过在CSV文件中提供用户名列表并将结果输出到CSV来删除AD用户数。
我可以通过一个命令来实现:

Remove-ADUser -Identity Username1

字符串
我现在有这个脚本:

$Users = Import-Csv 'c:\temp\DeleteADUsers.csv'
Foreach ($User in $Users)
{
    Try
    {
    # Verify that users from your CSV exist in Active Directory
    Get-ADUser $User -ErrorAction Stop | Out-Null
    Remove-ADUser $User
    }
    Catch
    {
    Write-Host "Username '$User' not found in Active Directory"
    }
}


我想知道是否有人可以帮助修改包含CSV文件的代码,如下所示:


的数据
也能够协助输出结果到CSV文件。

更新1

我试过这个代码:

$Users = Import-Csv 'c:\temp\DeleteADUsers.csv'
$logPath = 'c:\temp\out.log'

foreach ($User in $Users)
{
    Try
    {
        if($User.Delete -ne 'Yes'){
            # not marked for deletion, let's skip it
            continue
           "Username '$User' skipped as it is not marked for deletion" |Tee-Object -LiteralPath $logPath
        }
        # Verify that users from your CSV exist in Active Directory
        Get-ADUser $User.sAMAccountName -ErrorAction Stop | Out-Null
        Remove-ADUser $User.sAMAccountName
       "User '$User' removed from Active Directory" |Tee-Object -LiteralPath $logPath
    }
    Catch
    {
       "Username '$User' not found in Active Directory" |Tee-Object -LiteralPath $logPath
    }
}


这是我的CSV格式:



当我运行代码时,屏幕上没有错误或输出,也没有日志文件。
这就是我在PowerShell中得到的:

PS C:\Windows\system32> C:\Users\Administrator\Desktop\DeleteADUsers.ps1

PS C:\Windows\system32>


检查AD时不会删除用户。
请协助。

更新2

对不起,伙计们,我想通了,恢复到CSV风格,我有,这修复了问题。
重新正确读取代码,发现问题DUH...
再次感谢你。

yx2lnoni

yx2lnoni1#

Import-Csv将自动解析每一行,并吐出属性名称与CSV中的列标题相对应的对象。
这意味着您可以使用$User.sAMAccountName来引用sAMAccountName列中的值:

$Users = Import-Csv 'c:\temp\DeleteADUsers.csv'
$logPath = 'path\to\out.log'

foreach ($User in $Users)
{
    Try
    {
        if($User.Delete -ne 'Yes'){
            # not marked for deletion, let's skip it
            continue
           "Username '$User' skipped as it is not marked for deletion" |Tee-Object -LiteralPath $logPath
        }
        # Verify that users from your CSV exist in Active Directory
        Get-ADUser $User.sAMAccountName -ErrorAction Stop | Out-Null
        Remove-ADUser $User.sAMAccountName
       "User '$User' removed from Active Directory" |Tee-Object -LiteralPath $logPath
    }
    Catch
    {
       "Username '$User' not found in Active Directory" |Tee-Object -LiteralPath $logPath
    }
}

字符串

相关问题