Powershell Import-Csv然后Get-Aduser会在空白行显示时显示广告中的所有用户

时间:2016-11-18 16:26:59

标签: powershell csv

我正在编写一个powershell脚本来禁用用户,因为我们每天都会得到一个列表并且它是单调的。我将票证中的列表粘贴到格式化为姓氏,名字的csv中,然后运行我的脚本并导入列表,打印广告并询问是否要在发现它们时禁用。这是代码......

# Set variables
$Import = "C:\Scripts\Support Files\Users_To_Disable.csv"
$Export = "C:\Scripts\Support Files\Disabled_Users_Output.txt"

# Import user list
$Users = Import-CSV $Import

foreach ($User in $Users)

{

# Set user variables
$LastName = $User.("Surname")
$FirstName = $User.("GivenName")

# Use user variables from list to search ad
$UserName = (Get-ADUser -Filter "GivenName -like '$FirstName*' -and Surname -like '$LastName*'").SamAccountName

# What to do if it finds nothing
If ($UserName -eq $Null)

    {
    Write-Host $LastName, $FirstName NA -ForegroundColor Yellow
    Write-Output "$LastName, $FirstName NA" | Out-File $Export -Append
    }   

# What to do if it finds a user
Else

    { 
    # Ask for user input
    Write-Host $LastName, $FirstName Found -ForegroundColor Green 
    Write-Host UserName = $UserName -ForegroundColor Green

    DO {

        $Disable = Read-Host "Do you want to disable user? (Y/N)"

        If($Disable -eq "Y")

            {
            # Disable the user
            Disable-ADAccount -Identity $UserName
            # Move the user
            Get-ADUser $UserName | Move-ADObject -TargetPath "OU=Disabled - Retention,DC=intranet,DC=sw"
            # Add Disabled Users group
            Add-ADGroupMember "Disabled Users" -Members "$UserName"
            # Set Disable Users as primary group
            $Group = Get-ADGroup "Disabled Users" -Properties @("PrimaryGroupToken")
            Get-ADUser "$UserName" | Set-ADUser -Replace @{PrimaryGroupID=$Group.PrimaryGroupToken}
            # Remove all other groups
            $User = Get-ADUser "$UserName" -Properties MemberOf
            $Groups = $User.MemberOf |ForEach-Object { Get-ADGroup $_ } 
            $Groups | ForEach-Object { Remove-ADGroupMember -Identity $_ -Members $User -Confirm:$false }
            # Output 
            Write-Host $LastName, $FirstName Disabled -ForegroundColor Red
            Write-Output "$LastName, $FirstName Disabled" | Out-File $Export -Append
            Break
            }

        }

    Until ($Disable -eq "N")
    }

}

Invoke-Item $Export

所有这些都有效,可怕的是,如果用户上方有空白单元格,则会返回广告中的所有用户,并询问您是否要禁用所有这些用户。换句话说,如果csv看起来像这样......

Surname GivenName
User    Test

一切正常,但如果它看起来像这样......

Surname GivenName

User    Test

混乱,不是真的,但它确实询问你是否要发起简历生成事件,我不这样做我怎么能建立一些安全性,以阻止它返回所有广告,当有空白用户之前的csv?

1 个答案:

答案 0 :(得分:1)

您可以通过过滤导入的Null值来消除空行,这可以解决问题。

$Users = Import-CSV $Import | Where-Object {$_.Surname}