Add domain to excel name - powershell

I'm currently connecting to a domain controller that is on a different domain. I'm trying to automate a report that tells us if a user is enabled and the last time they logged in. I'm looking to either add the domain name to the excel output or even rename the tabs inside the workbook. Currently I just name the excel sheet by the IP of the domain controller. I have a total of 8 domains Thank you for any help.
$domainserver = "ipaddress1" , "ipaddress2" , "ipaddress3"
foreach ($s in $domainserver){
Get-ADUser -Credential $Credential -Server $s -Filter {Enabled -eq $TRUE} -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-30)) -and ($_.LastLogonDate -ne $NULL)} |
Select Name,SamAccountName,LastLogonDate | Sort-Object LastLogonDate |
Export-Csv C:\temp\$s.csv -NoTypeInformation
}

Run Get-AdDomain against the same server, to find domain details:
$domainserver = "ipaddress1" , "ipaddress2" , "ipaddress3"
foreach ($s in $domainserver)
{
$domain = Get-AdDomain -Server $s -Credential $Credential
Get-ADUser -Credential $Credential -Server $s -Filter {Enabled -eq $TRUE} -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-30)) -and ($_.LastLogonDate -ne $NULL)} |
Select-Object -Property Name,SamAccountName,LastLogonDate,#{Label='Domain'; Expression={$domain.DnsRoot}} |
Sort-Object LastLogonDate |
Export-Csv C:\temp\$s.csv -NoTypeInformation
}

Related

Powershell: Get all ADUsers from a list, with a specific E-Maildomain and has not logged in in 90 days

Im trying to write a script that goes through a CSV-File, searches up the Username in our AD and then gives me these users, that have a specific E-Maildomain and hasn't logged in for the last 90 days.
Here's what I got so far:
import-csv C:\pathtofile\user.csv | ForEach-Object {
Get-ADUser $_.SamAccountName -Filter "EMailAddress -like '*#thedomain.com'" -Properties SamAccountName,LastLogonDate | Where { ($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)} | Sort | Select Name,SamAccountName,LastLogonDate
}
But it gives me this weird error:
Get-ADUser : A positional parameter cannot be found that accepts argument 'Username'.
I tried to put the E-Mailsorting into my where-statement, but it was not able to find any users then...
Can you guys may see what I'm doing wrong?
Thank you for your help.
Kind regards,
Gabe
You cannot use parameter -Filter together with -Identity.
(using Get-ADUser $_.SamAccountName implicitely uses the -Identity parameter)
To filter out only users that are in your CSV file AND that have a specific domain in their email address, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Import-Csv -Path 'C:\pathtofile\user.csv' | ForEach-Object {
$userSam = $_.SamAccountName
try {
$user = Get-ADUser $userSam -Properties EmailAddress, LastLogonDate -ErrorAction Stop
if (($user.LastLogonDate) -and $user.LastLogonDate -lt $refDate -and
$user.EmailAddress -like '*#thedomain.com') {
$user | Select-Object Name,SamAccountName,EmailAddress,LastLogonDate
}
}
catch {
Write-Warning "User '$userSam' not found"
}
}
To filter out all users that have a specific domain in their email address, so not using the csv at all, you can do:
$refDate = (Get-Date).AddDays(-90).Date # set to midnight
$result = Get-ADUser -Filter "EmailAddress -like '*#thedomain.com'" -Properties EmailAddress, LastLogonDate |
Where-Object { ($_.LastLogonDate) -and $_.LastLogonDate -lt $refDate } |
Select-Object Name,SamAccountName,EmailAddress,LastLogonDate | Sort-Object Name
# show the result on screen
$result | Format-Table -AutoSize
# and/or save to a new csv file
$result | Export-Csv -Path 'C:\pathtofile\filteredusers.csv' -NoTypeInformation

get OU Permissions for specific domain

