Skip to content

Instantly share code, notes, and snippets.

@maxfunke
Last active April 27, 2020 15:45
Show Gist options
  • Save maxfunke/2d9f86927e38e1314415385508bf0b39 to your computer and use it in GitHub Desktop.
Save maxfunke/2d9f86927e38e1314415385508bf0b39 to your computer and use it in GitHub Desktop.
Basics for Powershell. From Pluralsight course.

Powershell Essentials

📝 ps1 boilerplate

Gather information for cmdlets and functions

Basically all cmdlets look like so: verb-noun

Basic process of information gathering

  1. Get-Command ** to find command I may need
    • Get-Alias [-Definition] ** to find its aliases
  2. Help ** to get help for its usage
  3. Get-Member for its functions and roperties
    • or try with GUI Show-Command

In detail

List all available verbs

get-verb

List help and filter for specific name

get-help asdf*

To prevent scrolling to the bottom when having a long output, pipe to |more

get-help * | more

Help is a function that combines get-help with a pipe to |more

help asdf*

To get help for PS internal functions, search for about_ files

help about_*

List and filter available cmdlets

get-command
get-command -type function
get-command -type cmdlet
get-command -name *ipconf*
get-command -verb new* -module Hyper-V
get-command -noun VM* -module Hyper-V

Find aliases

get-command dir
# shorthand
gcm dir

CommandType     Name
-----------     ----
Alias           dir -> Get-ChildItem

Find related cmdlet to an alias

get-alias dir
get-alias -definition Get-ChildItem

CommandType     Name
-----------     ----
Alias           dir -> Get-ChildItem
Alias           gci -> Get-ChildItem
Alias           ls -> Get-ChildItem

Open a GUI form for a specific command. Shows possible parameters and corresponding input fields

show-command get-service

History and Transcript

Show history of commands, list previous commands in posh

get-history

Invoke command from history (from current session)

invoke-history -id 1

Show full history for all sessions

more ([System.Environment]::ExpandEnvironmentVariables("%userprofile%\AppData\Roaming\Microsoft\Windows\Powershell\PSReadline\ConsoleHost_history.txt"))

record transcript of commands and save to a file

start-transcript .\transcript.txt

pwd
dir

stop-transcript

Objects

Use the get-members cmdlet to see what properties and methods returned objects have

get-history | get-members

format to table + use line wrap

get-history | format-table -wrap

format to list + select specific properties

get-service | format-list Name, Status, ServiceType

forward output to GUI grid view for further filtering etc.

get-service | out-gridview

get a counted subset of return objects (here -newest)

Get-EventLog Application -Newest 10

PsProvider + PsDrives

List avail. PsProviders

get-PsProvider

Name                 Capabilities                              Drives
----                 ------------                              ------
Registry             ShouldProcess, Transactions               {HKLM, HKCU}
Alias                ShouldProcess                             {Alias}
Environment          ShouldProcess                             {Env}                                   \
FileSystem           Filter, ShouldProcess, Credentials        {C, D}
Function             ShouldProcess                             {Function}
Variable             ShouldProcess                             {Variable}
Certificate          ShouldProcess                             {Cert}
WSMan                Credentials                               {WSMan}

Navigate to/in PsDrives

e.g. registry, environment variables, installed certificates

cd hkml:
cd env:
cd cert:

help dir -Examples

Get the value of records in e.g. env PsDrive

$env:tmp
$env:path
$env:home

cd $env:USERPROFILE
get-PsDrive

Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
Alias                                  Alias
C                 139.50         97.92 FileSystem    C:\
Cert                                   Certificate   \
D                 238.24        227.40 FileSystem    D:\
Env                                    Environment
Function                               Function
HKCU                                   Registry      HKEY_CURRENT_USER
HKLM                                   Registry      HKEY_LOCAL_MACHINE
Variable                               Variable
WSMan                                  WSMan

OS + Hardware

Get-Counter

For dynamic hardware monitoring

get-counter

See also: 📝 systemProfile.ps1

WMI + CIM

These are used to get information about OS and hardware.

WMI Repository \

CIMv2 namespace

class

properties

Get-Counter [-listset *cpu/memory*]
Get-WMIobject
Get-CimInstance
Get-Eventlog

See also: 📝 systemProfile.ps1

EventLog

List entries from specific windows event logs

Get-EventLog -log System -Newest 400

See also: 📝 systemProfile.ps1

in File System

´´´ps # attribute filter get-childItem -Attributes !Directory+Hidden,!Hidden,Directory dir -att !d+h,!h,d

# shorthand
gci *.png

# recursive
move-item .\* ~\newDir -recurse

# verbose / preview
move-item .\* ~\newDir -recurse -verbose

´´´

Permissions

icacls .

Calculate

# sum up, select sum, map to GB size
(((Get-PSDrive).Used | measure -SUM).Sum / 1gb ) / (((Get-PSDrive).Free | measure -SUM).Sum / 1gb)

# use Math lib to round
[Math]::Round(((Get-PSDrive).Free | measure -SUM).Sum / 1gb ,2)

Variables

# global variables
get-variable

# set a variable
$myInt = 1
$myStr = "asdf"
$myCmdReturnObj = Get-Services

Write-Output "$myStr ist: $myInt aber nicht $myCmdReturnObj"
# find all avail. counters related to 'memory'
get-counter -ListSet *memory* | select -ExpandProperty Paths
# get current memory usage in %
get-counter '\Memory\% Committed Bytes In Use'
# get available CIM classes related to *disk*
Get-CimClass -ClassName *disk*
# use that CIM class with WMI (e.g. logical disks)
Get-WmiObject CIM_LogicalDisk
# or do the exact same with `Get-CimInstance`
Get-CimInstance CIM_LogicalDisk
# filter windows event log for reboots
Get-EventLog -log System -Newest 400 | where-object eventid -eq '1
074' | Format-List MachineName, UserName, TimeGenerated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment