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