Last update: 2017-11-07

Tips and tricks on using PowerShell

Find the version of PowerShell installed


Set permission to run unsigned scripts

Set-ExecutionPolicy -executionpolicy Unrestricted

Manually install new modules

Copy files to: C:\Users\\Documents\WindowsPowerShell\Modules\module-name

Catch run-time errors

} catch {
     Write-Error "$_"

Listing filtered items from a folder

Get-ChildItem -Path C:\temp -Filter *.zip

Creating a RSA key

$RSA = New-Object System.Security.Cryptography.RSACryptoServiceProvider(2048)

Save and load credentials as an encrypted blob

Read-Host "Password" -AsSecureString | ConvertFrom-SecureString | Out-File C:\cred.dat
$p = Get-Content C:\cred.dat | ConvertTo-SecureString
$cred = New-Object -typename System.Management.Automation.PSCredential -ArgumentList "myusername",$p
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($p)
$plainText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Zip files

Add-Type -AssemblyName System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)

Access environment variables


Access GEO IP whois information

Invoke-WebRequest -Uri | ConvertFrom-Json

Create a unique ID


Crete a remote share

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($args[0],$args[1],0)} -ArgumentList $sharepath, $sharename

List file NTFS permissions recursively

Get-ChildItem .\ -Recurse | Get-Acl | Select @{Name='Path';Expression={Convert-Path $_.Path}},Owner,AccessToString | Out-GridView

Sending a SOAP request

$weather = New-WebServiceProxy -Uri "" -Namespace WebServiceProxy
[xml]$xml = $weather.GetWeather("Montreal", "Canada")

Accessing an XML feed

([xml](Invoke-WebRequest -Uri "")).feed.entry|select -ExpandProperty title

Creating a SHA1 hash

$sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
$enc = [system.Text.Encoding]::UTF8
$b = $enc.GetBytes("Hello world")
# To HEX:
$result = ""
$sha.ComputeHash($b) |foreach { $result += $_.ToString("X2") }
# To Base64:

Build a custom PSObject

$user = New-Object PSObject
$user | Add-Member -NotePropertyName "Name" -NotePropertyValue "John Smith"
$user | Add-Member -NotePropertyName "Age" -NotePropertyValue "18"
$user | Add-Member -NotePropertyName "City of birth" -NotePropertyValue "New York"
$user | Add-Member -NotePropertyName "Pet" -NotePropertyValue "none"

Mounting a VHD or WIM image

Mount-WindowsImage -ImagePath file.vhd -Path c:\mount -Index 1

Load custom C# code

function Open-DiskTray
    Add-Type -TypeDefinition  @'
    using System;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    namespace CDROM
        public class Commands
            static extern Int32 mciSendString(string command, string buffer, int bufferSize, IntPtr hwndCallback);
            public static void Eject()
                string rt = "";
                mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero);


Delete folders older than x days

Get-Item c:\camera\* | Where {$_.LastWriteTime -lt ((Get-Date).AddDays(-3))} |foreach {Remove-Item $_ -Recurse}

Access COM objects

$master = New-Object -ComObject IMAPI2.MsftDiscMaster2
$recorder = New-Object -ComObject IMAPI2.MsftDiscRecorder2

AD Group listing

$results = @()
Get-ADGroup -Filter * |foreach {$g = $_.SamAccountName; Get-ADGroupMember $g |foreach {$results += New-Object PSObject -Property @{GroupName = $g; Account = $_.SamAccountName}}}

Get Registry property or attribute

Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\SystemInformation" |Select -ExpandProperty SystemProductName

Get/Set AD attribute for all users

Get-ADUser -Filter * -Properties * | Where {$_.uidNumber -eq $null} | Select sAMAccountName
Get-ADUser -Filter * |foreach { Set-ADUser $_ -Email "$($_.GivenName).$($_.Surname)@seven-kingdoms.local" }

Find AD users who logged on since a specific date

$logonDate = New-Object System.DateTime(2007, 1, 1)
Get-ADUser -Filter 'LastLogonDate -gt $lastdate' -Server -Properties * |Select SamAccountName,La stLogonDate |Sort LastLogonDate

Update the Registry

$path = "HKCU:\Software\MyApp"
$key = "Version"
$value = "1.2"
if(!(Test-Path $path)) { New-Item -Path $path -Force }
New-ItemProperty -Path $path -Name $key -Value $value -PropertyType String

Count the number of files by type

(Get-ChildItem -Path C:\scripts -Recurse | Where {Test-Path $_.FullName -PathType Leaf} | foreach {Get-FileMetaData $_.FullName | Select Name,"Item Type",Size}) | group -NoElement -Property "Item Type"

Convert date and time from unixtime

$origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0

Pin an app to taskbar

$shell = New-Object -ComObject Shell.Application
$program = $shell.NameSpace('C:\Program Files\Internet Explorer\').ParseName('iexplore.exe')

Run a script bypassing execution policy

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -File <script_name>

Get top 10 processes based on CPU usage

Get-WmiObject -Class win32_perfformatteddata_perfproc_process |Where {$_.Name -ne "_Total"} |Sort PercentProcessorTime -Descending |Select Name,PercentProcessorTime,ThreadCount,IDProcess -First 10

Resolve an IP address into a hostname


List permissions on Windows shares:

Get-WmiObject win32_LogicalShareSecuritySetting | foreach {$_.Name + ":"; $_.GetSecurityDescriptor().Descriptor.DACL | foreach {$_.Trustee.Name + " => " + $($_.AccessMask -Replace 2032127,"Full Control" -Replace 1245631,"Change" -Replace 1179817,"Read")}}

Get the local computer name and serial number

"$($(gwmi win32_computersystem).Name).$($(gwmi win32_computersystem).Domain): $($(gwmi win32_bios).S erialNumber)"

© 2007-2019 Patrick Lambert - All resources on this site are provided under the MIT License - You can contact me at: