Find Row in CSV - powershell

I'm trying to reset passwords from a set username and password CSV. I have tried using the for-each method and it passes through all of the list rather than just one. Ideally I want it to ask for the username and then reset the password based on the username being entered.
The CSV is as follows
Daniel,Apples
Ben,Bannanas
Harry,Pears
Peter,Grapes
The code is very messy, but any input would be very much appreiciated. I've tried a few different ways and just can't get it to play ball!
Do I need to remove the For-Each element, basically I want it to ask me for a username and when I type it, it resets the password that is given for that username. As all are given a default password.
$Spreadsheet = Import-CSV "C:\Desktop\Password Reset\Passwords.csv"
$username = $User.'Username'
$password = $User.'Password'
ForEach($User in $Spreadsheet) {
$resetusername = Read-Host "Who's Password would you like to reset"
Set-ADAccountPassword $User.UserName -reset -NewPassword (Convertto-Securestring -asplaintext $($User.Password) -force)
Write-Host "Password reset to $password for $username"
}
Thank you very much in advance! :)

The idiomatic approach would be to filter the list of CSV records using Where-Object:
$Spreadsheet = Import-CSV "C:\Desktop\Password Reset\Passwords.csv" -Header Username,Password
$resetUsername = Read-Host "Who's Password would you like to reset"
$targetUser = $Spreadsheet |Where-Object Username -eq $resetUsername
if($targetUser){
Set-ADAccountPassword $targetUser.Username -Reset -NewPassword (Convertto-Securestring -AsPlainText $targetUser.Password -Force)
Write-Host "Password reset to $($targetUser.Password) for $($targetUser.Username)"
}
else {
Write-Host "User '$resetUsername' could not be found in spreadsheet!"
}

Related

Creating a simple script to import user's first name , create local account and and password

I'm looking to create a simple powershell script that will import the user's first name from file, prompt to create a new password and loop on error when the password doesn't meet the password requirement based on the "ErrorVariable" if possible. If not, please advise.
# import user firstname from file
$firstname = $(Get-Content "C:\tmp\local\firstname.txt")
# prompt user for new password
$password = Read-Host "Hello, $firstname!! Please change your local admin account password. (Requirements: At least 8-characters, 1-Cap Letter, 1-Number) " -AsSecureString -Erroraction silentlycontinue -ErrorVariable PasswordError
# create new password
$password = $password
Get-LocalUser -Name "$firstname" | Set-LocalUser -Password $password -Erroraction silentlycontinue -ErrorVariable PasswordError
If ($PasswordError)
{
"Unable to update the password. The new password does not meet the length or complexity."
}
If (-Not $PasswordError)
{
"Password updated successfully!!"
See script above.........
Think you could simply use try/catch - e.g.:
try {
Set-LocalUser -Name $firstname -Password $password -Erroraction:stop
write-host "Password updated successfully!!"
}
Catch {
write-error $_
}
If the operation succeeded you will get "Password updated successfully!!", otherwise it returns the error.

sudent, invalid name for New-ADUser multi user creation script

I'm pulling some user info from a .csv to create new users,
I've splatted the New User Params at the suggestion of someone here
but I'm getting this error
New-ADUser : The name provided is not a properly formed account name
At C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\Bamboo Attributes form a csv.ps1:67 char:17
+ New-ADUser $NewUserParms -ErrorAction Stop
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=System.Colle...=Cyclone,DC=com:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1315,Microsoft.ActiveDirectory.Management.Commands.NewADUser
the username variable seems to be correct as far as I know, when it outputs during running of the script its what I assume to be correct format of "firstname.lastname"
I have added trims and a section to remove spaces from usernames. to deal with multipart names such as Van der.... etc
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'path'
foreach ($User in $ADUsers) {
$firstName = $user.FirstName.Trim()
$surname = $user.Surname.Trim()
$vaildUsernameFormat = "[^a-zA-Z_.]" # identifies anything that's _not_ a-z or underscore or .
$username = "($firstName'.'$surname)" -replace $vaildUsernameFormat, '' #removes anything that isn't a-z
$DefaultPassword = 'Pa$$w0rd'
$NewUserParms = #{
'samAccountName' = $username;
'Name' = "$firstname $surname";
'DisplayName' = "$firstname $surname";
'UserPrincipalName' = "$username#domain.com";
'GivenName' = $firstname;
'Surname' = $surname;
'EmailAddress' = $User.Email;
'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force);
'Enabled' = $true;
'Path' = "OU=Users,DC=domain,DC=com";
}
write-host "$username this is username value"
#Check if the user account already exists in AD
if (Get-ADUser -F {
sAMAccountName -eq $username
}) {
#If user does exist, output a warning message
Write-Warning "A user account $username has already exist in Active Directory."
}
else {
#If a user does not exist then create a new user account
New-ADUser $NewUserParms -ErrorAction Stop
}
}
I've removed some of the user attributes just to make this a bit smaller.
here is the.csv as well in case I've messed something up there
link to .csv file on git
I think it's something simple. When you use splatting, you need to use the # symbol when feeding your hash table to the cmdlet rather than the regular $:
New-ADUser #NewUserParms -ErrorAction Stop
Some more reading About Splatting.

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

Bulk change password of users in AD through powershell

I am trying to change password of multiple users in my AD through powershell script which I have written. In my AD, I have added an attribute called tempPassword which takes unicode string, which contains random generated password for all users. I want to write this tempPassword attribute as the user password. For this, my powershell script is:
$users = Get-ADUser -properties * -Filter *
foreach($user in $users)
{
$password = $user.tempPassword
$secure_string_pwd = convertto-securestring -String $password -asplaintext -force
Set-ADAccountPassword -Identity $user -NewPassword $secure_string_pwd
}
When i execute this script, I get the following error:
ConvertTo-SecureString : Cannot convert 'Microsoft.ActiveDirectory.Management.ADPropertyValueCollection' to the type 'S
ystem.String' required by parameter 'String'. Specified method is not supported.
The passwords contain numbers, lower and upper case characters and are all of length 8.
What may be the reason for this error?
I don't know how tempPassword is defined in AD. However from what you receive, it means you get a collection of elements.
Try this:
$password = $user.tempPassword[0]

PowerShell New-ADUser fails in cycle

Here is my powershell code for adding test user accounts to Active directory... Problem: when $i is between 1 and 99, everything works fine... immediatelly after $i reaches 100, created accounts are disabled and error message in console telling "The password does not meet the length, complexity, or history requirement of the domain."
Any idea what's the problem?
//EDIT: no password policy is set for the domain
Thanks
Import-Module ActiveDirectory
for($i=1; $i -le 500; $i++){
$name="Name1_$i" #name
$surname="Surname1_$i" #surname
$logon="logon1$i" #logon
$plainPass='pAs5w0rd'+$i+'&G'
$password=ConvertTo-SecureString -AsPlainText -Force -String $plainPass
New-ADUser -Enabled 1 -Name $name -AccountPassword $password -DisplayName "$name $surname" -GivenName $name -UserPrincipalName $logon#testdomain.local -SamAccountName $logon -Surname $surname -Path "OU=SomeTest,DC=testdomain,DC=local"
}
So I reproduce your problem, you are under the default domain policy. And when :
name = Name1_100
surname = Surname1_100
samAccountName = Logon1100
A too big part of the name is in the password (see default passord policy on the domain called password complexity)
The samAccountName is checked in its entirety only to determine whether it is part of the password
So try
$plainPass='pAs5w0rd'+($i+1)+'&G'
It will work.