II. Precautions: Non-Medical

  1. Not for Medical Care
  2. The author uses several software packages and programming languages to develop FPnotebook content
  3. For convenience, a dozen pages in FPNotebook are dedicated to quick notes on content creation

III. Background

  1. Commands are shown in Pascal Case for readability, but they are typically used in lower case
    1. In most cases, Powershell is case insensitive
  2. Running script files (.ps1) from within powershell command line
    1. Get-Help About_Scripts
    2. Running a script starts with a period (".") and then the file path: . ".\myfile.ps1"
    3. If Running a script in the same directory, precede the script file name with ".\"
    4. Scripts can also be used within pipelines
  3. Comments
    1. # precedes each plain text comment
  4. Clear screen
    1. Clear-Host (cls)
  5. Get-History
    1. Displays a list of all Powershell commands issued during the current session
  6. Transcript
    1. Start-Transcript
      1. Starts copying all powershell window output to file (filename output to window)
    2. Stop-Transcript
      1. Stops copying powershell window output to file (filename output to window)
  7. Debugging
    1. Breakpoints (F9) can be set within Powershell ISE
    2. May step into (F11) or over (F10) functions
    3. Within the command line, variable values may be queried (or modified) while at line break
  8. Alias
    1. Get-Alias
    2. New-Alias -name clr -value clear-host
      1. Set an alias (shortcut abbreviation to a function)
  9. Powershell IDEs
    1. Powershell and PowerShell ISE
    2. Visual Studio with POSH Tools Extension
  10. Cmd
    1. Most old command-line utilities will run without a problem from within Powershell
    2. However, there may be exceptions and typing "cmd" at the powershell prompt, will change to a command window
    3. Type "exit" to return to the Powershell prompt

IV. Techniques: Piped Expressions

  1. Pipes (|)
    1. Get-Help About_Pipelines
    2. Get-process | where-object {$_.cpu -gt 1} | sort-object -property cpu -descending
      1. Finds all processes
      2. Then pipes all processes to a filter (cpu>1)
      3. Then pipes filtered processes to a descending sort based on the "cpu" member property
  2. ForEach-Object
    1. ForEach-Object {$_.propertyName}
      1. Used in a piped expression to act on each item as directed in the bracketed clause
      2. The $_. prefix followed by the property name, refers to the object within the iteration
  3. Where-Object
    1. $_
      1. Represents the current item in the iteration
    2. Where-Object ($_.ProcessName -eq 'chrome')
      1. Filters process to only the one named 'chrome'
  4. Write-Output
    1. See output below

V. Techniques: Output

  1. Write-Output
    1. Writes objects that may be piped to another function (and if no pipe, then to the console)
  2. More
    1. Use after a pipe (e.g. get-service | more) to display the info in pages (space-bar moves to the next page)
  3. Out-File
    1. Out-File filename.txt
  4. Format-List (or fl)
    1. Outputs each table column on its own row (get-service | format-list)
  5. Format-Wide -Column 2
    1. Outputs piped data in 2 columns

VI. Techniques: Flow control

  1. Operators
    1. See specific comparison operators for strings, arrays and hash tables below
    2. Get-Help About_Operators
    3. Arithmetic: +, -, *, /, %
    4. Unary: ++X, X++, --X, X--
    5. Assignment: =, +=, -=, *=, /=, %=
    6. Comparison: -eq, -ne, -gt, -lt, -le, -ge
    7. Logical: -and, -or, -xor, -not, !
    8. Type: -is, -isnot, -as
  2. If
    1. If (1 -eq 1) {'one equals one'} elseif ($var -lt 5) {'below 5'} else {'the sky is falling'}
  3. Switch
    1. switch ($var) { 1 {"one"; break} 2 {"two"; break} 3 {"three"} default {"default"} }
    2. switch (1,2,3) {...} matches any or all of the item collection 1,2,3
    3. switch -wildcard ("hello") { "he*" {"matches wildcard"} }
    4. Use break unless you want to match more than one case/option
    5. String matches are case insensitive (exception: switch -casesensitive)
  4. For
    1. For ($i = 0; $i -le 10; $i++) { $i }
    2. $i=0; for (; $i -lt $arr.Length; i++) { $arr[$i] }
  5. ForEach
    1. Foreach ($i in 1..3) { $i }
    2. Foreach ($file in Get-ChildItem) { $file.Name }
  6. While
    1. $i=0; While ($i -lt 10) {$i++; $i}
  7. Do While
    1. $i=0; Do {$i++; $i} While ($i -lt 10)
  8. Break and Continue
    1. Break exits the current loop (but if embedded in an outer loop, it will continue to iterate the outer loop)
      1. Loops can be named and break statement can specify a specifc loop to break out of
      2. :outerloop foreach(...){ break outerloop}
    2. Continue exits the current loop iteration, and then continues with the next item in the loop
      1. Like "break", continue can also specific a loop name to return to
  9. Script Blocks
    1. Script blocks may be stored and executed
    2. $method = {Clear-Host; "Run Me"}
    3. & $method will execute the code (without the ampersand, only the text will be output, but not run)
  10. Try Catch Finally
    1. Error handling
    2. try {} catch { break} finally {}

