Store credentials in a file and use them later
Sometimes a script have to authenticate, but it would be a really bad idea to store passwords in scripts. Encrypt them!
Store-Creds.ps1
<# .SYNOPSIS Store-Creds - Stores a password encrypted to disk. .DESCRIPTION Store-Creds - Stores a password encrypted to disk Allows to create a file in the current directory and store the password encrypted in it. .NOTES File Name : Store-Creds.ps1 Author : Fabrice ZERROUKI - fabricezerrouki@hotmail.com #> $ValidPattern = "^[a-zA-Z0-9\s]+$" $UserName=Read-Host "Please provide a username" if ($UserName -match $ValidPattern) { $CredsPath=".\$UserName-Creds.txt" } else { $UserName=$UserName -replace "\\","_" $CredsPath=".\$UserName-Creds.txt" } if (!(Test-Path $CredsPath)) { $Password=Read-Host "The file '$CredsPath' will be created with your encrypted password. Enter your password" -AsSecureString | ConvertFrom-SecureString | Set-Content $credsPath Write-Host "File '$CredsPath' created! You can now use it with the 'Get-Creds.ps1' script." -ForegroundColor DarkGreen; } else {Write-Host "The file '$CredsPath' already exists." -ForegroundColor Yellow;}
Get-Creds.ps1
<# .SYNOPSIS Get-Creds - Gets an encrypted password from file. .DESCRIPTION Get-Creds - Gets an encrypted password from file Allows to read an encrypted password stored in a file in the current directory. .PARAMETER UserName Defines the username associated to the password Mandatory parameter. .NOTES File Name : Get-Creds.ps1 Author : Fabrice ZERROUKI - fabricezerrouki@hotmail.com #> Param( [Parameter(Mandatory=$true, HelpMessage="You must provide an username.")] $UserName ) $ValidPattern = "^[a-zA-Z0-9\s]+$" if ($UserName -match $ValidPattern) { $CredsPath=".\$UserName-Creds.txt" } else { $UserName=$UserName -replace "\\","_" $CredsPath=".\$UserName-Creds.txt" } if (Test-Path $CredsPath) { $Password=Get-Content $CredsPath | ConvertTo-SecureString Write-Host "Password stored in '$CredsPath' file is '$Password'." -ForegroundColor DarkGreen; } else {Write-Host "The file '$CredsPath' doesn't exists. You can create it with the 'Store-Creds.ps1' script." -ForegroundColor Yellow;}