Better way to do this?

Hi,

First post here. I'm still new to powershell's more advanced features, although I've been using basic scripts and starting to advance my knowledge. What gets me is certain syntax or 'why' things go where, and while I can poke around to figure a lot of it out, sometimes I hit a wall and can't think through it.

The below script actually works, and does what I need, but I would think that there's a better way than using a second foreach to write the data to a file? The part I'm asking a question on is after the #Write data to CSV comment. This is mainly to increase my own knowledge, so any assistance is appreciated.

import-module activedirectory
$Output = "c:\scripts\output\samnames.csv"
#Remove output file if it already exists
If (Test-Path $Output){
Remove-Item $Output}
#Get list of employees
$csv = import-csv "c:\scripts\input\UserList.txt"
foreach($user in $csv){
$ENumber = $user.ENumber
$userSAM = Get-ADUser -Filter {EmployeeNumber -eq $ENumber} -Properties EmployeeNumber
#Write data to CSV
foreach ($userID in $userSAM) {
add-content -Path $Output -Value $userID.SamAccountName -NoNewline
add-content -Path $Output -Value "," -NoNewLine
add-content -Path $Output -Value $userID.Enabled
}
}

  • So you're just after a list of SamAccountNames that match the employee numbers from your user list ?

    My adds/changes are highlighted with ##

    import-module activedirectory
    $Output = "c:\scripts\output\samnames.csv"
    ## initialise array to store SAMs
    $sams = @()
    #Get list of employees
    $csv = import-csv "c:\scripts\input\UserList.txt"
    foreach ($user in $csv)
    {
    $ENumber = $user.ENumber
    ## This adds to the existing array (well, not really but that's the end result)
    $sams += Get-ADUser -Filter {EmployeeNumber -eq $ENumber} -Properties EmployeeNumber
    }
    ## this will overwrite existing file so no need to check/delete
    $sams | select samaccountname,enabled | export-csv $output -notypeinformation

    ## if you require extra information just add the required attributes to the select part eg select samaccountname,enabled,displayname

    ## Note: Because your Get-ADuser command only adds EmployeeNumber attribute to the default attributes if you want more attributes either add individually (you'd have to add displayname for my preious example)
    ## OR use -properties * to get all properties and then limit output with your SELECT

    Hope this helps