VII. Techniques: Data types

  1. Variables
    1. Get-Variable (or GV)
      1. Displays all variables including system built-in variables
    2. Variables are preceded by $ and may be defined implicitly (typical use)
      1. $ten = 10
      2. $ten.GetType() returns int32
      3. $ten | Get-Member returns all methods on the int32 object
    3. Methods may also be called on literal values not defined with a variable
      1. "no variable".ToUpper() returns "NO VARIABLE"
      2. (10).GetType() returns int32
    4. Strongly typed variables may also be defined (used when calling COM objects)
      1. [System.Int32]$ten = 10
    5. Built-in Variables
      1. Includes $false, $true, $null
      2. $pth is the current location (equivalent to Get-Location)
      3. $home is the path for the user's directory
      4. $pid is the current process id
  2. Strings
    1. Comparison operators (-like, -match) listed above
      1. "..." -like
        1. "Pizza Parlor" -like "?izza *"
        2. ? matches a single wildcard character
        3. * matches multiple characters
      2. "..." -match
        1. Regular expression matching: "55126-8967" -match "[0-9]{5}-[0-9]{4}"
    2. Surround string definitions
      1. Double quotes(")
      2. Single quotes(')
      3. Here-Strings or multi-line strings: @" "@
        1. Also works with single quotes (must be double quotes)
        2. The closing quote ("@) must not be indented (must be flush with start of line)
        3. Need to be inside the ISE for this to work (not the immediate window)
    3. String Interpolation
      1. Variables may be enclosed in strings
        1. "There are $ten items in the list" will replace the $ten with its value
      2. Expressions may be used in strings
        1. "There are $((Get-ChildItem).Count) items in this folder: $(Get-Location)"
        2. "BMI is $(($wtKg)/($htM*$htM))"
      3. String formatting
        1. "There are {0} {1} in the {2}." -f $ten,"bugs","soup"
        2. "{0,8}" -f "hello" will right justify "hello"
        3. Used when specific formatting of variable value is needed (e.g. currency format, dates)
          1. Currency: "{0:C2} is in dollars" -f 12.25
          2. Hemidecimal: "{0:X0}" -f 250 will display the hex conversion of 250
          3. DateTime: "{0:MM/dd/yyyy hh:mm:ss}" -f $(Get-Date) will output current date as formatted
          4. Percent: P1 for one decimal, P2 for 2 decimal places
    4. May escape characters with backtick
      1. CrLf: `r`n
      2. Tab: `t
      3. Backtick will treat undefined characters as text (e.g. `$, displays a "$", not a variable)
  3. Arrays (zero based)
    1. Array operators
      1. $arr -contains 2 if the array contains the number 2; -NotContains may also be used
    2. Array manipulation
      1. $arr1 = 1,2,3,4,5
      2. $arr2 = 1..5
      3. $arr = $arr1, $arr2
        1. Creates a 2 dimensional array with 5 columns (1-5) in each of 2 rows
        2. $arr[0][1] accesses the item in the first column in the second row
      4. $arr = @(1,2,3,4,5)
        1. Formal notation (but usually short form is used as above)
        2. $arr = @() creates an empty array
      5. $arr[2] ="this replaces the third item"
      6. $arr += "appending new item to array"
      7. $arr -join ";"
        1. Concatenates each string in the array with a semi-colon
      8. $arr[2..4]
      9. $arr.Count
  4. Hash tables (dictionaries)
    1. Hash table operators
      1. $hash.Contains("hello") if there is a key "hello"; -NotContains may also be used
      2. $hash.ContainsValue("hello contents")
      3. $hash.Keys
      4. $hash.Values
    2. Hash table editing
      1. $hash = @{a=1; b=2}
      2. $hash['a'] = 5
      3. $hash.$a if we set the $a="a"
      4. $hash.Remove("a")
  5. JsonString (output to file)
    1. '{"name":"myname"}' | Out-File "myfile.json" -Encoding utf8
  6. Enum (introduced in Powershell version 5)
    1. Enum MyEnum { one two three}
    2. $enum = [MyEnum]::two

VIII. Techniques: Functions

  1. Function verb-noun ($parameter1, $parameter2...) { return "done"}
    1. Use approved verbs for naming (type get-verb to see verbs used in powershell)
  2. Return statement is optional
    1. Default is to return void)
    2. Return "done" may be written as only "done" and this will be returned
  3. Call functions as follows
    1. verb-noun "a" "b"
    2. verb-noun ("a","b")
    3. verb-noun -parameter1 "a" -parameter2 "b"
  4. Parameters may be passed by reference (instead of value)
    1. function verb-noun (

      $param1)...

    2. verb-noun (

      "hello")

  5. Pipeline enable function
    1. Three blocks are used within pipeline enabled functions
      1. Begin
        1. Runs once before process is started (init code). Optional and may be ommitted
      2. Process
        1. Called for one iteration for each item piped to the function
        2. Can return an item for each iteration which allows for other function to pipe from this one
      3. End
        1. Runs once before function exits (cleanup code). Optional and may be ommitted
    2. function verb-noun
      1. begin {}
      2. process { if ($_ -lt 10) return $_ }
      3. end {}
  6. Advanced function (allows for more control over parameter definitions)
    1. Allows for setting default param values, assigning parameter datatypes, and other settings
    2. Starts with cmdletBinding attribute tag, followed by each parameter definition above each declaration
    3. function verb-noun {
      1. [cmdletBinding()]
      2. param ( [Parameter(Mandatory=$false, HelpMessage="Type something here")]
      3. [int] $param =54
  7. Creating Help for custom functions
    1. Place help in comment block within the function using powershell official tags
      1. Place just below the function opening bracket
    2. Official tags
      1. .SYNOPSIS, .DESCRIPTION, .PARAMETER, .EXAMPLE, .INPUTS, .OUTPUTS, .NOTES, .LINK
    3. Example
      1. <# .SYNOPSIS I just made this up #>
  8. Help
    1. Get-Help About_Functions

IX. Techniques: Classes (Powershell Version 5, much simplified)

  1. See the older version of Object/Class creation below (much clunkier)
  2. Create Class
    1. Class MyClass { [string] $MyProp = 'default value' [string] MyFunction() { return $this.MyProp }}
      1. Standard class definition defines a property (MyProp) with optional default value and function (MyFunction)
      2. If function has no return value, define as [void]
    2. Class can have a constructor (as well as overloads) each named the same as the class
      1. MyClass(){...}
      2. MyClass([string] param1){...}
    3. Methods and Properties may be static
      1. static MyFunction([string] param2) { return param2 }
      2. static

        $MyProp = 'default value'

  3. Instantiate Class
    1. $object = [MyClass]::new()
    2. $object = [MyClass]::new('param 1 value here')
    3. $object.MyProp = 'new value'
    4. $object.MyFunction()

X. Techniques: Modules

  1. Module Overall Structure
    1. Modules are typically placed within their own directory (with the module name)
    2. Files include Module file (.psm1), manifest file (.psd1), and function files (.ps1)
    3. Manifest file defines which module to process (ModuleToProcess='filename.psm1')
    4. Module file, in turn, defines which functions to include (either inline or in separate files)
  2. Module file (psm1)
    1. Instead of .ps1, modules have extension .psm1
    2. Module name is the file name (without the path or extension)
    3. Module files contain multiple functions or include a link to external ps1 file
      1. Starts with period "." followed by the path and filename: . path/file.ps1
  3. Module manifest (psd1)
    1. Manifest is metadata placed within a file with extension "psd1" and within a module directory
    2. Enclosed in @{ ModuleToProcess = 'filename.psm1' GUID='e8f8...' Author... CompanyName... Description...}
      1. Use New-GUID to generate a new GUID
  4. System Defined Related Variables
    1. $PSScriptRoot
      1. File path of currently executing code
    2. $env:PSModulePath
      1. Shows the default locations (win env) Powershell will look for modules
  5. Module Commands
    1. Get-Module
    2. Import-module
      1. Import-Module path\module_name.psm1 imports the module into the current code
    3. Import-module -force myModule
      1. Forces a reload of imported module
    4. Remove-module myModule
      1. Unloads a module from memory (pass the module name)
  6. Scope
    1. Variables defined inside the module are typically private
      1. Globals can be defined in the module: $Global : myGlobal
      2. Best practice, however, is to avoid globals and return values from functions
        1. Script Variables, $Script : myScriptVar, may be returned from functions
    2. Functions inside of a module are all public by default
      1. Best to explicitly make functions public (and others default as private)
        1. Once a module defines any function as public, all other functions will become private as default
      2. Export-ModuleMember MyFunction-Public
        1. Exports a function as a public function
        2. All non-exported functions will be private
  7. Help
    1. Get-Help about_modules -online

XI. Techniques: Help

  1. Update-Help
    1. May also call Update-Help -Force
    2. Downloads all help information for powershell (repeat command when installing or updating Powershell)
  2. Get-Help
    1. Get-Help *process*
      1. Lists all "process" related topics (with * as wildcard) for which help is available
    2. Get-Help Start-Process
      1. Shows basic information about the Start-Process command
    3. Get-Help Start-Process -full
      1. Shows all help information including examples for Start-Process
    4. Get-Help Start-Process -Examples
      1. Shows examples for the topic
    5. Get-Help About_*
      1. Gets all of the "About" topics in powershell
    6. Get-Help Get-Process -online
      1. Opens online help in browser
  3. Get-Command
    1. Get-Command
      1. Gets all commands in powershell
    2. Get-Command -Name *DNS*
      1. Gets all commands with DNS in the name
    3. Get-Command -noun process
      1. Shows all commands that relate to process
    4. Get-Command -verb get
      1. Shows all get commands
  4. Get-Member
    1. Get-Process | Get-Member
      1. Displays all member property and method names of the Get-Process command
  5. Select-Object
    1. Get-Process -name powershell | Select-Object *
      1. Displays all member properties AND their values
  6. What-If
    1. To make a dry run before actually performing an action, follow a command with -What-if

XII. Management: Powershell Setup

  1. Reset console colors and settings
    1. Delete registry key "console" for current user
      1. Precaution: As with all registry edits, backup before hand (regedit > export, and/or set windows Restore point)
      2. Computer -> HKEY_CURRENT_USER > console
  2. Information
    1. $PSVersionTable displays a table of powershell related information
    2. $host displays the current powershell developer environment (e.g. Powershell ISE with version)
  3. Profile Scripts File
    1. Each version of powershell (console or ISE) has a profile script file that is called on start-up
    2. Placing function in the profile script file will allow use of those scripts by default
    3. $profile holds the path of the profile script file for the current powershell implementation (e.g. ISE)
      1. $profile = "~\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1"
    4. For each version of powershell there are 4 powershell scripts (current host, all hosts, current user, all users)
      1. $profile | select *
    5. Profile script file may not exist (create it to add your own scripts)
      1. if ($(Test-Path $profile) -eq false) {...}
      2. New-Item -ItemType file -path $profile -force
      3. psEdit $profile
        1. Loads the profile file path (stored in $profile) into the Powershell ISE
      4. Invoke-Item $profile
    6. Help
      1. Get-Help About_Profiles

XIII. Management: Execution Policy

  1. Get-Help about_execution_policies
  2. Get-ExecutionPolicy
    1. Restricted - Will not allow Running scripts, only single line commands (change as below)
    2. AllSigned - All Scripts (remote and local) must have code signing to run
    3. RemoteSigned - Local scripts may run without signing, but remote scripts must be signed
    4. Unrestricted - all scripts can be run regardless of origin
  3. Set-ExecutionPolicy remoteSigned
    1. Allows current user created scripts to run on the current machine
    2. Scripts created on other machines will need to be signed with a digital signature
    3. May also use attribute -Scope with scope settings below
  4. Scope settings
    1. MachinePolicy or UserPolicy
      1. Set within group policy
    2. CurrentUser or LocalMachine
      1. Valid for this user or for all users on local machine
    3. Process
      1. Setting only for current process
  5. Code Signing of a powershell script
    1. Create a self-sign certificate OR create a certificate via active directory OR purchase a certificate
    2. Self-Signed certificate (do not use in production)
      1. Create the certificate using powershell
        1. New-SelfSignedCertificate -DnsName mySite.myCompany.com -CertStoreLocation cert:\LocalMachine\My
        2. $Password = ConvertTo-SecureString -String “myPassword” -Force –AsPlainText
        3. Export-PfxCertificate -Cert cert:\LocalMachine\My\123... -FilePath C:\cert.pfx -Password $Password
        4. http://woshub.com/how-to-create-self-signed-certificate-with-powershell/
      2. Alternative: Self-sign certificate process using older process with MakeCert
        1. http://www.hanselman.com/blog/SigningPowerShellScripts.aspx
      3. Confirm certificate exists
        1. Get-ChildItem cert:\CurrentUser\My -CodeSigningCert
        2. Use CertIm.msc also displays certificates (will be in personal folder)
      4. Apply signed certificate to the script
        1. $certificates = Get-ChildItem cert:\CurrentUser\My -CodeSigningCert
        2. Set-AuthenticodeSignature myFile.ps1 @($certificates)

  6. Help and Utilities
    1. CertIm.msc
      1. Windows utility that displays all certificates
    2. Get-Command -Module PKI
      1. Displays all commands related to code signing

XIV. Management: Powershell Remote

  1. Set-up
    1. Enable-PSRemoting -Force
      1. Enable remoting on machine to receive connection
    2. Set-Item wsman:\localhost\client\trustedhosts IPAddressHost
      1. Perform Restart-Service WinRM after executing set trusted host command
      2. Where IPAddressHost is of the machines you wish to trust
        1. Alternatively, IPAddressHost may be replaced with * wildcard to trust all hosts (dangerous)
      3. Needed on home networks (but not if machines are on the same domain)
        1. Perform on both host and client machines
    3. Test-WsMan myRemoteComputerName
      1. Returns information regarding the remote if normal (otherwise, fails)
    4. Remote Server Administration Tools (RSAT)
      1. Install on client machine that will issue powershell commands
    5. Network connections must be private for Powershell Remoting to work
      1. Get-NetConnectionProfile
        1. Displays network connections
      2. Set-NetConnectionProfile -InterfaceAlias "myEthernetPublic" -NetworkCategory Private
        1. Sets the named network connection ("myEthernetPublic") to private
        2. May be changed back to public with attribute -NetworkCategory Public
  2. Remote connection options
    1. Enter-PsSession
      1. Starts interactive session in Powershell with remote computer
    2. Invoke-Command
      1. Runs commands (or scripts) on local or remote computers
      2. Invoke-command -ComputerName myOtherComputer -ScriptBlock {Get-Process}

XV. Techniques: Folder Management (Windows Explorer in Powershell)

  1. Get-Command -Module Storage | Select-Object -Property Name
    1. Displays all commands related to storage
  2. Get-PsDrive (GDr)
    1. Returns all the Powershell Drives
    2. Includes physical drives (e.g. C:\), alias, registry (HKCU, HKLM), certificates (Cert), and processes (Env)
    3. Note that changing to a root directory, requires a ':' (e.g. cd env:\)
  3. Get-Location (GL)
    1. Returns current directory location
    2. Current location is stored automatically as $pwd (without trailing \)
  4. Get-Childitem (Dir)
    1. Returns all files or items in the current directory
    2. Dir filename /S will search all subdirectories for the file
  5. Get-ChildItem myRootDir -filter "*myPattern??" -Recurse
    1. Find a file matching pattern (with wildcards) starting with myRootDir and checking subfolders
    2. Directories can be searched with attribute -Directory
  6. Set-Location (ChDir, CD)
    1. Changes to new specified directory
  7. Push-Location (PushD)
    1. Pushes a location onto a stack (as well as changing to that location)
    2. Multiple locations/directories can be pushed onto the stack
  8. Pop-Location (PopD)
    1. Returns to the prior location before the last push
    2. Allows for return to initial directory prior to Running a script
  9. Get-Item (GU)
    1. Lists the particular item in its directory
    2. Get-Item ./test.txt
  10. New-Item (NI)
    1. Create a new item (e.g. file, folder or alias)
    2. New-Item ./test.txt -type file -value "Text within the file"
    3. New-Item ./test.udp -type file -value ""
    4. New-Item alias:/clr -value "clear-host" (or New-Alias -name clr -value clear-host)
    5. New-Item -ItemType directory -Force "myDirName"
  11. Remove-Item "path/filename" or "path/wildcard"
    1. Delete a file or file(s) from a directory
  12. Copy-Item "path/myFile" "myFileDest" -force
    1. Copy a file or file(s) to a destination folder
  13. Directories
    1. Current directory: "."
    2. Windows User root or home directory (e.g. c:\Users\Username): "~/"
  14. Invoke-Item (ii)
    1. Opens an item with it's default program (e.g. "ii ./test.txt" will open in notepad)
    2. To open Windows Explorer in the current directory, type: "ii ."
  15. Test-Path myPath
    1. Returns true if file or directory exist
  16. PsEdit myFilePath
    1. Loads the file at myFilePath into the Powershell ISE editor
  17. Help
    1. Get-Help *Location
    2. Get-Help About_Providers
  18. Related DOS Commands
    1. Dir
      1. Displays contents from current directory (equivalent to get-childitem)
    2. CHDir (CD)
      1. Change directory (e.g. cd "~/")
    3. MkDir (MD)
      1. Make directory
    4. RmDir (RD)
      1. Remove directory (if adding the "/s" switch, remove directory is forced even if subfolders)
    5. Copy, XCopy, RoboCopy, and RichCopy
      1. Copy files and folders
    6. Erase (DEL)
      1. Delete files (e.g. del 'i:\bogus\*.md /f')
      2. Force switch ("/f") forces the delete
    7. Format H: /q /v: VOL
      1. Format drive specified
      2. Where /q = quick format and /v: VOL = volume label
    8. DiskPart
      1. Manage disks, partitions and volumes
    9. ChkDsk
      1. Show disk status and also corrects errors

XVI. Techniques: Task Management

  1. Stop-Process (kill process)
    1. Stop-process -processname PROCESSNAME (e.g. chrome)
  2. Related DOS commands
    1. TaskList
      1. Get Running tasks, their process ID (PID) and image name
    2. TaskKill /PID 111 /T
      1. Kills Running process with ID 111, and with switch "/T", will kill all sub-processes

XVII. Techniques: Server Configuration

  1. Rename-Computer
    1. Rename-Computer -NewName MyName
    2. Servers are often named DC1 (e.g. domain controller), Server1
  2. Set-Timezone
    1. Tzutil.exe /s "Central Standard Time"

XVIII. Techniques: Network Configuration

  1. Related DOS commands
    1. GpuUpdate /f
      1. Refreshes group policy (local and active directory) with or without force switch (/f)
    2. GpResult
      1. Displays who is logged onto system and what group policies are being applied
      2. Evaluates RSoP (Resultant Set of Policy)
  2. Computer Network connections
    1. Wireless info
      1. netsh wlan show drivers

XIX. Techniques: General Server

  1. Restart-Computer
    1. Restarts the system
  2. Stop-Computer
    1. Shuts down computer
  3. New-GUID
    1. Generates a GUID
  4. Related DOS commands
    1. Shutdown -f -r -t 60
      1. Where -f = forces, -r = restart and -t = timer
    2. BootRec
      1. Troubleshoot and repairs/recover boot record
    3. SFC /scannow
      1. Scans protected system files and confirms/validates these files

XX. Techniques: Visual Studio Package Manager

  1. Update package by reinstall
    1. Update-Package

      -reinstall

XXI. Techniques: Legacy - Objects/Classes (older method, before Powershell version 5)

  1. See the newer Class method used in Powershell 5 as above
  2. Create object - hash table method (typically preferred)
    1. $properties = [ordered] @{prop1 = 'one', prop2 = 2}
    2. $object = New-Object -TypeName PSObject -Property $properties
    3. $object.prop1 refers to property on the object
  3. Create object - adding properties later
    1. $object = New-Object -TypeName PSObject
    2. Then add property in one of two ways
      1. Add-Member -InputObject $object -memberType NoteProperty -Name Prop1 - Value "one"
      2. $object | Add-member -memberType NoteProperty -Name Prop1 - Value "one"
  4. Property aliases
    1. $object | Add-member -memberType AliasProperty -Name MyPropAlias - Value "prop1" -PassThru
      1. Both MyPropAlias and prop1 will refer to the same property on $object
  5. Adding functions to objects
    1. $myScriptBlock = { param($myParam) $result = $this.prop1 + this.prop2 + $myParam; return $result }
    2. $object | Add-member -memberType ScriptMethod -Name MyCoolScript - Value $myScriptBlock -PassThru
    3. $object.MyCoolScript("myParamValue") calls the function
  6. Getters and Setters
    1. Precaution - the original properties are public and can be directly changed, bypassing getter/setter
    2. $object | Add-member -memberType NoteProperty -Name Prop1 - Value "one"
    3. $getter = {return $this.Prop1}
    4. $setter = {param (

      $prop1); $this.MyProp = $prop1}

    5. $object | add-member -memberType ScriptProperty -Name MyProp -Value $getter -SeconValue $setter
  7. Default properties
    1. Default properties may be set

XXII. Resources

XXIII. References

  1. Bender (2016) Windows Server Admin Fundamentals Using Powershell, Pluralsight
  2. Cain (2016) Powershell Scripting for Developers, Pluralsight
  3. Christopher (2012) Everyday Powershell for Developers, Pluralsight
  4. Young (2016) Powershell for Beginners, Channel 9
    1. https://channel9.msdn.com/Blogs/MVP-Windows-and-Devices-for-IT/PowerShell-for-Beginners

Images: Related links to external sites (from Bing)

Related Studies