Skip to content

Powershell Notes – Advanced Tools and Scripting

Share this Post
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Course 2 – Advanced Tools and Scripting

Instead of real time we will do scripting
Make tools to use and share
DL scripts from here: https://powershell.org/2013/07/29/mva-powershell-jumpstart-2-scripts-for-aug-1st/
Steps to create tools with modules inside scripts and clean them up
Automate things you need to do again
In Win Server 2012 R2 default execution is remotesigned and Remoting is now on by default
Run script with full path or .\test.ps1 will not work with test.ps1 for security
Run ISE as admin it has intellisense in script and PS window. Use in splitscreen mode to run commands and paste into script window. Ctrl R switches between Script and PS window
RemoteSigned is the best policy
On commandline you can type: ii . (invoke item the dot bring it up)
When downloading scripts go to script file properties to see if it is blocked
New cmdlet called unblock-file *\* -Verbose
This will unblock the all files in the folder/subfolders

Variables can store strings, text, numbers, modules
Press F8 to run highlighted text in script editor
Avoid Var names with spaces or with {} these brackets but it can be done still
1Var.ps1 script example
$x = [int]”1″ – if you want variable as integer do this
$x = “test”
[int]$x =”1” – If you only want var to contain integers do this
$d = “12/25/2017”
$d
12/25/2017
PS C:\Users\iq\Documents\PS_Scripts> $d.PadLeft(100)
12/25/2017
PS C:\Users\iq\Documents\PS_Scripts> [datetime]$d = “12/25/2017”
PS C:\Users\iq\Documents\PS_Scripts> $d.Day
25
PS C:\Users\iq\Documents\PS_Scripts> $d.DayOfWeek
Monday
PS C:\Users\iq\Documents\PS_Scripts> $d.AddDays(- (7*6))
13 November 2017 00:00:00
These are known as types and are quite powerful functions for strings
Cmdlets for variables are available but better to write it all out as a script
All the types are available that are in .net you can find out more about types from msdn
The vars are different in powershell to other languages
Validation string
[validateteset(“a”,“b”,”c”)] [string]$x = “a”

