Some powershell related commands and tricks I want to quickly find again

Posted March 23, 2022 by Adrian Wyssmann

Set Environment Variable

[Environment]::SetEnvironmentVariable("PATH", "C:\Tools;$env:PATH", "User")

Wget with proxy authentication

[System.Net.WebRequest]::DefaultWebProxy = [System.Net.WebRequest]::GetSystemWebProxy()
[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
wget https://updates.jenkins-ci.org/download/war/2.138.1/jenkins.war

Add username and password to https url

Adds $username:$password between https:// and the rest of the url

$username = "user"
$password = "pass123"
$giturl = "https://scm.intra"

$url = $giturl -split "\/\/"

echo "$($url[0])://${username}:${password}@$($url[1])" 

Security Question in Script

$Confirm = Read-Host "Force (y/N)"
if ($Confirm -Match "^y$") {
    $gitPushCommand = "Force"
} else {
    $gitPushCommand = "Not force"
Write-Host "Command: $gitPushCommand"

Calculate Folder Size

{0:N2} MB" -f ((Get-ChildItem C:\users\ -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1MB)

Usage of parameters

Param (
        HelpMessage="Enter target path")]
    [string] $Basedir = "D:\Dev",

        HelpMessage="Enter source location for sw packages")]
    [string] $baseurl= "https://myserver/tools",

        HelpMessage="Component to be installed, use 'all' to install all, use -Show to show all components")]

        HelpMessage="Show all installable components")]

    [parameter(ParameterSetName="SilentInstall", Mandatory=$true)]
    [string] $component

Resize a partition

$size=Get-PartitionSupportedSize -InputObject $part
Write-Host "Resizing partition to size: $($size.SizeMax)"
Resize-Partition -InputObject $part -Size $size.SizeMax

Powershell Credentials

$mycredentials = Get-Credential

# When you have to provide credentials in non-interactive mode, you can create a PSCredential object in the following way.
# You can now pass ```$mycreds``` to any ```-PSCredential``` input parameter
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)

Show Certificates

Display Certificates from Certificates store in Windows

Set-Location Cert:\CurrentUser\My
Get-ChildItem | Format-Table Subject, FriendlyName, Thumbprint -AutoSize

Invoke-Expression Advanced

Advanced Invoke-Expression which catches errors

$isContinue = $true
while ($isContinue) {
    Push-Location $workDir
    try {
        Write-Host $(Get-Location)
        Invoke-Expression $command 2>&1
        $isContinue = $false
    } catch {
        $msg = $($_.Exception.Message)
        Write-Host "### [ERROR] $msg"
        # abort on critical issues, otherwise continue
        if (!($msg -match "Found possible branch point")) {
    } finally {

Invoke-WebRequest with username and password for basic authentication

Invoke-WebRequest -Uri $url -Credential $cred

$user = "shaunluttin"
$pass = "super-strong-alpha-numeric-symbolic-long-password"
$pair = "${user}:${pass}"
Encode the string to the RFC2045-MIME variant of Base64, except not limited to 76 char/line.

$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
Create the Auth value as the method, a space, and then the encoded pair Method Base64String

$basicAuthValue = "Basic $base64"
Create the header Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

$headers = @{ Authorization = $basicAuthValue }
Invoke the web-request

Invoke-WebRequest -uri "https://api.github.com/user" -Headers $headers

Run a script without downloading it first

iex(New-Object Net.WebClient).DownloadString($URL)

Edit this page