0

I have a script that creates random passwords and stores them in a csv file with different informational headers such as $username, $system, $password. This script is run in a new environment to create randomly generated passwords for service accounts. Every 90 days the people managing this environment will need to change these passwords so I am trying to create a script that will then change the passwords and update the csv file with the new ones. I am able to change the passwords without a problem, but modifying the csv file has been another story all together.

My Function, Function UpdatePassword ($username,$system,$password) will receive the following line:

$result = UpdatePassword $entry.Name "Active Directory" "${account_password}"

I want to search the csv file and match the username I am editing with the corresponding username in the CSV file. However, because some usersnames may be the same (just accept this) I also need to check against the $system variable, which in this case is "Active Directory". If both of these values match a line, then I want to replace the $password with the new one.

function UpdatePassword($username,$system,$password) { if($(hostname)
-eq "Machine") {   New-PSDrive -Name AdminShare -PSProvider FileSystem -Root $LOCALPASSWORDFILE | Out-Null } else {   New-PSDrive -Name AdminShare -PSProvider FileSystem -Root $REMOTEPASSWORDFILE | Out-Null } $PASSWORDFILE = "AdminShare:\Passwords.csv"

##########
#Checking for required values
##########

if(!$username -or !$system) {   write-host "username, system, and special characters fields are required"   return "invalid arguments" }

$pwFile = import-csv $PASSWORDFILE

foreach ($user in $pwFile) {   
    if($user.username.tolower() -eq $username.tolower() -and $system.tolower() -eq $userem.tolower())   {       
        $_ -replace $user.Password, $password | Set-Content $pwFile;
    }
return 0   
 }

  Remove-PSDrive -Name AdminShare | out-null }

1 Answer 1

1

When you use Import-Csv you read a CSV file into an array of PowerShell custom objects where each field of the CSV is represented by a property on the each custom object. You don't want to treat that as a string and attempt to write the string back to the CSV file. Instead, modify the properties on the objects e.g. inside you if do this:

$user.Password = $password

Then outside your foreach loop, export the objects back out to a CSV file e.g.:

$pwFile | Export-File $PASSWORDFILE -NoTypeInformation
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.