Helpful Powershell Cmdlets/Functions

February 26, 2023 (Modified on March 24, 2023) • PowerShell • 2 minutes to read • Edit

These are some of the PowerShell cmdlets that I have found useful. I will be adding more as I find them. I usually add them to my PowerShell profile so that I can use them anywhere. To get the path of your PowerShell profile, run the following command:

> $profile
C:\Users\<user>\Documents\PowerShell\Microsoft.PowerShell_profile.ps1

Don’t forget to restart PowerShell after adding the cmdlets to your profile.

Table of Contents

List all USB devices

function Get-UsbDevices { 
  Get-PnpDevice -InstanceId 'USB*' -Class 'USB' -Status OK 
}
Set-Alias -Name lsusb -Value Get-UsbDevices

Get the size of a folder

This is a recursive function that will get the size of a folder in MB with 2 decimal places.

function Get-Size {

  param(
    # The path to the folder
    [Parameter(Mandatory=$true, Position=0)]
    [string]$Path="."
  )

  "{0:N2} mb" -f ((Get-ChildItem -Recurse -Force $path | Measure-Object -Property Length -sum).Sum / 1Mb)
}

List PATH environment variable

Print the PATH environment variable with newlines.

function Get-Path {
  $env:Path -split ';' | Out-String
}

or

function Get-Path {
  $Env:Path | % {$_.replace(";", "`n")}
}

Print all environment variables sorted by name with an alias printenv.

function Get-Env {
  Get-ChildItem Env: | Sort-Object Name | Format-Table -AutoSize
}
New-Alias printenv Get-Env



comments powered by Disqus