Windows PowerShell

A collection of Windows PowerShell resources

Customization / Modules

PowerShell modules can enhance functionality and the user interface. In this example, the profile is updated to use git over an SSH connection, readline settings for a bash like experience, custom color output and a custom prompt.

My Customized PowerShell

Execution Policy

This command sets the PowerShell execution policy.

If you encounter an error such as …

{script path} cannot be loaded.
The file {script path} is not digitally signed.
You cannot run this script on the current system.
For more information about running scripts and setting execution policy,
see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.

You can set a Bypass execution policy for the current session.

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Menu Example

This PowerShell script contains a menu to execute various tasks using functions.

UtilityMenuExample.ps1
function ListProcess
{
    Get-Process | Group-Object Company | Sort-Object Count -Descending
}

function ListEnvVars
{
    Get-ChildItem env:
}

function ListEventLog
{
    Get-EventLog -List
}

function Cleanup
{
    Write-Host "Delete files from $env:temp older than 24 hours"
    Get-ChildItem -path $env:temp | where {$_.Lastwritetime -lt (date).addhours(-24)} | remove-item
    <# Clear-RecycleBin #>
    $Shell = New-Object -ComObject Shell.Application
    $RecBin = $Shell.Namespace(0xA)
    $RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}
}

function ShowMenu
{
     param (
           [string]$Title = 'Menu'
     )
     Write-Host "====== $env:USERPROFILE - $Title ======="

     Write-Host "1: List Running Processes"
     Write-Host "2: List Environment Variables"
     Write-Host "3: List Event Log"
     Write-Host "4: Clean Temp and Recycle Bin"
     Write-Host "q: quit"
}

do
{
     ShowMenu
     $input = Read-Host "Please make a selection"
     switch ($input)
     {
        '1' {
            Clear-Host
            ListProcess
        }
        '2' {
            Clear-Host
            ListEnvVars
        }
        '3' {
            Clear-Host
            ListEventLog
        }
        '4' {
            Clear-Host
            Cleanup
        }
        'q' {
            return
        }
     }
     pause
}
until ($input -eq 'q')

Compress-Archive

This example creates a zip file of the Documents folder with a datetime string in the zip filename.

Compress-Archive "$env:USERPROFILE\Documents" "$env:USERPROFILE\Documents_$(get-date -f yyyyMMdd'T'HHmmss).zip"

Resources