Creating a powershell script to unlock AD accounts - powershell

I am new to Powershell, I am trying to create a fast script that I can run as admin with one click of a button to display the current accounts locked out first and then have a pre written text in the command line, in which I can just type the SAM account name I want to unlock, since I don't want to unlock them all at once necessarily.
My question is, how can I get PS to run a command and then pre write text into command line for the to fill the rest in and execute?
Search-ADAccount -lockedout | Select-Object Name, SamAccountName
Unlock-ADAccount -Identity samAccountName

Read-host is one option when working interactively.
e.g.
Search-ADAccount -lockedout | Select-Object Name, SamAccountName
$samAccountName = Read-Host -Prompt 'Enter the samAccountName of the account you wish to unlock'
if($samAccountName) {
Unlock-ADAccount -Identity $samAccountName
}

in order to prompt a text for the users to be unlocked, you can use the read-host command:
and you can unlock multiple accounts at once as follow:
Search-ADAccount -lockedout | Select-Object Name, SamAccountName
$Samaccountnames = Read-Host "Enter SamAccountNames of accounts to unlock separated by comma ','"
$Samaccountnames =$Samaccountnames.split(",")
$Samaccountnames | % {Unlock-ADAccount -Identity $_}

this command will unlock all AD users in a domain.
if you want o add confirnation add -Confirm
Search-ADAccount -Lockedout | Unlock-AdAccount -Confirm
if not:
Search-ADAccount -Lockedout | Unlock-AdAccount
this command will final all locked user account:
Search-ADAccount -lockedout | Select-Object Name, SamAccountName

Related

Bulk Disable PowerShell Script Not Executing

