Skip to content

Powershell Jumpstart Notes

Microsoft Virtual Academy, MVA 23/06/2017

Getting started with Powershell 3.0 Jump Start

Useful Links:

Module 1 – Don’t fear the shell

set powershell normal as taskbar icon, can right click and start as admin or start ise
right click icon in taskbar > properties > shortcut tab > advanced > start as administrator
set the shell window properties to lucida console 24, change buffer and window to remove horizontal scroll bar buffer should be 3000 to display info
CmdLets introduced Verb – Noun
Native commands work such as ping, IPConfig, calc
CmdLet does some task you can use Pipeline to do bigger tasks
Improved management, real time and large scale
install ps win management framework for win7 server 2008/2012
check if these characters are visible in PS Screen:
Set-Location C:\
Aliases such as cmd and unix commands can work
Get-Alias – shows list of all aliases (gal lists all this)
Help command for Help
Get-Help CmdLet Name
Start using powershell instead of cmd
cls – Clear-Host
cd – Set-Location
dir, ls Get-ChildItem
type, cat – Get-Content
Copy, cp – Copy-item
example: ls is unix and points to a ps command
help (command)
Get-Alias has an alias gal
gal pwd
gal g* (look at get-service)
gal *sv (look at start, stop service – similar commands)
gal sa* (commands are mainly start-…)
get-alias -Definition get-process (what the alias is for that Cmdlet)

Module 2 – The help system

Don’t memorise, discover, figure out how to do things
There are thousands of cmdlets so use the help system
its about figure things out not remembering things
learn using help
each ms product has hundreds of cmdlets hard to memorise
Update-help –force (updates latest help files from internet)
Recommended for updated help notes
Get-help get-service (shows full page help at once)
Help get-service (shows page at a time)
Man get-service (same as above)
Save-help (update first then save to a location)
Use whichever one you prefer.
Get-help *service* (want to see what cmdlets there are related to service) * is a wildcard which helps search for related things
Get-help service *a
Get-help g*service* (displays all g related service cmdlets)
Search for the thing you want to find then use the help file
Get-help G*Adcomputer*
Get-help get-adcomputer
Get-verb (lists verbs)
get-verb | measure (shows count of verbs)
get-help get-service –detailed
get-help get-service –full (similar to above but a few more parameters)
get-help get-service –online (shows help file online, on older versions on ps, otherwise just update ps locally)
get-help get-service –examples (shows examples of command)
highlight example 8 and press enter, right mouse button pastes text to commandline
get-help get-service –ShowWindow (displays help in a window, search and filter, copy/paste examples)
copy text with right click, paste on command line with right click
Under syntax in help there are 3 parameter sets for the cmdlet
Get-service bits, bfe
[] means parameter can take multiple values separated by comma
Get-service –name b*, c*
Get-Service [-ComputerName <String[]>]
Get-service –displayname bit*
Get-service name bits
Get-service bits
Gsv bits
Use pinky finger to use tab key for better syntax and readability, scrolls through cmdlets and parameters of cmdlets
all parameters of a cmdlet are optional
get-service -displayname (value is required for this parameter)
get-service -displayname bit*
brackets around parameter means you dont have to type the parameter
gsv bits
when writing scripts make it readable with full commands
when at the command prompt you may want to use these shortcuts
Use tab key to cycle through Names and parameters
get-eventlog -logname application -newest 50 (can use tab complete on lognames position)
I have a business problem where I want to know last 5 errors in my logs or event logs. I wonder if powershell has a cmdlet for this.
Get-help *eventlog*
get-eventlog -LogName system -Newest 3 -EntryType Error (3 latest errors from system log)
get-eventlog -LogName system -Newest 3 -EntryType Error –computername dc,s1,s2 (3 latest errors from system log on multiple computers)
cls ; about-eventlogs (statement separator, clears screen then does about-eventlogs cmdlet)
Help about_* (shows list of about topics)
2 help systems 1 for cmdlets and 1 conceptual with _about
get-help -category provider
Get-help –certificate

Module 3 – The Pipeline

get-service -name bits | stop-service
get-service -name bits | start-service -passthru
piping allows continuation
get-service | export-csv -path c:\service.csv
notepad c:\service.csv
import-csv c:\service.csv
get-process | export-clixml -path c:\good.xml
imagine you are on another computer then type:
to compare a good machine with a bad machine or software installed
compare-object -referenceobject (import-clixml c:\good.xml) -difference (get-process) -property name
(live objects are compared to an xml file)
Connects cmdlets to produce better results
Import/export csv or xml
See powerpoint 03
Compare objects
Export-csv have to specify file
Converto-csv file not required
Get-service | out-file -filepath c:\test.txt
Get-help *content*
Get-content test.txt
Help *out*
Can out-printer
Export-csv (this is convert coupled with output to a file, need to specify file)
Convertto-csv (this can be used to do more things in the command)
get-service | convertTo-html -Property name,status | Out-File c:\temp\test.htm
Converto-html can make it pretty using tables css etc
WhatIf for safety on a command if you are uncertain
-Confirm – asks user yes, no to proceed
Get-service | stop-service -whatif (tells you what it would do but doesn’t do it)
Get-service | stop-service -confirm (asks you if you want to do the command)
Get-service -displayname *bi* |stop-service -whatif
Plugins and Snapins are available to extend PS
This is now known as modules
Get-module -listavailable
Active directory module comes when you install remote server management tools
Get-help *ad*
Get-help get-adcomputer (this can auto load the module just by entering the cmdlet)
Check with get-module
In ps v2 you had to import the module to use and check help

Module 4 – Objects

Objects dramatically simplify your life
An object has properties and has things you can do called methods
We spew objects out and can work on them, these can be displayed then converted to text
Each row is an object, each heading is a property
Get-process |where handles -gt 900 |sort handles
Get-service -name bits | get-member
Get-service -name bits | gm
In output .ServiceController shows the kind of object this is
Get-service has a method called start and stop so you don’t necessarily need to use start-service or stop-service
You find out with get-member what properties you want then can select them
Get-service | select -property name,status
Get-childitem | select -property name, length | sort -property length -descending
If it has the word property in the list of items then you can use that for sort and select
Get-eventlog -logname system -newest 5 | select -property, eventid, timewritten, message | sort -property timewritten | convertto-html | out-file c:\error.htm
This can be used by other admins to check the webpage find errors and fix them. This can be automated and scheduled
-FilterScript parameter – can just type {} without -filterscript
Whatever happens inside the {} is your filter
Where-object fiters only the data you want to see. Usually abbreviated to just where
$_ is a special symbol. means the current object crossing the pipeline store it in $_
This is an important variable
Get-service | where {$_.status -eq “running”}
Get-help *comparison* (comparison operators)
Get-help *operators*
$PSItem works the same way as $_
Get-service | where {$PSItem.status -eq “Running” -and $ -like “b*”}
Pseudo code example
Get-stuff | sort | where -somestuff |out-file
Get-stuff | where -somestuff | sort | out-file
2nd command is better as you don’t want to sort everything when you only need some stuff
You want to filter as far left as possible not always with where but with the cmdlet itself
Most of ps is case insensitive. There are some cmdlets require case sesitivity but this will be highlighted in documentation.
Gps – too many items so we want to filter this so we pipe it to where
Gps | where {}
3 lines of code far more powerful than sql
Where basically takes each object that comes in the pipeline assigns it to a variable $_ or $PSItem
Then secondly we evaluate the code within the brackets {} (we run the code)
Then thirdly if code returns true we pass the object on if not we throw it away
Memorise this algorithm one of the few things to memorise
(At 35 mins in the video)
This can be done without the brackets {} simplified
gps | where {$_.handles -ge 1000}
Gps | where handles -ge 1000
Don Jones Windows Powershell in a month of lunches, Chapter 9

Module 5 – Pipeline deeper

