Command to Unlock a locked domain user - powershell

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

Related

Creating a powershell script to unlock AD accounts

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

user to see Terms and conditions screen at password change

The company I am working for would like a splash screen that I did to pop up when ever a user changes password (90 day rule at present), this is mainly due to a external requirement.
One of the snags I have is that the system has no email to show me that a user is expiring, I am looking at a couple of things
A log output of expired accounts and locked accounts, ignoring accounts not logged on disabled accounts system etc.
On the 90 day policy a splash screen pops up with the t$c with an accept or decline window (they see this when they first turn the PC and pops up just before the logon box on basically saying by accepting you agree to have read blah and blah)
I do not know how to get either this to run as one script or have two separate scripts,
Any input greatly appreciated
Import-Module ActiveDirectory # Required for PowerShell 2.0 only
$a = (Get-Date).Date.AddDays(-89)
# The following line will build the variable based upon the noted criteria
$b = Get-ADUser `
-Property Name, SamAccountName, PasswordLastSet, CannotChangePassword, PasswordNeverExpires `
-Filter { (PasswordLastSet -lt $a) -and (PasswordNeverExpires -eq $false) } |
Where-Object { $_.CannotChangePassword -eq $false }
# The following line will display/export the data logging the accounts to be changed
# please note the Out-File path and change to suit your needs.
$b | Format-Table Name, PasswordLastSet, CannotChangePassword, PasswordNeverExpires -AutoSize |
Out-File -FilePath "C:\passwordchanges.txt"
# The following line will actually flag the accounts to require a password change
# (after -WhatIf is removed)
$b.SamAccountName | ForEach-Object {
Set-ADUser -Identity $_ -ChangePasswordAtLogon $true -WhatIf
}

Finding current logged on user(s) while running as SYSTEM (no environment variables)

