What I need to do is to export specific AD users and some of their properties to a CSV file. What I need to have there is some of the default properties like Name
, SamAccountName
, Enabled
and some custom ones: businesscategory
, extensionAttribute9
etc.
I'm struggling with my if - else
statements, as they seem to not be comparing employeenumber to $null
$name = Read-Host -Prompt "Please enter the name for output file."
$filename = $name+".csv"
$domain = @('DOMAIN1','DOMAIN2','DOMAIN3','DOMAIN4')
$result = foreach ($item in $domain) {
Get-ADUser -server $item -Properties businesscategory, extensionAttribute4,
extensionAttribute9, extensionAttribute13, employeenumber, Enabled -ResultPageSize 100 -Filter *
if (($null -ne $_.employeenumber) -and ($_.employeenumber -notlike '*svc*')) {
Select-Object Name,
SamAccountName,
UserPrincipalName,
@{n="businesscategory"; e={$_.businesscategory -join ", "}},
@{n="extensionAttribute4";e={$_.extensionAttribute4 -join ", "}},
@{n="extensionAttribute9";e={$_.extensionAttribute9 -join ", "}},
@{n="extensionAttribute13";e={$_.extensionAttribute13 -join ", "}},
DistinguishedName, employeenumber, Enabled
} else { (...)
The above is part of my code where it should enter into first if
. It does that, but it exports all accounts, whether employeenumber is present or not.
Another issue is that the exported CSV doesn't contain columns created from custom attributes, instead it shows some other properties that I did not ask for.
This used to work fine if I used Where-Object
instead of if - else
and checked the values like below:
Where-Object {
($_.SamAccountName -notlike '*proprietary*') -and
($_.UserPrincipalName -notlike '*proprietary*') -and
($_.SamAccountName -notlike '*mailbox*') -and (...)
Unfortunately I need to use if - else
to make more complex comparisons and selections, but can't figure it out
The problem is in this line:
Then in this line:
Since
$_
doesn't exist, you are comparing something like:Which will always be
$false
. It's also worth mentioning that this is aforeach
loop, different fromForEach-Object
, the automatic variable$_
($PSItem
) doesn't mean anything here.The next problem comes when using
Select-Object
as the beginning of the statement, there is no object being piped to it.In this case, the
if
condition could be removed completely with some LDAP Filtering:The code would look like this: