Tips and tricks on using PowerShell


Find the version of PowerShell installed

<powershell>
$PSVersionTable

Set permission to run unsigned scripts

<powershell>
Set-ExecutionPolicy -executionpolicy Unrestricted

Manually install new modules

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

Catch run-time errors

<powershell>
try
{
     ...
} catch {
     Write-Error "$_"
}

Listing filtered items from a folder

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

Creating a RSA key

<powershell>
$RSA = New-Object System.Security.Cryptography.RSACryptoServiceProvider(2048)
([xml]$RSA.ToXmlString($true)).RSAKeyValue

Save and load credentials as an encrypted blob

<powershell>
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

<powershell>
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

<powershell>
$env:TEMP

Access GEO IP whois information

<powershell>
Invoke-WebRequest -Uri https://freegeoip.net/json/8.8.8.8 | ConvertFrom-Json

Create a unique ID

<powershell>
[guid]::NewGuid().Guid

Crete a remote share

<powershell>
$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

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

Sending a SOAP request

<powershell>
$weather = New-WebServiceProxy -Uri "http://www.webservicex.net/globalweather.asmx?wsdl" -Namespace WebServiceProxy
[xml]$xml = $weather.GetWeather("Montreal", "Canada")
$xml.CurrentWeather.Temperature

Accessing an XML feed

<powershell>
([xml](Invoke-WebRequest -Uri "https://weather.gc.ca/rss/city/qc-147_e.xml")).feed.entry|select -ExpandProperty title

Creating a SHA1 hash

<powershell>
$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") }
$result
# To Base64:
System.Convert]::ToBase64String($sha.ComputeHash($b))

Build a custom PSObject

<powershell>
$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

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

Load custom C# code

<powershell>
function Open-DiskTray
{
    Add-Type -TypeDefinition  @'
    using System;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    namespace CDROM
    {
        public class Commands
        {
            [DllImport("winmm.dll")]
            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);
            }
        }
    }
    '@
    [CDROM.Commands]::Eject()
}

Open-DiskTray

Delete folders older than x days

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

Access COM objects

<powershell>
$master = New-Object -ComObject IMAPI2.MsftDiscMaster2
$recorder = New-Object -ComObject IMAPI2.MsftDiscRecorder2
$recorder.InitializeDiscRecorder($master)
$recorder.EjectMedia()

AD Group listing

<powershell>
$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

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

Get/Set AD attribute for all users

<powershell>
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

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

Update the Registry

<powershell>
$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

<powershell>
(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

<powershell>
$origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0
$origin.AddSeconds($unixtime)

Pin an app to taskbar

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

Run a script bypassing execution policy

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

Get top 10 processes based on CPU usage

<powershell>
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

<powershell>
[Net.DNS]::GetHostByAddress("8.8.8.8").HostName

List permissions on Windows shares:

<powershell>
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

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


© 2008-2017 Patrick Lambert - All resources on this site are provided under the MIT License - You can contact me at: dendory@live.ca