Export the content from multiple 'Get-ADComputer' commands - powershell

Using the Get-ADComputer command I am gathering the count of the operating systems for each OU based on when the password was last set. The problem I am facing, is exporting the whole thing into a CSV file.
When I append the (Export-Csv -Path 'c:\blah') it will only take the last command and leave the others in the console.
$ou1 = 'OU=Computers,OU=Name1,DC=domain,DC=com'
$ou2 = 'OU=Computers,OU=Name2,DC=domain,DC=com'
$ou3 = 'OU=Computers,OU=name3,DC=domain,DC=com'
$prop = 'OperatingSystem -Like "Windows 10*"'
Get-ADComputer -SearchBase $ou1 -Filter $prop -Property DistinguishedName, OperatingSystem, pwdLastSet |
Select-Object DistinguishedName, OperatingSystem,
#{Name="pwdLastSet";Expression={[datetime]::FromFileTime($_.pwdLastSet)}},
#{Name="90_Days_Old";Expression={([datetime]::FromFileTime($_.pwdLastSet)).AddDays(90) -le (Get-Date)}}
Get-ADComputer -SearchBase $ou2 -Filter $prop -Property DistinguishedName, OperatingSystem, pwdLastSet |
Select-Object DistinguishedName, OperatingSystem,
#{Name="pwdLastSet";Expression={[datetime]::FromFileTime($_.pwdLastSet)}},
#{Name="90_Days_Old";Expression={([datetime]::FromFileTime($_.pwdLastSet)).AddDays(90) -le (Get-Date)}}
Get-ADComputer -SearchBase $ou3 -Filter $prop -Property DistinguishedName, OperatingSystem, pwdLastSet |
Select-Object DistinguishedName, OperatingSystem,
#{Name="pwdLastSet";Expression={[datetime]::FromFileTime($_.pwdLastSet)}},
#{Name="90_Days_Old";Expression={([datetime]::FromFileTime($_.pwdLastSet)).AddDays(90) -le (Get-Date)}}
My expected result is to have the content of all three commands into a CSV file.

You have a lot of redundant code. Use a loop to avoid that. Also, there's no need to convert the property pwdLastSet (which contains the raw value from the AD attribute) to a DateTime value. The Get-ADComputer cmdlet already does that for you (the name of the property you want is PasswordLastSet).
$ou = 'OU=Computers,OU=Name1,DC=domain,DC=com',
'OU=Computers,OU=Name2,DC=domain,DC=com',
'OU=Computers,OU=name3,DC=domain,DC=com'
$prop = 'OperatingSystem -like "Windows 10*"'
$ou | ForEach-Object {
Get-ADComputer -SearchBase $_ -Filter $prop -Property DistinguishedName, OperatingSystem, PasswordLastSet |
Select-Object DistinguishedName, OperatingSystem, PasswordLastSet,
#{Name="90_Days_Old";Expression={$_.PasswordLastSet.AddDays(90) -le (Get-Date)}}
} | Export-Csv 'C:\path\to\output.csv' -NoType

You can put all your OUs into an array then use a foreach (%) as the SearchBase. This will also allow you to pipe (|) the results to a csv:
#OUs
$OUs = #('OU=Computers,OU=Name1,DC=domain,DC=com','OU=Computers,OU=Name2,DC=domain,DC=com','OU=Computers,OU=name3,DC=domain,DC=com')
$prop = 'OperatingSystem -like "Windows 10*"'
#forach --> | CSV
$OUs | %{Get-ADComputer -Filter $prop -Properties DistinguishedName, OperatingSystem, pwdLastSet -SearchBase $_ | Select-Object DistinguishedName, OperatingSystem,
#{Name="pwdLastSet";Expression={[datetime]::FromFileTime($_.pwdLastSet)}},
#{Name="90_Days_Old";Expression={([datetime]::FromFileTime($_.pwdLastSet)).AddDays(90) -le (Get-Date)}}} | Export-Csv Test123.csv -NoTypeInformation

Related

Password change notification problem exclude OU powershell

We are using a good script that we would like to extend to search for users everywhere except one OU. How can I do this?
Thanks in advance for your help!
PasswordChangeNotification
How to instert this code?
Get-ADOrganizationalUnit -filter * -SearchBase 'OU=test,DC=test,DC=com' | foreach {
if($_.distinguishedname -ne "OU=not,OU=that,OU=orgUnit,OU=test,DC=test,DC=com"){
$users=Get-ADUser -filter * -searchbase $_.distinguishedname -ResultPageSize 2000 -resultSetSize 500 -searchscope Onelevel | where-object enabled -eq true
$total=($users | measure-object).count
New-Object psobject -Property #{
OU=$_.Name;
A=$Total
}
}
}
On line 132 of the file you've linked to, you'll find the statement that actually queries Active Directory for the users:
$users = get-aduser -filter {(Enabled -eq $true) -and (PasswordNeverExpires -eq $false)} -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress | where { $_.passwordexpired -eq $false }
Add the following statement to the next line:
$users = $users |Where-Object distinguishedname -notlike "*,OU=not,OU=that,OU=orgUnit,OU=test,DC=test,DC=com"
... and leave the rest of the script as-is