Get-service | gm
serviceController is the object – to see the object then get help to see the receiving cmdlet for the object
Need to know what type of object
Then look at help file on receiving cmdlet
Get-help stop-service -full
Look at parameters section they have a capability.
Shows if they accept pipeline input?
-name does accept by value and by propertyname
Inputobject of stop-service works with servicecontroller
Get-service | stop-service – if the nouns match its likely they will work together on the pipeline
Get service | get-process
Help get-process -full the -inputobject is Process so it fails to match servicecontroller by value
But the -name parameter does accept pipeline input by PropertyName
What this means does it have a propertyname the same known as -name then that means the cmdlets can be hooked up and work together
Whenever you want to know anything about an object you pipe it to gm
Get-service | stop-process -whatif
Get-process calculator | dir
Dir takes a path and process object has a path
(15 mins of the pipeline deeper video)
Some cmdlets like get-adcomputer have safety so they don’t just run and will need some parameters. So get-adcomputer shows a filter prompt and you can enter * for everything but be careful you don’t want to pull all the computers in a large network
Get-adcomputer -filter * | get-service -name bits (bits status on every computer)
Get-adcomputer -filter * | gm find out what object i am working with, check if it works byvalue. So the object is ADComputer.
Help get-service -showwindow – search byvalue press next
InputObject accepts value but accepts serviceController object not ADComputer so check byPropertyName
Look at ComputerName in get-adcomputer that property is called Name
Search the help window for bypropertyname
– computername accepts input bypropertyname but for a service so won’t work
If there was only a way to change the Name property in get-adcomputer to ComputerName
You can take the existing property of get-adcomputer name and change it to computername in other words make your own properties
This syntax with @ is something you will have to learn
Get-adcomputer -filter * | select -property name, @{name=’ComputerName’;expression={$}}
Can be shortened with n and e:
Get-adcomputer -filter * | select -property name, @{n=’ComputerName’;e={$}}
If you pipe above command to gm then you will see the ComputerName property
Get-adcomputer -filter * | select -property name, @{n=’ComputerName’;e={$}} | get-service -name bits
Sometimes you will have to make a custom column or calculated property. It is worth spending time on this stuff its the core of ps
Get-wmiobject -class win32_bios -computername dc, s1,s2
Get-adcomputer -filter * | get-wmiobject -class win32_bios
What is in the () it will do those first
Get-wmiobject -class win32_bios -computername (get-adcomputer -filter *)
This is the 4th and last way of doing it, last line of resort if a cmdlet doesn’t support pipeline input, most of them do.
Get-wmiobject -class win32_bios -computername (get-adcomputer -filter * | select -expandproperty name)
Expandproperty (think extract that)
In powershell v3 this is easier
Get-wmiobject -class win32_bios -computername (get-adcomputer -filter * ).name
.name is shorthand syntax to do that commandline
Script Parameters
Get-adcomputer -filter * |get-wmiobject win32_bios -computername {$_.Name}

Module 6 – Remoting

Universal code execution
You have code sometimes you run it here but you want to run it anywhere
You want to run code on those machines as myself or as other credentials
Sometimes i want to run it get results back immediately or later
Sometimes want to run it to do anything or certain cmds in secure environments
Sometimes want to run it for a long time shut down machine and then continue when machine comes back up
Jobs run in background
Workflow – run things, suspend things shutdown then continue where i left off
WinRM is the service running that does all the remoting
Enter-PSSession -computername Server1
Its encrypted with kerberos you can use ssl over internet
PS remoting is enabled in server 2012 or in GP
Enable-psremoting but you can use GP to make it easier on the network
A conversation needs to be had with security guys to enable this, free ebook on secrets of remoting explains what security guys need to know
This is required because a lot of new tools have ps remoting requirement
This needs to be turned on
One port to deal with so easy with firewalls
Access dc: mstsc /v:dc
Server 2012 core is default for security performance etc
Invoke-command -computername dc,s1,s2 {get-eventlog -logname system -new 3}
Invoke-command -computer dc1 {get-service -name bits} | gm
Look at the Typename is deserialised, this has better performance on remoting
You can do all the code on 1 machine and run commands remotely
Remote into server 2012 box
Enter-pssession pwa
Get-windowsfeature – shows installed roles and features
Get-windowsfeature *powershell*
Install-windowsfeature windowspowershellwebaccess
This installs IIS, new module with 6 additional cmdlets, use help to find them
Get-help *pswa*
Install-pswawebapplication -usetestcertificate – you need to use https as its over internet or can use the test certificate. Dont use test cert in production
Add rules who should have access
Add-pswaauthorizationrule -username -configurationname
Users bases on configs, some can do get only some can set
Add-pswaauthorizationrule * * * – anyone can do anything full access
Start iexplore https://pwa/pswa
You then have web access to powershell (cert expires in 90 days)
Invoke-command -computername dc,s1,s2 {get-eventlog -logname system -new 3} | sort timewritten | format-table -property timewritten, message -Autosize
Icm dc,s1,s2 {get-volume} | sort sizeremaining | select -last 3
Can be exported to csv, html and really quickly check disk spaces
To run scripts you need some security
Powershell secured by default
Save scripts as .ps1 opens in notepad by default for security
Dont associate ps1 with powershell
You run scripts from the cmdline
You need to be clear what you want to run
Type full path to script or .\ in the current directory

Module 8 – Automation

Default execution policy is Restricted
Digital signed and someone you trust
Create new self signed certificate
View the certificate drive
Dir cert:\currentuser -recurse -codesigningcert -outvariable a
$cert = $a[0]
Set-executionpolicy “allsigned”
Cannot run script as it is not signed
Dont sign stuff you havent understood
Set-authenticodesignature -certificate $cert -filepath .\test.ps1
You can choose to run once or trust and always run from this person
Remotesigned is easier to get started with
You want to move to allsigned as soon as possible
Use group policy to set allsigned this is a good control you can stop downloaded scripts from running
Get-help *variable*
These are not really needed
Variables can be done in another way
They take text, integers and more
$MyVar=get-service bits
This can even store an object in the variable
$ sign infront is a variable to show its not a cmdlet you have to know
$Var=read-host “enter a computername”
Get-service -name bits -computername $var
Write-host $var -foregroundcolor red -backgroundcolor green
You cant automate console apps that output to the console they are the enemy of automation write-host is another console app so avoid it
Use the word show to say when there is a script that cannot be scripted
Variables in {} brackets can be crossed between ps windows or other machines

