May 14, 2016

PowerShell - Storing credentials in a file

# Script begins
 [CmdletBinding()]
Param(
 [Parameter(Mandatory=$True)]
 [ValidateSet('SetCredentials','UseCredentials')]
 [String]$Procedure,

 [Parameter(Mandatory=$True)]
 [ValidateNotNull()]
 [String]$User,

 [Parameter(Mandatory=$True)]
 [ValidateNotNull()]
 [String]$File
 )

    if ($Procedure -like "SetCredentials") {
$Password = Read-Host -Prompt "Enter password" -AsSecureString
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList ($User,$Password)
$Credentials.Password | ConvertFrom-SecureString | Set-Content $File
}

    if ($Procedure -like "UseCredentials") {
$Password = Get-Content $File | ConvertTo-SecureString
$Global:Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList ($User,$Password)
}
# Script ends

Usage example (cmd):
C:\Users\User>whoami
DOMAIN\user

C:\Users\User>PowerShell -Command "C:\Script\SecureCredentials.ps1 -Procedure SetCredentials -User Admin -File C:\Script\AdminCredentials.txt"
Enter password: ************

C:\Users\User>PowerShell -Command "C:\Script\SecureCredentials.ps1 -Procedure UseCredentials -User Admin -File C:\Script\AdminCredentials.txt; Invoke-Command -Credential $Credentials -ComputerName Localhost -ScriptBlock {whoami}"
DOMAIN\admin

Usage example (PS):
PS C:\Users\User> whoami
DOMAIN\user

PS C:\Users\User> C:\Script\SecureCredentials.ps1 -Procedure SetCredentials -User Admin -File C:\Script\AdminCredentials.txt
Enter password: ************

PS C:\Users\User> C:\Script\SecureCredentials.ps1 -Procedure UseCredentials -User Admin -File C:\Script\AdminCredentials.txt

PS C:\Users\User> $Credentials.GetNetworkCredential() | fl UserName,Password

UserName : Admin
Password : MyPassword

PowerShell - Write-Host variables without space

PS C:\> $a = "Hello"
PS C:\> $b = "World"
PS C:\> Write-Host $a $b
Hello World
PS C:\> Write-Host $a World
Hello World

PS C:\> Write-Host $a"$b"
HelloWorld
PS C:\> Write-Host $a"World"
HelloWorld