powershell get-aduser query with two or more name variables

I'm tryin to get a powershell query with two displaynames in it. It works fine with one displayname.
Get-ADUser -Filter "displayName -like '**'" -SearchBase "OU= ,OU= ,OU= AG,DC= ,DC=" -Properties * | select-object mail | sort-object
How can i insert more displayname variables to the code?
You can use OR in the filter
Get-ADUser -Filter "DisplayName -like '*user1*' -or DisplayName -like '*user2*'" -SearchBase "OU= ,OU= ,OU= AG,DC= ,DC=" -Properties Mail |
Select-Object -ExpandProperty Mail | Sort-Object
Using LDAP Filter you can do like this (using | as OR)
Get-ADUser -LDAPFilter "(|(cn=*user1*)(cn=*user2*))" -SearchBase "OU= ,OU= ,OU= AG,DC= ,DC=" -Properties Mail |
Select-Object -ExpandProperty Mail | Sort-Object

collect samaccount powershell

I have a list of users in a CSV, but I need to collect the SamAccount attribute from each user by name in the ad.
CSV model
Script
Get-ADObject -Filter 'ObjectClass -eq "user" -and userAccountControl -eq "512"' -Properties * | Select-Object SamAccountName,CN,DisplayName, | Export-CSV -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
I'm a little lost I don't know how to do a foreach using name
I am trying but without success.
Trying to get samaccountname based on Name on csv file.
Import-Csv -Path C:\Temp\userteste.csv | foreach-Object {Get-ADUser -Filter {Name -like $_.name} -Properties Name | Select-Object samAccountName}
and export to csv file.
Why use Get-ADObject and not Get-ADUser for this? The latter gives you more of the desired properties you need in the CSV.
As aside, it is wasteful to do -Properties * if all you want is a small set of user attributes.
Something like this should work:
Get-ADUser -Filter "Enabled -eq $true" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName |
Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
As per your comment you need to get some extra attributes of the users listed in the CSV, you can do this:
Import-Csv -Path C:\Temp\userteste.csv | ForEach-Object {
Get-ADUser -Filter "Name -like '$($_.Name)'" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName
} | Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
Hope that helps

Correcting PowerShell script to show Disabled AD user account (not shared mailboxes) with Exchange mailbox and its size in MBytes?

I am attempting to modify the script below so it is showing all Disabled AD user account with Exchange User mailbox still enabled (not Shared Mailbox).
Because the script below also returns Shared Mailboxes which is always created as disabled AD user account.
$Allusers = Get-ADUser -Filter {(enabled -eq $false)} -Properties homeMDB, mailNickName, mail, DisplayName, SamAccountName, Givenname, SurName | ?{ $_.homeMDB -ne $null }
$Allusers | Select-Object Givenname, Surname, DisplayName, Mail, MailNickName, SamAccountName, homeMDB | Export-Csv "C:\DisableduserMBX.csv" -NoTypeInformation
It would be good if there is mailbox size as well in the column in MBytes.
Like in the below script:
Get-Mailbox -ResultSize Unlimited |
Get-MailboxStatistics |
Select DisplayName,StorageLimitStatus, `
#{name="TotalItemSize (MB)"; expression={[math]::Round(($_.TotalItemSize.ToString().Split("(")[1].Split(" ")[0].Replace(",","")/1MB),2)}}, `
ItemCount |
Sort "TotalItemSize (MB)" -Descending
To add the MBYTES column, you can try this.
Note this uses the filter as provided by notjustme.
# for the sake of readability..
$filter = '(Enabled -eq $false) -and (msExchRecipientTypeDetails -ne 4) -and ("$null" -ne homeMDB)'
$properties = #('homeMDB', 'mailNickName', 'mail', 'DisplayName', 'SamAccountName', 'Givenname', 'SurName', 'ProxyAddresses')
$Allusers = (Get-ADUser -Filter $filter -Properties $properties |
ForEach-Object {
$size = (Get-MailboxStatistics $_.SamAccountName).TotalItemSize.Value.ToMB()
New-Object -TypeName PSObject -Property #{
homeMDB = $_.homeMDB
mailNickName = $_.mailNickName
mail = $_.mail
ProxyAddresses = $_.ProxyAddresses -join '; '
DisplayName = $_.DisplayName
SamAccountName = $_.SamAccountName
Givenname = $_.Givenname
SurName = $_.SurName
MBytes = $size
}
}) | Sort-Object MBytes -Descending | Export-Csv "C:\DisableduserMBX.csv" -NoTypeInformation
p.s. I've added the ProxyAddresses in there to be able to spot more alias emailaddresses.
p.s. 2 The Identity parameter for Get-MailboxStatistics can be one of:
Name
Display name
Alias
Distinguished name (DN)
Canonical DN
domain name\account name
Email address
GUID
LegacyExchangeDN
SamAccountName
User ID or user principal name (UPN)
msExchRecipientTypeDetails with the value of 4 denotes a shared mailbox. So to exclude these you could try changing your first line of code to the following and see if that gives you the desired output.
$Allusers = Get-ADUser -Filter 'enabled -eq $false -and msExchRecipientTypeDetails -ne 4' -Properties homeMDB, mailNickName, mail, DisplayName, SamAccountName, Givenname, SurName | ?{ $_.homeMDB -ne $null }
You should also be able to include the homeMDB-bit in the filter directly;
$Allusers = Get-ADUser -Filter 'enabled -eq $false -and msExchRecipientTypeDetails -ne 4 -and homeMDB -ne "$null"' -Properties homeMDB, mailNickName, mail, DisplayName, SamAccountName, Givenname, SurName

