Reputation: 67
I wrote a code and have a problem to export it to csv. So the code is comparing the list of AD users to a Distribution Groups or number of Distribution Groups and it works perfectly. I only cannot export it to .csv.
Get-ADUser -filter {Enabled -eq $true} -SearchBase "OU=Location" |% { $_.samAccountName } | out-file "C:\users.txt"
Get-ADGroupMember -Identity "Company" |% { $_.samAccountName } | out-file "C:\Members.txt"
$List = Get-Content ("C:\Members.txt")
$ListOfUsers = Get-Content ("C:\users.txt")
$compare = Compare-Object -ReferenceObject $ListOfUsers -DifferenceObject $List -IncludeEqual
foreach($Inp in $compare)
{
$notice = $Inp.InputObject
If ($Inp.SideIndicator -eq "==")
{
"$notice User is avaiable in Distribution List"
}
elseIf ($Inp.SideIndicator -eq "<=")
{
"$notice User is not available in Distribution List "
}
}
If I add at the end of the line export-csv it giving me something like this:
My question is: how to export it correctly to receive InputObject as a Name, SideIndicator as a Notice and Comparison Operators as information if the user is inside the Distribution Group or not?
Upvotes: 0
Views: 51
Reputation: 25001
If we keep your current logic, you can achieve the desired results with calculated properties in Select-Object.
$compare = Compare-Object -ReferenceObject $ListOfUsers -DifferenceObject $List -IncludeEqual
$hash = @{'==' = "{0} User is available in distribution list" -f $compare.inputobject
'<=' = "{0} User is not available in distribution list" -f $compare.inputobject
}
$compare | Select-Object @{n='User';e={$_.InputObject}},@{n='Notice';e={$hash.($_.SideIndicator)}} |
Export-Csv output.csv -NoType
Explanation:
The calculated property, which is a hash table with specific key-value pairs, allows you to output a custom property name along with a corresponding custom value. It requires having a key that represents the name of the property and a key that is an expression for your value. The name can be represented as l
,n
,name
, or label
. The value expression can be e
or expression
.
Creating the $hash
hash table is merely to make the calculated property more readable. It simply has a key that matches your desired SideIndicator
values so that we can dynamically return the message you require.
You can change the property names User
and Notice
to whatever you wish.
Upvotes: 2