Find a user by their real name in Active Directory - powershell

This script is for reseting passwords on AD users if they lost it and need to make a new one. But let's say we dont know the username only their real name, so we want to search for the username and insert it to $Username.
function Reset_Password_Account () {
$Username = Read-Host "Enter your username"
Write-Host "Changing Password for account" $Username
$Newpassword = Read-Host "Enter Temporary Password" -AsSecureString
Write-Host "Running Script..."
Set-ADAccountPassword $Username -NewPassword $Newpassword
Write-Host "Temporary password set"
Set-ADUser $Username -ChangePasswordAtLogon $True
Write-Host "You can now change password on login"
# Stop powershell from exiting after script is run
Read-Host "Press enter to exit"
}
$Readhost = Read-Host "To run script: Enter y
To decline script: Enter n and exit PowerShell
Press Enter to accept your input. ( y / n )"
switch ($ReadHost) {
Y {Reset_Password_Account}
N {exit}

I would recommend using Ambiguous Name Resolution, it searches a range if AD Attributes (list in link) and finds any matches.
The example query below would return both Jimmy Smith and Jim Smith-Williams
Get-ADUser -LDAPFilter "(anr=Jim Smith)"
It will search for all objects where any of the naming attributes start with the string "jim smith*", plus all objects where (givenName=jim*) and (sn=smith*), plus objects where (givenName=smith*) and (sn=jim*).

Related

Assigning a password to a word doc using Read-host using Powershell

I have the following script to update passwords with an autogenerated 32 character password. It then makes a password-protected Word doc so that we can update our secure password library. Generating the password works fine.
The problem occurs when I try to assign a password to the password-protected word doc. I can hard code a string directly such as:
$PL_Document.Password = 'blah'
In the case where I hard code it everything works fine. I get a password protected word doc with the login info.
However, when I try to read it in using Read-host then assign it, the script hangs.
Add-Type -AssemblyName System.Web
cls
#************ Create Document ******************************
function CreateDocument
{
$PL_Word = New-Object -ComObject Word.Application
#$PL_Word.Visible = $true
$PL_Document = $PL_Word.Documents.Add()
$PL_Report = 'C:\TEMP\MyDoc.docx'
$PL_Document.SaveAs([ref]$PL_Report,[ref]$SaveFormat::wdFormatDocument)
$PL_Selection = $PL_Word.Selection
#****************** Password Protect the Word File ********
$PL_PwdEntry = Read-Host ("Enter the password for the text document record") -AsSecureString
$PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry
$PL_Document.Password = $PL_WdPWD
#************** Write Password to Document *************************************
$PL_Selection.TypeParagraph()
$PL_Selection.TypeText("Username: $PL_UN")
$PL_Selection.TypeParagraph()
$PL_Selection.TypeText("Password: $PL_PWD")
#************** Close Document *************************************
$PL_Document.Close()
$PL_Word.Quit()
}
#****************** Create Password ************************
$PL_PWD = [System.Web.Security.Membership]::GeneratePassword(32,3)
Write-Host "`n`n"
$PL_UN = "Prime\"+(Read-Host ("Enter the username. Entering the Primelending domain is not neccessary."))
Write-Host "`nSummary of the change" -f Yellow
Write-Host "============================" -f Yellow
Write-Host "`nUsername: " -NoNewline
Write-Host "$PL_UN" -f Yellow
Write-Host "New Password: " -NoNewline
Write-Host "$PL_PWD`n" -f Yellow
Write-Host "Do you want to update AD (Y/N)" -NoNewline -f Yellow
$PL_Query = Read-Host (" ")
If ($PL_Query.ToUpper() -eq "Y") {
Write-Host "`nMaking change" -f Green
#Set-ADAccountPassword -Identity $PL_UN -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$PL_PWD" -Force)
CreateDocument
}
else {Write-Host "`nAbandoning change" -f Green }
The $PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry part of your script will not be returning a plain text password and instead will be an encoded version of the password that will have a much longer length than that of the original password.
From what I recall Word has a password limit of 255 characters, which this value would likely exceed and is probably the cause of the hang as Word cannot handle it.
If you're using PowerShell v7 or above change $PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry to $PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry -AsPlainText in order to get the plain text version of the password
Alternatively, seeing as you're needing the plain text password straight away and trying to store it in a separate variable, just get the Read-Host cmdlet to return you a plain text password instead by changing:
$PL_PwdEntry = Read-Host ("Enter the password for the text document record") -AsSecureString
$PL_WdPWD = ConvertFrom-SecureString $PL_PwdEntry
to
$PL_WdPWD = Read-Host ("Enter the password for the text document record")
Edit following comments
It appears that Word hangs when passing the $PL_WdPWD variable to $PL_Document.Password is due to a lack of quotes.
In order to resolve this, you can change this line
$PL_Document.Password = $PL_WdPWD
to this
$PL_Document.Password = "$PL_WdPWD"
Note: in your updated code, you're still using Read-Host -AsSecureString and then converting it with ConvertFrom-SecureString. This will not be giving you the password you expect and instead return an encoded version of that password. See my original answer for details on this.

password change for delegated users

I'm having some problems running a powershell script when not on the domain controller.
The idea is that a delegated user such as a principal can change the passwords for students.
On the server I have added the membership into the powershell script allowing users to remote connect.
I have tested the code line by line on an end users account and computer.
However, when I run the script the import-module active directory doesn't work.
The error I get on the screen shows that it doesn't know what get-ADUser is followed by still being connected to the remote powershell connection on the domain controller.
Enter-PSSession -ComputerName DomainController
Import-Module ActiveDirectory
Write - Host "********************************************************** `r`nDomainController - Studnet Password Configurator `r`n********************************************************** `r`n `r`nThis program will assist when a student requires a password change. `r`nPlease ensure that you verify the student prior to implementing the change. `r`n"
do
{
$TargetUser = Read-Host -Prompt 'Enter a student user ID name'
if (Get-ADUser -Filter {SamAccountName -eq $TargetUser})
{
"Process user $TargetUser"
Get-ADUser -Identity $TargetUser
$passwordchange = Read-Host -Prompt 'Would you like to change the user password? [y|n]'
if ($passwordchange -eq 'y')
{
$newPassword = Read-Host -Prompt 'Please type new password'
Set-ADAccountPassword $TargetUser -Reset -NewPassword (ConvertTo-SecureString -Force -AsPlainText '$newPassword')
Write - Host "$TargetUser` password has now been changed to: $newPassword"
}
}
else
{
Write - Host "$TargetUser` does not exist, please try again."
}
$answer = Read-Host -Prompt 'Would you like to see another user? [y|n]'
}
until ($answer -eq 'n')
Exit-PSSession

Automating a boring task

The second half of my script does not function the way I want it to. I believe I am using the incorrect cmdlet. I am trying to add a group from active directory to the local administrator account on a laptop/pc. And after this add a domain user to the power user group.
I want to pull from AD the group name, which I thought this cmdlet would do so. Any ideas?
I only ran the second half but receive errors. I have tried other cmdlets but I think this one is the most accurate.
#change computer name of the device + condition
$answer = Read-Host -Prompt 'Do you want to change the computer name?'
# First condition - 1) name comupter 2) take user creds 3) Rename computer using stored cred 4) write host if yes is the answer
if ($answer -match "yes"){
$computername = Read-Host -Prompt "What will be the name of the computer?"
#This part of the script will contain your credentials to change the computername and priveledges
$cred = Get-Credential -Message "This will be used to changed the computername. Do not worry!"
#$cred = Read-Host -Prompt "Enter your network username" - Uneeded string
Rename-Computer -NewName "$computername" -LocalCredential $cred -DomainCredential $cred
Write-Host "Computername has been changed to $computername successfully!"
}
#Second condition - If answer is no move on to second portion of the script to set privledges
elseif($answer -match "no"){
Write-Host "Moving to the next part of the script"
}
#Third condition - If answer is anything else - loop to the beginning of the script to accept the right answer
else{
write-host "Please answer with yes or no"
}
#Second half of script
#Adding AD group to local adminitrator
$localuser= Read-Host "Enter username of the PowerUser."
Add-LocalGroupMember -Group "Administrator" -Member "memeber"
Add-LocalGroupMember -Group "Power Users" -Member $localuser + "tamu.jaguar.edu"

If Statement in Powershell always responds with the same output

So i want a script that sets the Administrator password.
I want the user to input it twice and then check if it matches.
Ive already tried to switch the conditions -eq and -ne in the two if statements, but it didnt change anything
$Password = Read-Host -AsSecureString 'Passwort des lokalen Administrators setzen' #input admin password
$PasswordRepeat = Read-Host -AsSecureString 'Passwort wiederholen' #repeat password
if ($Password -eq $PasswordRepeat) {
$UserAccount = Get-LocalUser -Name "Admin"
$UserAccount | Set-LocalUser -Password $Password
'Passwort wurde gesetzt' #password was set
''
Read-Host 'Enter druecken um das Script zu schliessen' #press enter to close
}
elseif ($Password -ne $PasswordRepeat) {
'Passwoerter stimmen nicht ueberein' #passwords do not match
''
Read-Host 'Enter druecken um das Script zu schliessen' #press enter to close
}
So when the password and passwordrepeat match it should change the password and output that the password is set. But if i input the same password twice it also prints out that the passwords do not match, and when i input two different passwords it also says that they dont match
Find at this url : Verify Passwords Match in Windows Powershell
I think this can respond :
Write-Host "Hey..!! I am here to compare the password you are entering..."
$pwd1 = Read-Host "Passowrd" -AsSecureString
$pwd2 = Read-Host "Re-enter Passowrd" -AsSecureString
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd1))
$pwd2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd2))
if ($pwd1_text -ceq $pwd2_text) {
Write-Host "Passwords matched"
} else {
Write-Host "Passwords differ"
}

Interactive Powershell Script to Return Logon Account Validity Value

Function Test-ADAuthentication {
param($username,$password)
(new-object directoryservices.directoryentry "",$username,$password).psbase.name -ne $null
}
$username = read-host "Please Enter Username";
$password = read-host "Please Enter Password" -assecurestring;
Test-ADAuthentication $username $password;
Start-Sleep -s 5
Does Anybody know why this function at the top works on it's own but doesnt work when ran like the above? I am guessing it's the order in which things execute so, how can i change the variables to have the input information in them first to get the correct boolean result?
Thanks in advance