-
Intro
-
Cmdlets
-
Verb-noun pairs
- get-childitem
- Sort-Object, Select-Object, New-Object
-
Get/Set-ExecutionPolicy : per user
- Restricted
- AllSigned
- RemoteSigned
- Unrestricted
- Test-Connection, Restart-Computer, Start-Sleep
- Get-Help *-* : list all comdlets
- Parameters: -OutVariable, -WhatIf
- $env:path += ";DirectoryToAdd"
-
Scripts
- ./script to run script in current dir if not in env
- Reference elements in array starting by index position 0 : [0]
- Self-signed certificate: Makecert.exe
- Ctrl+S: Pause display - F7: History
- 8 sessions (execution environments)
- Set screen buffer size to 2000-3000
-
Poweruser
-
Environment
- Runas Administrator
- Start PS from cmd.exe:
Powershell -nologo -noprofile -command "get-process | sort-object Id"
- Piping: Command1 | Command2 | Command3
If cmdlet accepts input, it has -inputobject parameter
-
Script block: series of commands (;) executed in sequence, { ... ; ... ; ... }
- From cmd.exe: "& {Commandtext}"
-
Input
- Ctrl+End: delete all chars after cursor
-
Parsing
- Unit of execution: 1st char till ; or EOL
- Token: Value within unit of execution
- Expression mode: 1st token is not cmdlet, keyword, alias, function or external util but strings ("") or numeric values.
- Command mode: 1st token is cmdlet, keyword, alias, function or external util which PS invokes.
With special chars $, @, ", ' and ( expression mode is used.
- Variable definitions start with $
- & operator forces command mode: $a = "get-process" &$a
- >>subprompt indicates its waiting to complete expression
- ` backward apostrophe let you split commands across multiple lines or servers as escape char
- Object is collection of data points that represent an item. Objects have a data type like String, Boolean, Numeric and methods and properties.
-
Output
- Formatting cmdlets arrange the data to be displayed but do not display it. The output cmdlets take care of that.
- Sort-Object [-Unique] : sorting can be on one property or multiple
- get-service | get-member -membertype *property : use get-member to see all properties of an object
-
Output streams
- Standard
- Verbose
- Warning
- Debugging
- Error
- Write-Host: write output explicitly and use formatting options like colors,..
- Write-Output: accepts Input objects
-
Out-Host
- Out-File
-
Redirection
- Command1 | Command2 : Output 1 to Input 2
- Command > filename : Output to file, creating or overwriting if necessary
- command >> filename : Appends output if file already exists.
- Command 2> filename : Error output
- Command 2>> filename : Appends error output
- Command 2>&1 : Sends error output to same destination as standard output
-
PS Environment
- Profiles: .PS1
-
Extensions
-
Snap-ins
-
Providers
- Drive
- cmdlets
-
functions
- Named set of Powershell commands
-
modules
- get-module -listavailable
-
functions
- get-childitem function: to see all functions
- cmdlets
- providers
- Remote execution of commands
- remote sessions
- remote background jobs
-
Sessions - Jobs - Remoting
-
Remoting
- winrm quickconfig
- Enable-PSRemoting -force
- Invoke-Command
-
Without WinRM
- get-help * -parameter ComputerName
-
sessions
- Enter-PSSession
- New-PSSession
-
Background jobs
- Get-Job
- Start-Job
- Receive-Job -Keep
-
Core PS structures
-
Expressions - Operators
-
Expression
- Calculation that evaluates an equation and returns a result
-
Arithmetic
- return numeric values
-
Assignment
- assign or set a value
-
Comparison
- compare values
-
Regular
- [Chars]
- matches exact chars
- .
- matches any single char
- [value]
- matches at least one of the chars
- [^]
- matches any chars exept in brackets
- ^
- Matches the beginning chars
- $
- Matches the end chars
- *
- Matches any pattern in a string
- ?
- Matches single char in string
- +
- Matches repeated instances of preceding chars
- \
- char that follows is literal char
-
Operator
- element of expression howto perform calculation
-
Arithmetic
- + / % * -
-
Assignment
- = += -= *= /= %= ++ --
-
Comparison
- -eq -ne -lt -gt -ge -contains -like -match -replace
- ( ) to group expression operators
- $( ) to group collections of statements
- @( ) to group collections of statements, execute them and put results into array
-
Variables - Values
-
Automatic
-
$_
- where-object {$_.PropertyName -ComparisonOp "Value"}
- $Args
- $Error or $Error[0]
-
Preference
- PS customization
- User-created
-
Environment
- Set-Location env:
- Get-item -path env:*
- Get-Variable - New-Variable - Set-Variable
- In PS you directly assign values without declaring the data type because
PS has built-in capability for determining the data type
-
Variable scope can be global, local, private
- global > script/local > private
-
Strings
- A series of alphanumeric or non-alphanumeric characters
- PS has parsing rules for strings that modify the way values are handled.
-
single-quoted: 'string'
- literals passed to the command, no substitution
-
double-quoted: "string"
- does substitution (ex. variable is replaced by its value)
- use ` back apostrophe char to prevent substitution of variables
which serves as escape char as well as line-continuation char
-
Escape codes
- `'
-
`"
- double quotation mark
-
`0
- null char
-
`b
- backspace
-
`n
- new line
-
`r
- carriage return
-
`t
- horizontal tab
-
Multiline strings
- precede and follow the string value with @
-
operators
-
=
- Assigns a string value to a variable
-
+
- Concatenates strings by adding them together
-
Arrays = Collections
-
$VarName = Element1, Element2, Element3
- $VarName[Index]
-
Cast array
- $VarName = @(Element1, Element2, Element3,...)
- If you use ; instead of , to seperate values, PS treat each value as command text.
PS executes then each value and stores the result.
- add elements with += operator
-
MultiDimensional
-
2-dimensional
- first reference row then column index
- $myArray= new-object 'object[,]' 4,3
-
handled as objects
- First create array, then populate array
- PS supports up to 17 dimensions
- $a = new-object 'object [,,]' 5,5,3
-
Aliases - Functions - Objects
-
Aliases
- save you keystrokes, each command can have multiple aliases
- foreach, cls, ls, cat, gl, ps, gv, mount, cd, sleep, write
-
cmd /c dir
- runs windows internal cmd commands from PS
- Get-Alias New-Alias Set-Alias
-
Functions
- named sets of commands that can accept input
-
to create: function name {commands}
- ex function getwinrm {get-service -name winrm}
- define parameters and use parameter names to pass in values
-
Extended Functions
- Use Begin, Process and End code blocks
-
Filter functions
- function with only process block
- often use $_ var to work with current object
- ex filter Name { $_.Name }
- get-psdrive | Name
-
you can also work with functions via function: provider drive
- set-location function:
- get-childitem
- Tab expansion: -
-
Objects
- collections of data that represent items in defined namespaces
-
All objects have type, state and behavior
- State=properties, behavior=method
- <object> | get-member
- $ObjectName.PropertyName
- $ObjectName.PropertyName = Value
- $ObjectName.MethodName()
- [ClassName]::PropertyName
- [ClassName]::PropertyName = Value
- [ClassName]::PropertyName::MethodName()
- Static properties/methods of .NET Framework
-
COM
- New-Object [-ComObject] String
-
WMI
- Select * from WMIObjectClass where Condition
-
in PS
- Get-WmiObject -Class WMIClass -Namespace root/cimv2 -ComputerName Computername
- Get-WmiObject -list | where {$_.name -like "*Win32_*"}
- popular classes
-
Managing Computers
-
Transcripts
- Record all your activities
- Start-Transcript
- Stop-Transcript
-
Transactions
- Registry provider
-
subscribers
- Subunit within transaction
- Get-Transaction, Start-Transaction, Complete-Transaction
- get-help * -parameter UseTransaction
-
Scripts
- Comments: #
- MultiLine comments: <# comment #>
-
if (condition1) {action1} elseif (condition2) {action2} else {action3}
- Switch Construct
-
Control Loops
- for (countstart; condition; countnext) {Codeblocktorepeat}
- ForEach (item) {CodeblockTorepeat}
- while (condition) {CodeBlockToRepeat}
- do {CodeblockTorepeat} while (condition)
- do {CodeblockTorepeat} until (condition)
-
Roles - Features
-
ServerManagerCmd
-
import-module servermanager in PS
- Get-WindowsFeature
- Add-WindowsFeature
- Use -WhatIf parameter
-
Inventory
-
Basic Systeminfo
- $env:computername
- System Configuration
- Hardware
-
List every available .NET type
- [System.AppDomain]::CurrentDomain.GetAssemblies() | Foreach-Object {$_.GetTypes() }
-
Filesystem - Security - Audit
-
PS Drives, dirs, files
- Query # computers with Invoke-Command
- New-psdrive to map to share,dir or reg
- Get-psprovider
- New-item -type [Dir | File] -path path
- Copy-Item source destination
-
File Contents
- Get-Content
- Set-Content
- Add-Content
- Clear-Content
- -Force param. to access hidden, system or RO files
-
ACL
- Get-Acl
-
Shares - Printers - TCP/IP
-
Shares
- Get-Wmiobject -Class Win32_Share -computername
- Default Everyone Read access
- $shareobject.Create(FolderPath, Sharename, type, MaxAllow, Descr)
-
Printers
- Get-Wmiobject -Class Win32_Printer
- Get-Wmiobject -Class Win32_TcpIpPrinterPort
- %systemroot%\inf
-
$printer = New-Object -Comobject Wscript.Network
- $printer.SetDefaultPrinter("\\server\share")
- $printer.AddWindowsPrinterConnection("\\server\share")
-
TCP/IP
- one Local Area Connection per adapter
-
IPv6
- first 64 bits=network id, last 64 bits=network interface
-
$Firewall = new-object -com HNETCfg.FwMgr
- $Firewall | gm
-
Registry
-
Perform changes in transaction context
- Start/stop-Transaction
- REG_BINARY
-
By default only HKLM & HKCU
-
set-location hklm:\path
-
get-childitem
- get-itemproperty [-path] Keypath [-Name] ValueName
- New-item [-type registrykey -path hkcu:\software\test
- new-itemproperty [-path] Path [-name] Name [-Type type] [-value value]
- copy-item(property) source destination
- All reg keys are containers
-
Monitor - Optimize
-
Eventlogs
- Get-EventLog
-
$e = get-eventlog -newest 100 -logname "application"
- $e | where-object {$_.EntryType -match "warn"}
-
Custom events (except security log)
- Use eventcreate /l logname /so EventSource /t Type /id Eventid /d Descr
- XPath
- eventvwr Computername /v: Queryfile
-
Services
- Get-Service -computername name | where-object {$_.status -eq "Running"}
-
sc.exe
- use computernames as UNC \\computername
- NT Authority\LocalSystem
- NT Authority\LocalService
- NT Authority\NetworkService
-
System Restore
- Enable-ComputerRestore
- Checkpoint-Computer
- Restore-Computer
-
Computers
-
Add-Computer
- Any authenticated user can join pc to domain
- Restart-Computer -force
- Test-Connection
-
Performance
-
Processes
- Get-Process -Computername
-
Memory Leak
- Processes use more memory than they should
- Working memory set
- HandleCount
-
Non-paged pool
- Objects in RAM that can't be written to disk
-
Multithreaded
- allows concurrent execution of proces requests
-
Peak memory
- if very large -> memory leak
- Single app might start # processes
-
Performance Monitoring
-
Get-Counter
- \\Computername\ObjectName\ObjectCounter
-
Page Fault
- Soft page fault
-
Hard page fault
- Page Reads/sec
- Page Writes/sec