I am kinda new to powershell and started a role in support. Working on a powershell script that will do the following things:
Disable a user account
Remove all AD Groups except for Domain Users
Edit the description
Move AD object to a disabled users OU
I think I can probalby change the "$TargetOU = OUPath" because the disabled users OU is never really going to change...if that's the issue then i'll feel like a dumby lol.
I am trying and failing to complete this! I don't know what is going wrong. Powershell isn't faulting out or anything it is just not executing?
Thank you for any help!
My code is here:
Import-Module ActiveDirectory
$TargetOU = "OU=DisabledUsers"
Import-Csv "C:temp\DisableTest.csv" | ForEach-Object {
$samAccountName = $_."samAccountName"
Get-AdPrincipalGroupMembership -Identity $samAccountName {Where-Object -Property Name -Ne -Value 'Domain Users' | Remove-AdGroupMember -Members $samAccountName}
Get-ADUser -Identity $samAccountName | Disable-ADAccount
Get-ADUser -Identity $samAccountName -Description "Disabled Per Request XXXX"
Move-ADObject -Identity $UserDN -TargetPath $TargetOU
}
Need it to do four things:
Disable a user account
Remove all AD Groups except for Domain Users
Edit the description
Move AD object to a disabled users OU
You have several issues:
$TargetOU = "OU=DisabledUsers"
This should be the full distinguished name, so something like OU=DisabledUsers,DC=example,DC=com
Get-AdPrincipalGroupMembership -Identity $samAccountName {Where-Object -Property Name -Ne -Value 'Domain Users' | Remove-AdGroupMember -Members $samAccountName}
The sytax here is messed up. You want to pipe (|) the results from Get-AdPrincipalGroupMembership into Where-Object, but you have braces ({). The closing brace at the end of the line is thus unnecessary. The Where-Object cmdlet also lets you simplify the syntax to something more readable, like Where Name -ne 'Domain Users'.
Get-ADUser -Identity $samAccountName -Description "Disabled Per Request XXXX"
This should be Set-ADUser, which is explains why this isn't changing anything.
Move-ADObject -Identity $UserDN -TargetPath $TargetOU
You haven't defined $UserDN, so it's not going to find the user. And as already mentioned , the target path should be the full distinguished name.
You're also looking up the account several times. Every time you pass just the username, it has to search for the account. As you have it, it would be searching for the account 5 times. You can avoid that (and speed things up) by calling Get-ADUser once and passing the result into each of the other commands.
And just for simplicity, you can omit -Identity since the first parameter is assumed to be the identity.
Putting everything together, it would look something like this:
Import-Module ActiveDirectory
$TargetOU = "OU=DisabledUsers,DC=example,DC=com" #Change this to the real value
Import-Csv "C:temp\DisableTest.csv" | ForEach-Object {
$user = Get-ADUser $_."samAccountName"
Get-AdPrincipalGroupMembership $user | Where Name -ne 'Domain Users' | Remove-AdGroupMember -Members $user
Disable-ADAccount $user
Set-ADUser $user -Description "Disabled Per Request XXXX"
Move-ADObject $user -TargetPath $TargetOU
}

Powershell: Export group members from external domain

I want to export users of some large groups.
The groups are filled with other groups and the members of those groups are users from a trusted external domain.
When I run this script if gives an error:
$Users = Get-ADGroupMember -Identity 'Group' -recursive |
Where {$_.ObjectClass -eq 'User'} |
Get-ADUser -Properties SamAccountName |
Select-Object SamAccountName
Error: The operation being requested was not performed because the user has not been authenticated.
And that's the other domain that requests authentication.
How can I achieve this in the script?
Thanks
Whenever you run an AD group cmdlet, it uses your logged-in credentials to query Active Directory. This says you need to be on a domain joined computer logged in as an AD user that has permission to query.
You are on a workgroup computer or need to authenticate to AD as a different user. Then you need to provide credentials. Like other ps cmdlets, Get-ADGroupMember has a -Ceedential parameter and This parameter allows you to specify a username and password to use for the authentication.
This will show a dialog to prompt you for your credentials:
$Users = Get-ADGroupMember -Identity 'Group' -recursive -Credential (Get-Credential) | Where {$_.ObjectClass -eq 'User'} | Get-ADUser -Properties SamAccountName | Select-Object SamAccountName
Or you can specify credentials:
$cred = New-object System.Management.Automation.Pscredential User, Password
AND -Credential $cred

Get-ADUser using old pre-Windows 2000 Logon name instead of CN

I'm trying to use Add-ADGroupMember cmdlet in PowerShell, but I've realized PS doesn't recognize the object if I use the CN, and it only seems to recognize the pre-Windows 2000 logon name.
That attribute had a character limitation of 20 characters, so some of our accounts have different CNs and Pre-Windows 2000 logon names.
My whole process is:
Step 1: Get a list of my users (this gives me the legacy pre-Windows 2000 logon names):
Get-ADUser -Filter {department –notlike “Field”} –SearchBase “OU=Accounts,OU=HQ,OU=Production,DC=MYDC,DC=MYDC1,DC=MYDC2” -Properties department | select name | Out-file C:\Users\Public\Users.txt
Step 2: Add those users to my security group:
$UserList = Get-Content "C:\Users\Public\Users.txt"
$GroupName = "MY-SEC-Group"
$Members = Get-ADGroupMember -Identity $GroupName -Recursive | Select -ExpandProperty SAMAccountName
ForEach ($user in $UserList)
{
If ($Members -contains $user)
{
Write-Host "$user is member of $GroupName"
}
Else
{
Write-Host "$user is not a member. Attempting to add now, run script again for verification"
Add-ADGroupMember -Identity $GroupName -Members $User
}
}
For all accounts where the legacy logon name and the CN are the exact same, there are no issues. But in situations where they are different, I get the error "Object not found"
Is there a better/more up-to-date cmdlet to use? Maybe one that relies on the CN instead of the legacy logon name? Or do I need to add in CN to all my scripts now?
Get-ADGroupMember returns objects that point to the concrete user in ActiveDirectory and contain different fields including distinguishedName, SamAccountName , SID, Name and so on. In your code you create a txt file with Names (not SamAccountName) but use SamAccountName in Get-ADGroupMember. So, you just compare names with SamAccountName values (that's incorrect).
Just replace
select name | Out-file C:\Users\Public\Users.txt
with
select SamAccountName | Out-file C:\Users\Public\Users.txt
SamAccountName (just as SID) is the unique attribute in AD -
https://blogs.technet.microsoft.com/389thoughts/2017/02/03/uniqueness-requirements-for-attributes-and-objects-in-active-directory/ so, you should use it in your code.

Command to Unlock a locked domain user

I'v been using these to list locked users in my domain and prompt me for input samaccountname to unlock desired one:
I did it with 3 file.
first one is ps1 to list all of them
import-module activedirectory
search-adaccount -lockedout | select name, samaccountname, OU
second one is another ps1 file:
$user = Read-Host "Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list"
Search-ADAccount -LockedOut | Where {$_.samaccountname -eq $user} | Unlock-ADAccount
and for executing above files, i use a .bat file:
:loop
powershell.exe -ExecutionPolicy Bypass -File c:\ps\lockedlist.ps1
powershell.exe -ExecutionPolicy Bypass -File c:\ps\unlock.ps1
cls
goto loop
and when i run it... it list all locked users and i can copy paste each samaacount name to unlock them
BUT the problem is,when I want to do it with ONE ps1 file it doesnt work. it just ask for samaccountname but it doesnt list it
import-module activedirectory
search-adaccount -lockedout | select name, samaccountname, OU
$user = Read-Host "Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list"
Search-ADAccount -LockedOut | Where {$_.samaccountname -eq $user} | Unlock-ADAccount
i know .bat file will be pretty same...
thanks to anyone who reads and helps.
Powershell always tries to optimize the output it gives for you. So the order of the output might not be the same as you expect it from the commands you have in a script. If possible it will concatenate output to be more readable especially when it's the same type of objects. To break this you could use a format cmdlet like Format-Table par example.
Search-ADAccount -LockedOut |
Select-Object -Property Name, sAMAccountName, DistinguishedName |
Format-Table
$user = Read-Host -Prompt 'Enter user account (SAMACCOUNTNAME) to unlock or press ENTER to refresh list'
Search-ADAccount -LockedOut |
Where-Object -FilterScript {$_.samaccountname -eq $user} |
Unlock-ADAccount
At least, it worked in my environment.
And BTW: Since Powershell version 3 you don't need to explicitly import the modules anymore. They will be imported automaticaly. Better would be to use a #Requires statement like #Requires -Modules activedirectory on top of the script. That would even prevent the script to run if there's no active directory module installed

How to add wildcard for disable accounts with PowerShell?

I have the following PowerShell command which I run to show me all the numbers that have been assigned to users. However, I'd like to narrow it down to show me ONLY accounts which have been disabled BUT still have an number assigned, I've tried a few wildcards within 'enabled' but then it fails to run.
Get-ADUser -Properties "msRTCSIP-Line",mail,l,c,Enabled,CanonicalName -LDAPFilter "(msRTCSIP-Line=tel:+44*)" |
Select Name,CanonicalName,mail,l,c,Enabled,"msRTCSIP-Line" |
ft -AutoSize
The enabled/disabled status is encoded in the userAccountControl attribute. Try an LDAP filter like this:
(&
(objectclass=user)
(objectcategory=user)
(useraccountcontrol:1.2.840.113556.1.4.803:=2)
(msRTCSIP-Line=tel:*)
)
or collapsed:
(&(objectclass=user)(objectcategory=user)(useraccountcontrol:1.2.840.113556.1.4.803:=2)(msRTCSIP-Line=tel:*))
I think the best way is to get all disabled accounts then pipe it to your code :
Search-ADAccount -AccountDisabled -UsersOnly | %{
Get-ADUser $_ -Properties "msRTCSIP-Line",mail,l,c,Enabled,CanonicalName -LDAPFilter "(msRTCSIP-Line=tel:+44*)" |
Select Name,CanonicalName,mail,l,c,Enabled,"msRTCSIP-Line"
}