2Quotes.ps1 script
Vars in double quotes are resolved and ignored in single quotes
Use the back tick next to 1 key ` to control the var inside the double quotes
We don’t have to put quotes because PS knows how to handle it

$p = Get-Process lsass

“Process id = $p.id”
$p.ToString()
“Process id = $($p.id)” – anything in () gets executed
“Process id = $(read-host -prompt “what should I give them?”)”
‘Process id = $(read-host -prompt “what should I give them?”)’
Known as sub expression
Snippets
search command window pane for snip
Here strings this is a multi line string, it can contain carriage returns
Put script code in @’ and at the end ‘@ and at the start of first @’ type $script = @’

New-IseSnippet
Description: This is a test
Text: $script
Title: _MYVARTEST
Author: Me

Click run in the commands window then in script window press ctrl+j then choose _MYVARTEST
So when you create your own snippets you use the here string for multiline and single quote not double as you do not want the $ vars in the script to be expanded
$Service[0].Status
Range Operator
1..4
10..15
$Services[1..5]
$Services[5..1]Simple Scripts and Functions
$Services.count
$Services.[-1]
Script 4 example
notepad .\computers.txt
Import-csv .\Computers.csv
() means do what is inside them first
| gm this shows TypeName: PSCustomObject so need to extract column name

Get-Service -name bits -ComputerName (Import-csv C:\Computers.csv).computername
If statements
check for files, path, error handling
else and elseif
you can use switch of elseif is confusing: 6Switch.ps1

Simple Scripts and Functions

2SettingVars.ps1
param can then use -computername with it on the commandline
param(
[String]$ComputerName=’localhost’,
[String]$Drive=’c:’
)

Run .\2SettingVars.ps1 -computername localhost
3Params.ps1 – [CmdletBinding()]
This is what transforms a functions into a cmdlet
when you use tab completion and intellisense you will get many more options and validates your code for Cmdlet format

See powerpoint slides
ISE can be used to run scripts without dot sourcing
In powershell commandline you need to run . . before script

get-diskinfo cmdlet made
-outvariable can output to variable

Get-PSDrive – shows all drives and PS Drives includes registry
dir function: (you can see get-diskinfo)
Remove-Item Function:\get-diskinfo
This may not clean everything out so thats why we have modules
Ctrl+T brings new PS clean environment in ISE
Indent scripts to make it easier to read
You can add multiple functions to same script file
You can collapse blocks of text
you are now creating a script of parameterised functions that are becoming a toolbox for you

Advanced Functions

purpose of advanced functions, advanced function template
create and test parameters
adding code, writing objects to pipeline
create functions similar to cmdlets, these are not same as compiled cmdlets but are perfect for IT Pro
Get-Help *function*
lots of help on this
Big distinction with Cmdlet and function
The function has Begin, Process and End
Mod4 scripts\1SimpleTemp.ps1
ISE has built in function snippets. Ctrl+J

2 methods first one is much better:
invoke-command -ComputerName (get-content servers.txt) {} (Parallel faster, We handle concurrency control, 3 lists todo list, in progress list and done list)
foreach ($s in (Get-Content servers.txt) ) { Invoke-Command } (This is serial will wait if 1 of the servers was down, takes a long time)
Hash Table critical component of PS
Ctrl+H Search and Replace
PS is case insensitive so c$ is same as C$
5MainCodeEnd.ps1
General order of output is random but you have keywords order to order output
So you make a function and idea is another admin uses it and pipes to select object and selects the order they want but in PS3 we have ordered. See help file on hash tables

Can create PS Object
Can assign methods and properties
With object you can use select and where etc
It is a proper tool and can fit in with tool chain of other tools can combine with other tools to form more info
Get-CompInfo -ComputerName -ComputerName localhost | select -property computername
You can now select certain properties so its a useful tool
Get-CompInfo -ComputerName -ComputerName localhost | convertTo-Json
Outputs to Json quite popular, other tools can read Json
So PS can import Json to PS and output to Json
You make your own tools to solve your own problems

More on Parameters

Parameter Mandatory=True
Localisation of language automatically for the error messages
Get-Help about_Functions_Advanced_Parameters | clip
This has info on advanced parameters and pipe to clipboard so you can paste into script window or word to read it
Mod5\1mandatory.ps1
to stop script from keep asking for computer press enter on blank line or ctrl c

ValueFromPipeline (allows pipeline input) so get-content
get-content c:\computers.txt | Get-CompInfo
get-compinfo | out-file c:\users\iq\documents\output.txt
get-compinfo | out-gridview
Parameter Alias
ValidateSet – When you want only certain values typed
Intellisense knows what is in the validateset
Ctrl + Space can display the intellisense popup
If PS tool is very network intensive then you can restrict to specific machines
7ParamPattern.ps1 Regex validation
Search Bing for Regex and you can learn them

help about_Functions_Advanced_Parameters -ShowWindow
ValidateScript – allows you to run code that is used to validate against
If you mess up then go to examples in help
Ctrl+J popsup snippets window

Writing Help

help about_comment_based_help
use comment based help but you can use update help and xml based if you are selling scripts

get-help get-testhelp
get-help get-compinfo -full

get-help get-compinfo -parameter computername
use lots of examples to help you
you can copy the output and paste into example comment block to quickly fill up the help section

Error Handling

ErrorActionPreference
Default answer, user can be offered to do something different
dir variable:*pref*
Mod7\1erroraction.ps1
-EA ErrorAction
-EV ErrorVariable
$MyError
The error is stored in variable you can type $MyError to view it or outfile this variable to text file
help about_commonparameters
Error action Stop will make script go to catch block
cat errorlog.txt (reads the txtfile in the shell)
to make error logging better write to a logfile or write to the real log file
write-eventlog -logname Application -Source Filename -EntryType Information -message “script foo ran”
Track time saving by running scripts
First create source and log that it ran
have script go across all machines, look in app event log for eventid
get data and have a table to see which script saves the time to see weekly, monthly, yearly
you have a way to show how your tool is being used by get-eventlog
reducing human or man hours
writing to eventlog is a great way to track when, how often a script was run etc

Tool Making

you should provide -WhatIf -Confirm in your scripts
shouldProcess allows whatif and confirm to be set
good if doing something risky you can use whatif and confirm to double check
This is important if tool is changing something
. is local machine same as localhost

Script and Manifest Modules

You don’t want to run script each time you want to perform a function in a script so you make a module
save script as psm1 file
Manually import module: import-module ….\MyTools.psm1
get-command -Module Mytools
Have to import it everytime so you need to be able to load dynamically virtual modules
Need to remove module and re import for testing
So you use PS Module Path
$env:PSModulePath -split “;”
Don’t put your modules in:
C:\Win\system32\WinPS\1.0\Modules
Put modules in the documents path
The path displayed does not exist in documents so create it
Mod9\Launch.ps1
Folder name and module name need to be exactly the same
So folder name MyTools and Module name MyTools
The Launch.ps1 creates the folder and the correct name and copies the module to it
Load PS console now you can type Get-CompInfo -ComputerName .
The . Is localhost
Get-Module -ListAvailable
Get-Module MyTools

Module is a directory that has a psm1 file and/or a manifest
Manifest tells all the things that are part of that module so you can have a set or part of a module
Module can include other things and be intentional about what others see and don’t see. Manifest can be just the script file, script file and formatting files like type and view files, processing can be done when you start do this initialisation or a data file.
V4 PS has DSC
I declare what I want to be push it to a machine and it works
A WMI Provider grabs and looks at it then looks at WMI Provider and does the task if no WMI Provider and then it goes to Powershell Provider which has, get,set,test target resource. It looks at resource name then look for module same name if it matches gets called and done. 3rd resource no wmi, no ps then you can register a Rest API could be linux then it is a PS Module zipped then this gets deployed and then Provider gets called.
With DSC you can make a SQL Module and then that gets called with your specific config and scripts
psd1 are data files. These are a subset of powershell language used for expressing data
it doesnt give full capabilities but it is constrained so it is secure

Show-Command New-ModuleManifest
Show-Command is an awesome tool to explore
you can isolate to particular host, ps version etc required dlls to run
shortcut you can type ise .\MyTools.psd1 to open in ise
This is a psd1 manifest you can edit the version in this or open the whole manifest thing
you can use this manifest as a generic and customise
You can create a custom view with manifest a default view
$Host – This displays PS Host info
The xml file shows how to display the view in powershell command
c:\windows\system32\windowspowershell\1.0\DotNetTypes.format.ps1.xml
Search for Process and this shows the column title and widths that are displayed
This is digitally signed so you cannot change it but you can copy the file and make your own custom template
you can attach your own xml view file to your manifest
gps *ss | ft (format table)
gps *ss | fl (format list)
gps *ss | ft -View sodifjsoidjfsdof
this will display error and show you what views you can use
cls; gps * | sort priority | ft -View Priority
cls; gps * | sort starttime | ft -View starttime
correction on WithView.ps1
$obj.PSTypeNames.Insert
Don Jones learn PS toolmaking in a month of lunches
MS Marketplace does toolmaking


Share this Post
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

avatar
  Subscribe  
Notify of
Scroll Up