Hi I am trying to run a script to get users in a network into an array so that it can be outputted to a csv file along with other data that I am going to get, such as distribution groups.
The code script I am running is giving an error:
Method invocation failed because [System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'.
The script is a simple for loop:
$ActiveDirectoryList=@()
$UserDetails = get-aduser -filter {enabled -eq $true} -properties * | Select DisplayName,EmailAddress, SAMAccountName
$counter = 0
foreach($User in $UserDetails){
$ActiveDirectoryList = New-Object PSObject
$Users = get-aduser $User.SAMAccountName -properties *
if(!$Users.EmailAddress -eq ""){
$counter++
$ActiveDirectoryList | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $Users.DisplayName
$ActiveDirectoryList | Add-Member -MemberType NoteProperty -Name "Email Address" -Value $Users.EmailAddress
write-host $Users.DisplayName
$ActiveDirectoryList+=$ActiveDirectoryList
}
}
Tried looking on the internet for a solution but they don't seem to solve anything.
To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator. For example, you have an existing array as given below. To add value “Hello” to the array, we will use += sign.
The + operator in PowerShell is used to add items to various lists or to concatenate strings together. To add an item to an array, we can have PowerShell list all items in the array by just typing out its variable, then including + <AnotherItemName> behind it.
Array subexpression operator @( )Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. PowerShell Copy.
The push() method is used for adding an element to the end of an array. Let's say you have an array of elements, each element being a string representing a task you need to accomplish. It would make sense to add newer items to the end of the array so that we could finish our earlier tasks first.
Don't reuse the same variable name for the array, and the individual objects that you want to add to the array. Here I've renamed the PSObject
variable to $ActiveDirectoryObject
:
$ActiveDirectoryList=@()
$UserDetails = get-aduser -filter {enabled -eq $true} -properties * | Select DisplayName,EmailAddress, SAMAccountName
$counter = 0
foreach($User in $UserDetails){
$ActiveDirectoryObject = New-Object PSObject
$Users = get-aduser $User.SAMAccountName -properties *
if(!$Users.EmailAddress -eq ""){
$counter++
$ActiveDirectoryObject | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $Users.DisplayName
$ActiveDirectoryObject | Add-Member -MemberType NoteProperty -Name "Email Address" -Value $Users.EmailAddress
write-host $Users.DisplayName
$ActiveDirectoryList += $ActiveDirectoryObject
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With