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.
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
}
}
Additional Note: This can also occur if you don't declare the array as an array or mistype it when you declare it. Simple little error. But, maybe it will help someone that comes here and still can't get it resolved. Check your array variable name declaration carefully.
# Example 1 of how you could unintentionally fubar it.
$ActiveDirectoryList=$null
# Example 2 of how you could unintentionally fubar it.
$ActiveDirectoryList_ExaggeratedExampleWrongName=#()
# Example 3. Same as 2 above, but not as easily identifiable type error
$ActiveDirectoryLists=#()
$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
}
}
+= kills puppies. (the whole array is copied every time)
$UserDetails = get-aduser -filter {enabled -eq $true} -properties |
Select DisplayName,EmailAddress, SAMAccountName
$counter = 0
$ActiveDirectoryList = foreach($User in $UserDetails){
$Users = get-aduser $User.SAMAccountName -properties *
if(!$Users.EmailAddress -eq ""){
$counter++
New-Object PSObject -property #{
Displayname = $Users.DisplayName
'Email Address' = $Users.EmailAddress
}
write-host $Users.DisplayName
}
}
This can be simplified to:
$ActiveDirectoryList = get-aduser -filter {enabled -eq $true -and
EmailAddress -like '*'} -properties Displayname,EmailAddress |
select Displayname,#{n='Email Address';e={$_.EmailAddress}}
Related
How do I add the value of $i as a new parameter to the object so that if $i is part of distinguishedName?
param([string[]]$Country="Norway,Denmark")
foreach ($i in $Country)
{
$users += Get-ADUser -searchbase "ou=$i,ou=FMS,dc=ce,dc=xxxx,dc=net" -ldapfilter $ldapfilter -properties CN,SamAccountName,mail,title,department,company,pager,employeeNumber,distinguishedName,extensionAttribute12
$users | Add-Member -MemberType NoteProperty -Name "OOU" -Force -Value ""
{missing code to add $i as value for property .OOU}
}
$users | Add-Member -MemberType NoteProperty -Name "license" -Force -Value ""
$users | where extensionAttribute12 -Like "*EOP1*" | %{$_.license="EOP1"}
$users | where extensionAttribute12 -Like "*E1*" | %{$_.license="E1"}
$users | where extensionAttribute12 -Like "*E3*" | %{$_.license="E3"}
I have tried to do the same as with the where clause in the bottom part, but the foreach loop makes it overwrite all values with the last member of $i
Use the -Value parameter to specify the initial value of a new property:
$users | Add-Member -MemberType NoteProperty -Name "OOU" -Force -Value $i
To avoid re-assigning the newest values to all the existing users that have already received their new OOP property, use an intermediary variable to hold the output from Get-ADUser:
foreach ($i in $Country)
{
$country_users = Get-ADUser -searchbase "ou=$i,ou=FMS,dc=ce,dc=xxxx,dc=net" -ldapfilter $ldapfilter -properties CN,SamAccountName,mail,title,department,company,pager,employeeNumber,distinguishedName,extensionAttribute12
$users += #($country_users | Add-Member -MemberType NoteProperty -Name "OOU" -Force -Value $i)
}
I want to migrate from one server to another one and because of that it is needed to add some local groups in the new server. In these local groups the users added belong to the domain.
Ex.:
Server | Members
---------------------------|------------------
Server\Group1 | Domain\User1, Domain\User2
Server\Group2 | Domain\User2, Domain\User3
The following link https://www.petri.com/use-powershell-to-find-local-groups-and-members seems to resolve this, but I am getting an unexpected result
This is the PowerShell script
# set variables
$server = $env:COMPUTERNAME
$localgroup = "Administrators"
$Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
# get users name
$members = $Group.psbase.Invoke("Members")
$members | ForEach-Object
{
$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
}
Get-WMIObject win32_group -filter "LocalAccount='True'" -computername $Server | Select PSComputername,Name,#{Name="Members";Expression={$_.GetRelated("Win32_UserAccount").Name -join ";"}}
The shown output is a two columns(although it should be 3, but PSComputerName is not being displayed where the Members column is empty)
Well, this is how I achieved the output and also exported it to a *.csv file
# set variables
$server = $env:COMPUTERNAME
$tableOutput = New-Object System.Collections.ArrayList
# get members
Function Get-Members($groupName){
$testgroup = [ADSI]"WinNT://$Server/$tmpGroupName,group"
$members = New-Object System.Collections.ArrayList
$testgroup.psbase.Invoke("Members") | ForEach-Object{
$searchFilter = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -replace "\."," "
$tmpUser = Get-ADUser -Filter {(Name -like $searchFilter) -or (SamAccountName -like $searchFilter)}
if($tmpUser){
[void]$members.Add($tmpUser.UserPrincipalName)
}
}
$members
}
Get-WMIObject win32_group -Filter { (LocalAccount='True') } -computername $Server | ForEach-Object{
$tmpGroup = $_
# get data
$tmpGroupName = $tmpGroup.Name
$members = Get-Members($tmpGroupName)
$tmpGroupDescription = $tmpGroup.Description
# save into object
$groupObject = New-Object -TypeName PSObject
$groupObject | Add-Member -MemberType NoteProperty -Name GroupName -Value $tmpGroupName
$groupObject | Add-Member -MemberType NoteProperty -Name GroupDescription -Value $tmpGroupDescription
$groupObject | Add-Member -MemberType NoteProperty -Name UsersList -Value $members
[void]$tableOutput.Add($groupObject)
}
$tableOutput | Select GroupName, GroupDescription, #{Name='Users';Expression={$_.UsersList -join ','}} | Export-CSV -Path 'C:\test\users.csv' -Delimiter ';' -NoTypeInformation
Any correction would be appreciated.
I'm trying to clean up our storage from legacy users that no longer exist and getting misc results.
I have a share with all usernames as folder names (ex. \\storage\homedir\joeblow) AD username: Joeblow. Throughout various years users have been removed from the domain but the folders were never removed from the share. So I am walking the share and using that to query the domain to find if said user still exists. I seems to work most the time and fail randomly. Not sure why, because manually sometimes the code will execute fine. Any thoughts?
Here is the code:
Import-Module ActiveDirectory
$folders = dir \\storage.domain.edu\C$\homedir3 | where {$_.PSIsContainer -eq $true}
$folder4 = "\\storage.domain.edu\C$\homedir4"
function New-Folder($Name, $Size) {
$folderList = New-Object PSObject
$folderList | Add-Member -MemberType NoteProperty -Name Name -Value $Name
$folderList | Add-Member -MemberType NoteProperty -Name Size -Value $Size
$folderList | Add-Member -MemberType NoteProperty -Name User -Value $User
}
foreach ($i in $folders) {
Write-Host "Folder presently is folder $i"
#$ADuser=Get-ADUser -Filter {$i.sAMAccountName.ToUpper() -eq"$i"} -SearchBase "OU=Active,OU=UserAccounts,DC=ad,DC=domain,DC=edu"
#$ADuser=Get-ADUser -Filter {samaccountname -eq $i} -SearchBase "OU=Active,OU=UserAccounts,DC=ad,DC=domain,DC=edu" -Property samaccountname
$r = "\\STORAGE.domain.EDU\HOMEDIR\$i"
$r = $r.ToUpper()
$ADuser = Get-ADUser -Filter {sameaccountname -eq $i} -SearchBase "OU=Active,OU=UserAccounts,DC=ad,DC=domain,DC=edu" -Property homeDirectory, samaccountname
if (!$ADuser) {
Write-Host "Null yo"
$ADuser = Get-ADUser -Filter {homeDirectory -eq $r} -SearchBase "OU=Active,OU=UserAccounts,DC=ad,DC=domain,DC=edu" -Property homeDirectory, samaccountname
}
$ADname = $ADuser.samaccountname.ToUpper()
$ADuser = $ADuser.homeDirectory
$ADuser = $ADuser.toupper()
Write-Host "R be this: $r and equal $ADuser"
#Write-Host "The person's folder name is: $ADuser"
#$iUp = $i.ToUpper()
Write-Host "The folder's is: $i"
if ($ADuser -eq $r) {
Write-Host "User: $ADname is in HomeDir3 $ADuser"
} else {
#(Test-Path "$folder4\$ADuser".trim()) {
#$notFound = $i
$folderList = New-Folder -Name $ADuser -User
Write-Host "$ADname failed"
}
}
#}
Write-Host "$folderList"
#$leftOvers = Compare-Object $folder4 $notFound
#Write-Host " Here is whats left $leftOvers"
#$i | Out-File -append "C:\deadaccounts.txt"
below code when inputting a few users, but fails is not returning expected results when querying for all users in AD. Not understanding why it's failing on bulk users versus a relatively small user list
Code below:
$Users = #('user1',"user2",'user3','user4')
$Mailboxes = $Users | Get-ADuser -pr *
$OU = 'DC=local,DC=local,DC=org'
$Mailboxes = Get-ADUser -Filter {SamAccountName -notlike '*$*'} -pr samaccountname
$Mailboxes = Get-ADUser -Filter * -SearchBase $OU -Properties samaccountname
foreach ($Mbx in $Mailboxes)
{
$ADUser = Get-ADUser $Mbx.SamAccountName -Properties * #Enabled,AccountExpirationDate
$UserObj = New-Object PSObject
$UserObj | Add-Member NoteProperty -Name "Username" -Value $ADUser.SamAccountName
If($mbx.msExchRecipientTypeDetails -eq $null)
{
$UserObj | Add-Member NoteProperty -Name "E-Mail" -Value "NoEmailAddress"
$UserObj | Add-Member NoteProperty -Name "email ItemCount" -Value "NoMailBox"
$UserObj | Add-Member NoteProperty -Name "TotalItemSize(GB)" -Value "NoMailBox"
Write-Host $Mbx.SamAccountName "has no mailbox" -ForegroundColor green
}
Else
{
If($mbx.msExchRecipientTypeDetails -eq 1)
{
$stats = $Mbx.EmailAddress | Get-MailboxStatistics | Select-Object TotalItemSize,TotalDeletedItemSize,ItemCount,LastLogonTime,LastLoggedOnUserAccount
$MbxSizeb = $stats.TotalItemSize -replace "(.*\()|,| [a-z]*\)"
$Tmp_gb = $MbxSizeb/1GB
$MbxSizeGB = [math]::Round($Tmp_gb,2)
$UserObj | Add-Member NoteProperty -Name "E-Mail" -Value $ADUser.EmailAddress
$UserObj | Add-Member NoteProperty -Name "email ItemCount" -Value $stats.ItemCount
$UserObj | Add-Member NoteProperty -Name "TotalItemSize(GB)" -Value $MbxSizeGB
}
}
$Report = $Report += $UserObj
}
Results with selected users
enter image description here
Results against all users:
enter image description here
You are missing the property msExchRecipientTypeDetails when populating the $Mailboxes variable. Lines 5 and 6 should read -Properties msExchRecipientTypeDetails
Update: So this wasn't completely correct. You can use your code if you change If($mbx.msExchRecipientTypeDetails -eq $null) to If($aduser.msExchRecipientTypeDetails -eq $null). However, you really don't need to get the ADUser again. $Mailboxes is a collection of ADUsers. Changes lines 2,6,7 to -Properties EmailAddress,msExchRecipientTypeDetails,SamAccountName
$Users = #('user1',"user2",'user3','user4')
$Mailboxes = $Users | Get-ADuser -Properties EmailAddress,msExchRecipientTypeDetails,SamAccountName
#$OU = 'DC=local,DC=local,DC=org'
#$Mailboxes = Get-ADUser -Filter {SamAccountName -notlike '*$*'} -Properties EmailAddress,msExchRecipientTypeDetails,SamAccountName
#$Mailboxes = Get-ADUser -Filter * -SearchBase $OU -Properties EmailAddress,msExchRecipientTypeDetails,SamAccountName
$Report = #()
foreach ( $Mbx in $Mailboxes ) {
switch ( $Mbx.msExchRecipientTypeDetails ) {
1 {
$Stats = $Mbx.EmailAddress | Get-MailboxStatistics | Select-Object TotalItemSize,ItemCount
$Report += [pscustomobject] #{
'Username' = $_.SamAccountName
'E-Mail' = $Mbx.EmailAddress
'E-Mail ItemCount' = $Stats.ItemCount
'TotalItemSize(GB)' = ( [math]::Round( ( $Stats.TotalItemSize -replace "(.*\()|,| [a-z]*\)" )/1GB ),2 )
}
break
}
default {
$Report += [pscustomobject] #{
'Username' = $_.SamAccountName
'E-Mail' = 'NoEmailAddress'
'E-Mail ItemCount' = 'NoMailBox'
'TotalItemSize(GB)' = 'NoMailBox'
}
break
}
}
}
#Shawn Esterman - thanks for the input -- below code works like a charm. Explicitly stated properties to search on.
cls
$Users = #()
$Report = #()
$UserObj = #()
$ADUser = #()
$Mbx = #()
$OU = #()
$Mailboxes = #()
$Users = #("user1",'user2','user3','user4','user5')
$Mailboxes = $Users | Get-ADuser -Properties EmailAddress,msExchRecipientTypeDetails,SamAccountName
$OU = 'DC=local,DC=local,DC=local'
$Mailboxes = Get-ADUser -SearchBase $OU -Filter {SamAccountName -notlike '*$*'} -ResultSetSize 50 -Properties EmailAddress,msExchRecipientTypeDetails,SamAccountName
foreach ($Mbx in $Mailboxes)
{
$UserObj = New-Object PSObject
$UserObj | Add-Member NoteProperty -Name "Username" -Value $Mbx.SamAccountName
If($mbx.msExchRecipientTypeDetails -eq $null)
{
$UserObj | Add-Member NoteProperty -Name "E-Mail" -Value "NoEmailAddress"
$UserObj | Add-Member NoteProperty -Name "email ItemCount" -Value "NoMailBox"
$UserObj | Add-Member NoteProperty -Name "TotalItemSize(GB)" -Value "NoMailBox"
Write-Host $Mbx.SamAccountName "has no mailbox" -ForegroundColor green
}
Else
{
If($mbx.msExchRecipientTypeDetails -eq 1)
{
$stats = $Mbx.EmailAddress | Get-MailboxStatistics | Select-Object TotalItemSize,TotalDeletedItemSize,ItemCount,LastLogonTime,LastLoggedOnUserAccount
$MbxSizeb = $stats.TotalItemSize -replace "(.*\()|,| [a-z]*\)"
$Tmp_gb = $MbxSizeb/1GB
$MbxSizeGB = [math]::Round($Tmp_gb,2)
$UserObj | Add-Member NoteProperty -Name "E-Mail" -Value $Mbx.EmailAddress
$UserObj | Add-Member NoteProperty -Name "email ItemCount" -Value $stats.ItemCount
$UserObj | Add-Member NoteProperty -Name "TotalItemSize(GB)" -Value $MbxSizeGB
}
}
$Report = $Report += $UserObj
}
I want to generate a list of users, with the exception of a list of names. This exclusion list changes from week to week.
$exclude = #('smith, bob', 'jones, tom', ...)
$csvmaster = #()
$uacct = 'User Account'
$UserID = 'User ID'
$lastname = 'Last Name'
... other attributes
$ulist = get-aduser -filter {enabled -eq 'true'} -properties * | ? {$_.Distinguishedname -like '*Standard User*' -and $_.title -ne $null -and $_.employeenumber -ne $null}
foreach ($u in $ulist)
{
if ($u.name -notmatch $exclude) {
$csvline = New-Object System.Object
$csvline | Add-Member -MemberType NoteProperty -name $UserID -value $u.EmployeeNumber
$csvline | Add-Member -MemberType NoteProperty -name $lastname -value $u.surname
...other attributes
$csvmaster += $csvline
}
}
...Output to csv
When I run this, the names I want to exclude still make it into the list. I also tried -notcontains and excluding them like this:
$ulist = get-aduser -filter {enabled -eq 'true'} -properties * | ? {$_.Distinguishedname -like '*Standard User*' -and $_.title -ne $null -and $_.employeenumber -ne $null -and $_.name -notmatch $exclude}
This behaves the same way.
Cheers.
So I think my problem was the way Get-ADUser accepts input value. And/Or my logic in general. I changed the code to this:
$exclude = #( ..list..of..names..)
$csvline = #()
$ulist = get-aduser ...
foreach ($u in $ulist)
{
if ($exclude -notcontains $u.name)
{
...
$csvline += $u.name
}
}
And it is doing what I need.