Module 9 – Automation in scale Remoting

Reusable sessions
Icm -session $sessions {$var=2}
Icm -session $sessions {$var}
Output: 2
A lot of invoke commands is not that efficient
Going to go to dc start ps and set variable
Icm -comp dc {$var=2}
icm -comp dc {write-output $var}
the variable is not there anymore when the console dies everything dies
So you need to keep running ps using sessions
$sessions=new pssession -computername dc
this creates a variable which keeps powershell open
Instead of using invoke command you can now use invoke for the -session
Icm -session $session {$var=2}
icm -session $session {$var}
output = 2 so the ps session is still running so the variable output appears
measure-command {icm -computername dc {get-process}}
this shows how long the command is taking
measure-command {icm -session $sessions {get-process}}
this should be faster
$servers= ‘s1’ ’s2’
$servers | foreach{start iexplore http://$_}
$s = new-pssession -computername $servers
This gets you sessions to the remote boxes
create web server or you can use for hyperv server. $s can me as many servers as you want
icm -session $s {install-windowsfeature web-server}
$servers | foreach{start iexplore http://$_} – this now has iis running
$servers | foreach{copy-item c:\default.htm -destination \\$_\c$\inetpub\wwwroot}
This copies your webpages to all servers
you can just script this and add to it to automate install and configuration of servers and features
You dont need to install tools cmdlets on each machine
Create session to the machine that has the cmdlets
server 2012 has the ad cmdlets, exchange server has the exchange cmdlets
$s=new-pssession -computername dc
import-pssession -session $s -module activedirectory -prefix remote
get-help *remotead*
get-remoteadcomputer -filter *
get-help vs get-command
get-command is more structural
$c= get-command get-process
you import the stuff from other computers no need to install everything and use disk space
Referred to as implicit remoting
you create session with credentials then you use them everytime

Module 10 – Scripting and PS ISE

Ctrl R to toggle script window in ISE
Get-wmiobject win32_logicaldisk -filter “DeviceID=’C:’” | select freespace
Get-CimInstance win32_logical
In ise when you are at the end of logical hit ctril space to see a popup intellisense against the wmi namespaces
Hit enter after a pipe | for >> next line continuation – works in the powershell not ise
Get-wmiobject win32_logicaldisk -filter “Deviceid=’c:’” | select @{n=’freegb’ ;e={$_.freespace / 1gb -as [int]}}
In ISE hit ctrl c then can ctrl v into the script window
$computername =’localhost’
Get-wmiobject -computername $computername -class win32_logicaldisk -filter “DeviceID=’C:’” | select @{n=’freegb’ ;e={$_.freespace / 1gb -as [int]}}
Make a parameter on the fly for what you need
this is a short explanation
This is a long description
.Parameter ComputerName
this is for remote computers
Diskinfo -computername remote
This is a remote computer
function Get-diskinfo{
Get-wmiobject -computername $computername -class win32_logicaldisk -filter “DeviceID=’C:’” | select @{n=’freegb’ ;e={$_.freespace / 1gb -as [int]}}
Save as diskinfo.ps1
now on command line run diskinfo.ps1 -computername dc (you can run the script on any computer)
[string completes the syntax lets you fill the help file
[CmdletBinding()] makes things mandatory so adding Parameter mandatory true makes you have to enter a computername on the commandline
This is known as Parameterized script
Adding the script comments creates the help for the script with the categories
New script window hit ctrl + j for cmdlet snippets
Can use these as templates to create scripts
In ISE you can collapse the comments section clicking the –
function Get-diskinfo{
It will tell you missing closing brackets with red squiggly
When the script ends the get-diskinfo will be gone
When you run with . . It retains the variables so will remember the get-diskinfo
. .\Diskinfo.ps1
Get-diskinfo – computername localhost (can use tab completion on get-diskinfo)
Modules are the future and you can make your own. Save file as psm1
enter import-module .\diskinfo.psm1 -force -verbose
cat Env:\PSModulePath (Special location to store your modules so they are loaded everytime)
$env:PSModulePath -split ‘;’ (makes the output on screen more readable)
Powershell module locations:
Dont store your modules in the above path
Location to save your scripts:
The name of your module psm1 file needs to be the same name as the folder
This will autoload the module when powershell starts
You can add more functions to the module

0 0 votes
Article Rating
Share this Post
  • 1
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x