I have created a PowerShell script that saves the current user to a report. When creating this report, it was working fine because I was using $env:USERNAME. However, now that the report is running under the SYSTEM account as a scheduled task, it saves the current user as "HOSTNAME$." Is there another easy way of getting the logged on users? The following doesn't work as well:
Get-WMIObject -class Win32_ComputerSystem | select username
Any ideas would be greatly appreciated as I need the current logged on user saved. I also need to run the report as NT AUTHORITY\SYSTEM to run the elevated tasks.
"Current user" is an ambiguous term that depends on what you're looking at. A user logged in on the desktop (locally or remotely)? A user running a background process? A user accessing an SMB share? WMI? WinRS?
Assuming that you want to identify which user is logged in on the desktop, you could check the owner of the explorer.exe process as described in this answer on ServerFault:
Get-WmiObject Win32_Process -Filter "Name='explorer.exe'" |
ForEach-Object { $_.GetOwner() } |
Select-Object -Unique -Expand User
I was able to gather the current logged on user by using tasklist in PowerShell:
$User = tasklist /v /FI "IMAGENAME eq explorer.exe" /FO list | find "User Name:"
$User = $User.Substring(14)
Works perfectly even when ran as SYSTEM.
I know this is old, it took me all morning to get this straightened out, this gets you the current logged on user and their my docs path, since environment variables don't work under the system account.
New-PSDrive HKU Registry HKEY_USERS
$user = get-wmiobject -Class Win32_Computersystem | select Username;
$sid = (New-Object System.Security.Principal.NTAccount($user.UserName)).Translate([System.Security.Principal.SecurityIdentifier]).value
$val = (Get-Item "HKU:\$sid\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
$myDocPath = $val.GetValue("Personal");
To test using a powershell account that runs as system, follow these instructions
http://powershell-guru.com/powershell-tip-53-run-powershell-as-system/
Assuming from your original script that you are looking to return just usernames, you could use this:
Get-Process -IncludeUserName | Select-Object UserName -Unique |
Where-Object {$.UserName -notlike 'NT AUTHORITY\SYSTEM' -and
$.UserName -notlike 'NT AUTHORITY\NETWORK SERVICE' -and $_.UserName
-notlike 'NT AUTHORITY\LOCAL SERVICE'} | Format-Table -Wrap -AutoSize
I liked the Get-Process answer from #MNiles, but made it a little simpler with the filtering for explorer from the other answers
Get-Process -IncludeUserName -Name explorer | Select-Object UserName -Unique

PowerShell: Get membership info for a computer account (not a user account)

Getting an ambiguous identity error. I can search successfully to return the group that a user account is a member of, but when I try to search for the groups that a computer account is a member of there is the ambiguous identity error. I tried to use a -type or -identity switch, but either I did not have the syntax correct or it was just not applicable.
Where my targeted computer account is called SNA00760856, I have been working on using...
Get-QADGroup -Containsindirectmember SNA00760856
Any massaging that I can do to the command to get the groups that the computer SNA00760856 is a member of? Dropping in a user account in place of the computer account works like a charm.
I have also tried to qualify the computer name with the domain info.
Ie SNA00760856.mydivision.mydomain.com or mydivision\SNA00760856
Also tried to collect the membership of the computer using which I know is wrong after a closer reading of the switch info....
Get-QADobject -IndirectMemberOf SNA00760856
Results in ambiguous identity as well.
You can get the group memberships of a computer in AD through the ActiveDirectory module with Get-ADPrincipalGroupMembership. You'll need to search via the computers DistinguishedName, which can be achieved by leveraging Get-ADComputer:
Get-ADPrincipalGroupMembership (Get-ADComputer SNA00760856).DistinguishedName
That'll return all of the group objects SNA00760856 is a member of.
If you want to clean up the output, use this
Get-ADPrincipalGroupMembership (Get-ADComputer ComputerName) | select-object name
If you export to a list use
Get-AdPrincipalGroupMembership ( Get-ADComputer XXXXXXX ) | Out-File C:\XXX\XXX
I used something to pull down the AD Computer information and the Computer membership into one Text file.
This is using $Env:computerName to get the name of computer script is run on. If you want to select a different computer, change out the variable $HostName = to a computer name of your choice. Example $HostName = "Janes-Laptop01" .
The computer you run this script on must have the Active Directory module installed for this to work.
Import-module -Name ActiveDirectory
$HostName = $Env:computerName
$path = "c:\temp\Computer_AD_Membership_Info_$($HostName)_$(get-date -f yyyyMMdd-hhmm).txt"
Echo "`r`n ******* Computer OU Information. ******* `r`n" | Out-File -FilePath $path -Encoding utf8 -Force ;
Get-AdComputer -Identity $($HostName) -Properties * | Out-File -FilePath $path -Encoding utf8 -Append -Force ;
Echo "`r`n ******* AD Groups Computer Member of. ******* `r`n" | Out-File -FilePath $path -Encoding utf8 -Append -Force ;
Get-ADPrincipalGroupMembership (Get-ADComputer $($HostName)).DistinguishedName | Out-File -FilePath $path -Encoding utf8 -Append -Force ;

Powershell - Adding computers to a security group in Active Directory

How can I add multiple computer accounts from within a text file into a security group in Active Directory? I put this snippet of code together but it only works with user accounts.
Import-Module ActiveDirectory
Get-Content C:\Servers.txt | Foreach-Object {Add-ADGroupMember "WSUS Auto Download and Notify for Install" $_}
The command you are looking for is Add-ADPrincipalGroupMembership.
Get-Content c:\servers.txt | Add-ADPrincipalGroupMember -memberof 'WSUS Auto Download and Notify for Install'
If you need to add the "$" at the end of the computer name, your command could use a scriptblock parameter (an anoymous function that can modify pipeline input).
Get-Content c:\servers.txt | Add-ADPrincipalGroupMember -memberof 'WSUS Auto Download and Notify for Install' -identity {"$_$"}
I use -Identity $_.objectGUID
$_$ didn't work for me.
EDIT: Ah, sorry, that's because I use Get-ADComputer to pipe it, and not a text file.
I had similar task found info on this link worked for me,
Run it in powershell as admin
Import-Module ActiveDirectory
$List=Get-Content c:\computers.txt
$List | foreach {Add-ADGroupMember -id ADGroupName -MEMBERS (Get-ADComputer $_)