Terminated & Not In Group

I'm trying to generate a report for all disabled accounts that don't have the group "Terminated Employees" but it isn't seeming to generate the report. Below is the code that I have at the moment.
TLDR: The text file contains a list of all the disabled accounts and I am trying to cross reference that list with the list of people in Terminated Employees and then return to a CSV file the accounts that are in that list and not in the group "Terminated Employees".
Also note that we need to bypass the limit of Get-ADGroupMember as there are over 5000 members in this group.
$ADGroupName = "Terminated Employees"
$users = Get-Content C:\Shortcuts\users.txt
$InputPath= "C:\Scripts\T_Accounts.csv"
$a = #(Get-ADGroup $ADGroupName | Select-Object -ExpandProperty Member)
foreach ($user in $users) {
if ($a -contains $user) {
"Member found"
} else {
$SplitStep1 = ($Member -split ",",2)[0]
$SplitStep2 = ($SplitStep1 -split "=",2)[1]
$SplitStep2 = $SplitStep2 | Out-File -Append $InputPath
}
}
foreach ($value in (Get-Content $InputPath)) {
$b = Get-ADUser -Identity $value -Properties DisplayName, sAMAccountName, LastLogonDate, Enabled
}
I suggest using Import-Csv and Export-Csv cmdlets handling input and output files. And if we are searching disabled user accounts, which are members of specific group, there should be no need for the input file at all.
How about this oneliner:
Get-ADGroup "Terminated Employees" -Properties Members |
Select-Object -ExpandProperty Members |
Get-ADUser -Properties Enabled, Displayname, LastLogonDate |
Where-Object {$_.Enabled -eq $false} |
Select-Object DisplayName, SamAccountName, LastLogonDate, Enabled |
Export-Csv outfile.txt
Edit: Should have internalized the original question before rushing to answer. I think the clearest way is to create two sets of users and compare them, exporting results to CSV file.
$disabledusers = Get-Aduser -filter "Enabled -eq '$false'" -properties
DisplayName, SamAccountName, LastLogonDate, Enabled | select DisplayName,
SamAccountName, LastLogonDate, Enabled
$groupmembers = Get-ADGroup "Terminated Employees" -Properties Members|
Select-Object -ExpandProperty Members | Get-ADUser -Properties DisplayName,
sAMAccountName, LastLogonDate, Enabled | select DisplayName, SamAccountName,
LastLogonDate, Enabled
Compare-Object $groupmembers $disabledusers -Property enabled -PassThru |
?{$_.sideindicator -eq "=>"} | select DisplayName, SamAccountName,
LastLogonDate, Enabled | export-csv outfile.txt
You aren't requesting the Members property from ActiveDirectory in your Get-ADGroup command (also need to add the s to Members in your Select-Object ;) ).
$ADGroupName = "Terminated Employees"
$users = Get-Content C:\Shortcuts\users.txt
$InputPath= "C:\Scripts\T_Accounts.csv"
# Here we need to add the -Properties parameter to ask ActiveDirectory for the group Members
$a = #(Get-ADGroup -Identity $ADGroupName -Properties Members | Select-Object -ExpandProperty Members)
ForEach ($user in $users)
{
if ($a -contains $user)
{
"Member found"
}
else
{
$SplitStep1 = ($Member -split ",",2)[0]
$SplitStep2 = ($SplitStep1 -split "=",2)[1]
$SplitStep2 = $SplitStep2 | out-file -Append $InputPath
}
}
ForEach ($value in (Get-Content $InputPath))
{
$b = Get-ADUser -identity $value -Properties DisplayName, sAMAccountName, LastLogonDate, Enabled
}