How to check if AD user has direct reports - powershell

I am trying to write a PowerShell script to check if an AD-User has direct reports (meaning, if that AD-User is a manager), with following code but no go, Any help?
Import-Module ActiveDirectory
Set-Location AD:
$SamAccountName = "Mansings"
$test = Get-Aduser -identity $SamAccountName -Properties directreports | %{$_.directreports}
Write-Host $test
if ($test -eq $null)
{
Write-Host "He is a Manager"
}
else
{
Write-Host "He is not a manager"
}

Got the working script now
Import-Module ActiveDirectory
Set-Location AD:
$SamAccountName = "Mansings"
$test = Get-Aduser -identity $SamAccountName -Properties directreports | %{$_.directreports}
Write-Host $test
if (!$test)
{
Write-Host "He is an employee"
}
else
{
Write-Host "He is a Lead"
}
it's working. Thank you.

Related

POWERSHELL - Display Users AD Group That Starts With a Specific Character

This is my script it can display all the AD group that is assigned to a user account. I just don't know the syntax on how to do a wildcard search.
Write-Host "'Get AD Groups"
$userName = Read-Host -Prompt "Please enter the LDAP ID"
$ADUser = Get-ADUser -Filter "SamAccountName -eq '$userName'" | Select-Object SamAccountName
if($ADUser -eq $null) {
Write-Host "$userName does not exist in AD or account is inactive" -ForegroundColor Red
Continue
} else {
$sourceUser = Get-ADUser -Identity $userName -Properties MemberOf
$sourceGroups = $sourceUser.MemberOf
Foreach($group in $sourceGroups) {
$thisgroup = $group.split(",")[0].split("=")[1]
Write-Host "$thisgroup"
}
}

Coping AD member groups for Computers - Poweshell

Trying to create a script that Copies groups from 1 Computer to another. The script also has a list of Groups that won't copy over. I have been able to debug the script until line 42 with the below error message.
Here is my current script:
*If($Hostname -eq 'ISD-TS-01' -or 'ISD-TS-03' -or 'ISD-TS-04')
{
function Show-Menu
{
param (
[String]$Title = 'Copy AD Computer Groups Groups'
)
cls
Write-Host ================ $Title ================
$ComputerToCopy = Read-Host -Prompt 'Input the Computer to copy'
$Computer = $ComputerToCopy
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive Select -ExpandProperty SamAccountName
If ($members -contains $Computer) {
Write-Host "$Computer is in $group" -ForegroundColor Red
Pause
Exit
} Else {
Write-Host Starting Script -ForegroundColor Green
}
}
$NewComputer = Read-Host -Prompt 'Input the name of the new computer'
Get-ADComputer -Identity $ComputerToCopy -Properties memberof -Verbose | Select-Object -ExpandProperty memberof -Verbose |
Add-ADGroupMember -Members $NewComputer -PassThru -Verbose
$Computer = $NewComputer
$groups = 'G-SCCM-SD-EGRESS_WIN10'
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
If ($members -contains $Computer) {
#remove-adgroupmember -Identity "$Group" -Member "$NewComputer" -Confirm:$false
Write-Host "$Computer has been removed from $group" -ForegroundColor Cyan
} Else {
Write-Host "$Computer is not a member of $group" -ForegroundColor Green
}
}
Write-Host "1: Press '1' to Retry."
Write-Host "Q: Press 'Q' to quit."
}
do
{
show-menu
$input = Read-Host "Select an option"
Switch ($input)
{
'1' {
cls
'You chose option #1'
}'2'{
cls
'You chose option #2'
}'q'{
return
}
}
pause
}
until ($input -eq 'q')
}
Else {
Write-Host "Script Cannot be Run on this Host. Please use TS-01"
Read-Host
}*
Powershell Error
You have to use the SamAccountName of the station! the SamAccountName is the computer name with $ at the end
you can use this in your script to find it
Get-ADComputer -Identity $NewComputer | Select-Object -ExpandProperty SamAccountName

Powershell issue with executing in Task Scheduler

