Powershell


Save Credentials

To save credentials you need to save a secure string to a file like below

"plaintxtpassword" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-secureString | Out-File pwdata.txt

and to use it you can use this to create a credential object to pass

$user = "someuser@domain.com"
$spass = get-content pwdata.txt | ConvertTo-SecureString

$credObject = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $spass

List directories last modified older than 3 years ago

Get-ChildItem .\Projects | where{$_.LastWriteTime -lt (get-date).AddYears(-3)} | sort-object -Property LastWriteTime

Load custom powershell profile

To load a directory of custom powershell scripts automatically when you open a shell.

1) first check if a PS profile exists. if not create one

test-path $profile

if this returns false create a profile like this

New-Item -path $profile -type file force

now open the the profile in notepad

notepad $profile

Now paste the following script changing the SCRIPT_DIR and START_DIR

$psdir = "SCRIPT_DIR"

Set-Location $psdir

#autoload script directory

$cnt = (Get-ChildItem $psdir).Count

For($i = 0; $i -le $cnt; $i++)

{ 

    Write-Progress -Activity "Loading Scripts" -status "Loading $i" -percentComplete ($i / $cnt*100)
    
}

Get-ChildItem "${psdir}\*.ps1" | %{.$_}

Set-Location c:\

Write-Host -foregroundcolor green "Custom Powershell Environment Loaded"