I found a script that give you OU permissions for the domain the script is run on.
I want to use the same script from a single domain but scan other domains I specify.
The problem I think is with $schemaIDGUID = #{}
When run It's always for the domain the script is running on which is different from the domain I want to run the script on.
Here's the script I modified it to pickup specific domain.
$schemaIDGUID = #{}
$domain = "My specific domain name"
$report = #()
$schemaIDGUID = #{}
$ErrorActionPreference = 'SilentlyContinue'
Get-ADObject -Server $domain -SearchBase (Get-ADRootDSE -Server $domain).schemaNamingContext -LDAPFilter '(schemaIDGUID=*)' -Properties name, schemaIDGUID |
ForEach-Object {$schemaIDGUID.add([System.GUID]$_.schemaIDGUID,$_.name)}
Get-ADObject -SearchBase "CN=Extended-Rights,$((Get-ADRootDSE -Server $domain).configurationNamingContext)" -LDAPFilter '(objectClass=controlAccessRight)' -Properties name, rightsGUID |
ForEach-Object {$schemaIDGUID.add([System.GUID]$_.rightsGUID,$_.name)}
$ErrorActionPreference = 'Continue'
$OUs = #(Get-ADDomain -Server $domain | Select-Object -ExpandProperty DistinguishedName)
$OUs += Get-ADOrganizationalUnit -Server $domain -Filter * | Select-Object -ExpandProperty DistinguishedName
$OUs += Get-ADObject -Server $domain -SearchBase (Get-ADDomain -Server $domain).DistinguishedName -SearchScope OneLevel -LDAPFilter '(objectClass=container)' | Select-Object -ExpandProperty DistinguishedName
ForEach ($OU in $OUs) {
$report += Get-Acl -Path "AD:\$OU" |
Select-Object -ExpandProperty Access |
Select-Object #{name='organizationalUnit';expression={$OU}}, `
#{name='objectTypeName';expression={if ($_.objectType.ToString() -eq '00000000-0000-0000-0000-000000000000') {'All'} Else {$schemaIDGUID.Item($_.objectType)}}}, `
#{name='inheritedObjectTypeName';expression={$schemaIDGUID.Item($_.inheritedObjectType)}}, `
*
}
$report | Export-Csv -Path ".\$domain.OU_Permissions.csv" -NoTypeInformation
#Start-Process ".\$domain.OU_Permissions.csv"
break
$report |
Where-Object {-not $_.IsInherited} |
Select-Object IdentityReference, OrganizationalUnit -Unique |
Sort-Object IdentityReference
$filter = Read-Host "Enter the user or group name to search in OU permissions"
$report |
Where-Object {$_.IdentityReference -like "*$filter*"} |
Select-Object IdentityReference, OrganizationalUnit, IsInherited -Unique |
Sort-Object IdentityReference
Your problem has nothing to do with the $schemaIDGUID variable.
The problem is this line:
$report += Get-Acl -Path "AD:\$OU"
The AD: drive is mapped to ADWS on a DC in your home domain, on module import, so you'll need to explicitly create another drive that maps to the target domain instead:
$domain = "other.domain.tld"
# discover naming context + find a DC to query
$defaultNC = (Get-ADRootDSE -Server $domain).defaultNamingContext
$DC = Get-ADDomainController -Server $domain
# map new ADTemp:\ drive
New-PSDrive -Name ADTemp -PSProvider ActiveDirectory -Root $defaultNC -Server $DC
For the rest of the script, the only thing you need to change is the previously mentioned line, to:
$report += Get-Acl -Path "ADTemp:\$OU"

Powershell last logon query. Help setting up array to go thought all my domain controllers

This script below works, but every attempt I make to have it cycle through all my domain controllers fail. How do I add a array to go through all these OUs on all my domain controllers. Thanks in advance!
$OUs= “OU=Test1,OU=Test1,OU=Test1,OU=Test1,OU=All Users,DC=domain,DC=local",
"OU=Test2,OU=Test2,OU=Test2,OU=All Users,OU=Test2,DC=domain,DC=local",
"OU=Test3,OU=Test3,OU=Test3,OU=All Users,OU=Test3,DC=domain,DC=local",
"OU=test4,OU=test4,OU=test4,OU=All Users,OU=test4,DC=domain,DC=local",
"OU=Test5,OU=test5,OU=Test5,OU=All Users,OU=test5,DC=domain,DC=local”
$OUs | ForEach-Object
{
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $_ -Properties Name,SamAccountName,LastLogonDate |
Where-Object {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)}
} |
Sort LastLogonDate |
Format-Table -Property Name,SamAccountName,LastLogonDate, DistinguishedName |
Out-String
Below you have now an array of your OUs. Please try whether that works for you now.
$OUs= #(
“OU=Test1,OU=Test1,OU=Test1,OU=Test1,OU=All Users,DC=domain,DC=local",
"OU=Test2,OU=Test2,OU=Test2,OU=All Users,OU=Test2,DC=domain,DC=local",
"OU=Test3,OU=Test3,OU=Test3,OU=All Users,OU=Test3,DC=domain,DC=local",
"OU=test4,OU=test4,OU=test4,OU=All Users,OU=test4,DC=domain,DC=local",
"OU=Test5,OU=test5,OU=Test5,OU=All Users,OU=test5,DC=domain,DC=local”
)
I would also suggest to break your line after every pipe in order to cut the line. That makes it far easier to read for you, plus your colleagues.
$OUs | ForEach-Object
{
Get-ADUser -Filter {Enabled -eq $TRUE} -SearchBase $_ -Properties Name,SamAccountName,LastLogonDate |
Where-Object {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)}
} |
Sort LastLogonDate |
Format-Table -Property Name,SamAccountName,LastLogonDate, DistinguishedName |
Out-String
You mention cycling through your domain controllers, but then you go on to ask about OUs. I suspect you want DC's, because each DC might have a different Last Logon Time for the user.
You can omit the -SearchBase and search all OU's, if you're looking to get this data for all users.
$Domains = Get-ADDomainController -Filter * #Note, this shows all DCs- you may have some without ADWS Installed, which won't handle the WHERE.
foreach ($domain in $Domains) {
Get-ADUser -Filter {Enabled -eq $TRUE} -Server $domain -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)} |
Export-CSV -Path 'UsersNotRecentlyLoggedIn.CSV' -Append
}
If you only want one DC, but all OUs
$Domains = Get-ADDomainController -Discover -Service ADWS
foreach ($domain in $Domains) {
Get-ADUser -Filter {Enabled -eq $TRUE} -Server $domain -Properties Name,SamAccountName,LastLogonDate |
Where {($_.LastLogonDate -lt (Get-Date).AddDays(-7)) -and ($_.LastLogonDate -ne $NULL)} |
Export-CSV -Path 'UsersNotRecentlyLoggedIn.CSV' -Append
}