I have below script that add users to o365 group at start of their work as below:
$DateMaxTime = (Get-date).AddDays(0)
$DateMaxTimeNew = (Get-date).AddDays(-30)
$usersRO = Get-ADUser -Filter * -Properties * -SearchBase "OU=Users,OU=Resources,OU=Romania,OU=DataManagement,DC=USA"|where {$_.Description -like "*TEMP*" -or $_.Description -like "*PERM*" } |select samaccountname,description,name
$groupsRO = '#O365-EXTERNALACCESS'
$FinalResultRO = New-object System.Collections.ArrayList
ForEach($groupRO in $groupsRO){
$membersRO = Get-ADGroupMember -Identity $groupRO -Recursive | Select -ExpandProperty samaccountname
Foreach ($userRO in $usersRO){
$AcountNameRO = $userRO.samaccountname
$DatePartRONew = get-aduser -identity $AcountNameRO -Properties * | Select-Object whenCreated
$DatePartSubsRONew = $DatePartRONew.whenCreated
$DataPartROdesc=$userRO.description
$expressionRO = ([regex]'(\d{2}/\d{2}/\d{4})').Match($DataPartROdesc).Groups[0].Value
$DatePartRO= $expressionRO
$FinalDateRO = [datetime]::ParseExact($DatePartRO,'dd/MM/yyyy',$null)
If ($DatePartSubsRONew -lt $DateMaxTimeNew){
Write-Host "$AcountNameRO ouf of date scope"}
else {Write-Host "$AcountNameRO in scope"
If ((get-date $FinalDateRO.Date) -eq (get-date $DateMaxTime.Date)){
Write-Host "$AcountNameRO is a today Starter"
If ($membersRO -notcontains $AcountNameRO ) {
Write-Host "Adding external group $groupRO for: $AcountNameRO"
Add-ADGroupMember -Identity "#O365-EXTERNALACCESS" -Members $AcountNameRO
$FinalResultRO.Add((New-Object psobject -Property #{User=$AcountNameRO}))
}
Else {Write-Host "$AcountNameRO exists in group $groupRO"}
}Else {Write-Host "$AcountNameRO is not a Starter"}
}
}
}
$listRO = [array]$FinalResultRO |Select User |Out-String
$listRO.gettype()
if [string]::IsNullOrEmpty($listRO){
Write-Host "nothing to send"
}
Else {
Write-Host "Mail sent"
Send-MailMessage -From "mail1#donut.com" -To "mail2#donut.com" -Subject "Following users have been granted external access rights" -smtpServer "donut" -body "$($listRO)"
}
I run this script daily in task scheduler with higest privilage .
For some reasons, sometimes when script is executing , telling me that users has been added to group but its not changing in Active DIrectory . Only when I run the script second time its working (manually on powershell , not using task scheduler).
What can be a reason for this ?
I would check this line
Add-ADGroupMember -Identity "#O365-EXTERNALACCESS" -Members $AcountNameRO
Your code runs even if it hits some error for whatever reason. I would add a try catch statement to figure out what went wrong (could be DNS, Network, some problem with $AcountNameRO variable ...).
try {Add-ADGroupMember -Identity "#O365-EXTERNALACCESS" -Members $AcountNameRO}
catch{
write-host "something went wrong in Add-ADGroupMember"
Send-MailMessage -From "mail1#donut.com" -To "mail2#donut.com" -
Subject "please check Add-ADGroupMember"
write-host $_
}
Of course, write-host is a bad idea when running a scheduled task because you do not see the output. So I would dump the output in a file or the eventlog or write an email. Bill wrote a nice summary of what you could do concerning the logging.
https://adamtheautomator.com/powershell-logging/

Powershell command to replace AD user's title in title field not working?

I have created a script for a project with some code which I was given fused with my own. Most of the commands which are great, but unfortunately two commands are not working.
These commands are:
Set-ADUser $UserName -replace #{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Any ideas? I appreciate the help!
Here is the full script:
$UserName = Read-Host "Please enter username to be disabled"
if ($UserName) {
''
} Else {
'User not Found'
}
Disable-ADAccount $UserName
Get-ADUser $UserName -Properties MemberOf | ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false }
$title = get-aduser $UserName -properties title
$title = $title.title
$old=Get-ADuser $UserName -properties Description
$old = $old.description
$new = "DISABLED " + $old
set-aduser $UserName -description $new
set-aduser $UserName -clear "manager"
set-aduser $UserName -clear "telephonenumber"
# these two:
set-aduser $UserName -replace #{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
I think it's better to clear up a bit of your code. Have a look at this:
$SamAccountName = Read-Host 'Please enter the SamAccountName of the user you want to disable'
$VerbosePreference = 'SilentlyContinue'
$VerbosePreference = 'Continue'
Try {
$ADUser = Get-ADUser -Identity $SamAccountName -Properties MemberOf, Title, Description
Write-Verbose "User '$($ADUser.Name)' found in AD"
}
Catch {
throw "No user found in AD with SamAccountName '$SamAccountName'"
}
Write-Verbose 'Disable user'
Disable-ADAccount $ADUser
foreach ($Group in $ADUser.MemberOf) {
Write-Verbose "Remove user from group '$Group'"
Remove-ADGroupMember -Identity $Group -Members $ADUser -Confirm:$false
}
$NewTitle = "Former Employee {0}" -f $ADUser.Title
Write-Verbose "Set 'Title' to '$NewTitle'"
Set-ADUser -Identity $ADUser -Title $NewTitle
$NewDescription = "DISABLED {0}" -f $ADUser.Description
Write-Verbose "Set 'Description' to '$NewDescription'"
Set-ADUser -Identity $ADUser -Description $NewDescription
foreach ($Property in #('Manager', 'telephonenumber')) {
Write-Verbose "Clear property '$_'"
Set-ADUser -Identity $ADUser -Clear $Property
}
$NewTargetPath = "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Write-Verbose "Move AD User to '$NewTargetPath'"
Move-ADObject -Identity $ADUser -TargetPath $NewTargetPath
Some tips:
Use Write-Verbose to show what is happening in the script. Yuo can disable/enable this by commenting out the VerbosePreference.
Always start with retrieving an object instead of working with text strings ($UserName vs $ADUser). See Get-ADUser as the very first action.
Work with Try/Catch in case things fail.
Always use the parameter names. It makes it more clear on what you're trying to do.

Powershell Script to check if Active Directory User Last Logon

I'm trying to write a powershell script that accepts an username as an argument, and displays the last logon time of the user. If the user has not logged in before, the message has not logged in before should be displayed.
For example, if you run .\lastlogon -username marywong the message is displayed:
marywong last logon time 13/07/2017
If you run .\lastlogon -username guest, I get the message:
guest has not logged in before
Below is my code, however it doesn't seem to be looping into the else loop when the user has not logged in before.
param (
[string]$username
)
$user = Get-ADUser -Filter {sAMAccountName -eq $username} | Get-ADObject -Properties lastLogon
$lastlogontime = $user.lastlogon
If ($user -ne $Null) {
if($user.LastLogon -gt $time) {
$displaylastlogon = [datetime]::FromFileTime($lastlogontime)
Write-Host $username " last logon time" $displaylastlogon
}
else {
$displaylastlogon = [datetime]::FromFileTime($lastlogontime)
Write-Host $username " has not logged in before"
}
}
else {
Write-Host $username " does not exist"
}
There is information to be gained from using Get-ADUser and Get-ADObject separately. If the user has never logged in, they are still a user that exists. That is different from a user that does not exist.
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, Position = 0)]
[string]$username
)
$user = Get-ADUser -Filter {SamAccountName -eq $username}
if ($user -ne $null) {
$userlogon = $user | Get-ADObject -Properties lastLogon
if ($userlogon.LastLogon -ne $null) {
$lastlogontime = [DateTime]::FromFileTime($userlogon.LastLogon)
Write-Host $username " last logon time" $lastlogontime
} else {
Write-Host $username " has not logged in before"
}
} else {
Write-Host $username " does not exist"
}
When you use the lastLogon you get a format that AD uses...
then when the if is running you get
Could not compare "131820853335016078" to "09/24/2018 18:18:57". Error: "Cannot convert value "9/24/2018 6:18:57 PM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'.""
so it's not getting to the else..
try using the LastLogonDate property, it will help you more.
try to use this:
$user = Get-ADUser -Filter {sAMAccountName -eq $username} -Properties LastLogonDate
$lastlogontime = $user.lastlogonDate
Edit:
you have some more issues with you code:
You need to remove the displaylastlogon
you cant use -gt because it will always be false.. the user cant log in the future.. you need to use -lt
here is the full script, working:
$user = Get-ADUser -Filter {sAMAccountName -eq $username} -Properties LastLogonDate
$lastlogontime = $user.lastlogonDate
If ($user -ne $Null) {
if($lastlogontime -lt $time)
{
Write-Host $username " last logon time" $lastlogontime
}
else
{
Write-Host $username " has not logged in before"
}
}
else
{
Write-Host $username " does not exist"
}
Another Edit:
I just notice that its not answering the case when user never logon, because you will get $null and $null is lower then the current Time. so you need to check that the lastlogontime is not null
change the if to this:
if($lastlogontime -ne $null -and $lastlogontime -lt $time)