Select users from AD randomly

We've been tasked with creating a process to review random employee's web traffic on a quarterly basis. I have started a script in Powershell that selects 10 random users from a specific OU, but I'm still getting some unneeded data. I need help filtering down the list further. The output gives me users that have been disabled and left in the OU as well as PRN employees that haven't signed on in a long time. I would like to search AD accounts that has an email address & a logon, modified within the last 3 months. Here is an example of the code I have so far.
Get-ADUser -SearchBase "ou=ouname,ou=ouname,dc=domainname,dc=suffix" -Filter * | Select-Object -Property Name | Sort-Object{Get-Random} | select -First 10
[Edit: Question Answered]
Here is my final script, added $_.passwordlastset as a search attribute since this will pickup users that have changed their password in the last 90 days.
$DateFrom = (get-Date).AddDays(-90)
Get-ADUser -Properties * -Filter {enabled -eq $True} -SearchBase "ou=ouname,dc=domainname,dc=suffix" | where { $_.passwordlastset -gt $DateFrom -and $_.mail -ne $null } | Sort-Object {Get-Random} | select name, sAMAccountName -First 10
Get-ADUser -Properties name, mail, lastlogondate -Filter {enabled -eq $True} -SearchBase "ou=ouname,ou=ouname,dc=domainname,dc=suffix" | select name, mail, lastlogondate | where { $_.lastlogondate -gt (Get-Date).AddDays(-90) -and $_.mail -ne $null }
Here a start.
Try this:
$timeFrame = (get-Date).AddDays(-90)
get-aduser -SearchBase 'ou=ouname,ou=ouname,dc=domainname,dc=suffix' -Filter * -Properties * |
Where-Object {$_.whenChanged -gt $timeFrame -and $_.mail -ne $null} |
Select-Object -Property Name | Sort-Object{Get-Random} | select -First 10
Change the -Filter value:
# LastLogontimeStamp is not guaranteed to be updated on every login, so 30 days + 14 days margin
$threshold = (Get-Date).AddDays(-44).ToFileTime()
Get-ADUser -Filter {Enabled -eq $true -and LastLogontimeStamp -gt $threshold} -SearchBase "ou=ouname,ou=ouname,dc=domainname,dc=suffix" | Sort-Object {Get-Random} | Select Name -First 10
This filter will ensure that AD only returns Enabled users and that their lastLogontimeStamp value has been updated within the last month and a half
This will do everythign the OP stated:
$timeFrame = (get-Date).AddDays(-90)
get-aduser -SearchBase 'YourOU,DC=Domain,DC=com' -Filter * -Properties * |
Where-Object {$_.whenChanged -lt $timeFrame -and $_.mail -ne $null -and $_.Enabled -eq $true} |
Select-Object -Property Name | Sort-Object{Get-Random} | select -First 10
This should meet all the OPs checkpoints via the snippets:
"I would like to search AD accounts that has an email address"
$_.mail -ne $null
"& a logon"
$_.Enabled -eq $true
"modified within the last 3 months"
$_.whenChanged -lt $timeFrame

Powershell script for listing specific expiring accounts

I am a bit of a powershell novice so any help is greatly appreciated. I am using the following script to get and export a list of AD accounts that are expiring, that match the specific description item. I have not been able to get it to successfully include the expiration date. This is the script as it currently works.
$users = Get-QADUser -SizeLimit 10000 -SearchRoot 'company.com/employees' -IncludedProperties "description" | where {$_.description -like "non-company*" }
#(foreach($user in $users)
{
$user | Select-Object DisplayName,LogonName,description
}) | export-Csv "C:\Users\svcacct\Documents\Steve Test Scripts\test.csv" -noType
I have tried adding -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} but it just fails.
Thanks for your help.
You can try this:
Import-Module ActiveDirectory
$users = Get-ADUser -Filter {(Enabled -eq $True -and PasswordNeverExpires -eq $False) -and (Description -like "non-company*")} -SearchBase "OU=employees,DC=Company,DC=com" -Properties Description,DisplayName,sAMAccountName
#(ForEach($user In $users){
$user | Select-Object DisplayName,sAMAccountName,Description
}) | Export-Csv "C:\Users\svcacct\Documents\Steve Test Scripts\test.csv" -noType