Author:GoalKicker.com
No description
Tags
Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
PowerShell Notes for ProfessionalsPowerShell® Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial PowerShell® group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 100+ pages of professional hints and tricks
Page
2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with PowerShell 2 .................................................................................................... Section 1.1: Allow scripts stored on your machine to run un-signed 2 ........................................................................ Section 1.2: Aliases & Similar Functions 2 ....................................................................................................................... Section 1.3: The Pipeline - Using Output from a PowerShell cmdlet 3 ........................................................................ Section 1.4: Calling .Net Library Methods 4 .................................................................................................................... Section 1.5: Installation or Setup 5 .................................................................................................................................. Section 1.6: Commenting 5 ............................................................................................................................................... Section 1.7: Creating Objects 6 ........................................................................................................................................ Chapter 2: Variables in PowerShell 7 ..................................................................................................................... Section 2.1: Simple variable 7 .......................................................................................................................................... Section 2.2: Arrays 7 ........................................................................................................................................................ Section 2.3: List Assignment of Multiple Variables 7 ..................................................................................................... Section 2.4: Scope 8 ......................................................................................................................................................... Section 2.5: Removing a variable 8 ................................................................................................................................ Chapter 3: Operators 9 .................................................................................................................................................. Section 3.1: Comparison Operators 9 ............................................................................................................................. Section 3.2: Arithmetic Operators 9 ................................................................................................................................ Section 3.3: Assignment Operators 10 ........................................................................................................................... Section 3.4: Redirection Operators 10 ............................................................................................................................ Section 3.5: Mixing operand types, the type of the left operand dictates the behavior 11 ...................................... Section 3.6: Logical Operators 11 ................................................................................................................................... Section 3.7: String Manipulation Operators 11 .............................................................................................................. Chapter 4: Special Operators 13 .............................................................................................................................. Section 4.1: Array Expression Operator 13 ..................................................................................................................... Section 4.2: Call Operation 13 ......................................................................................................................................... Section 4.3: Dot sourcing operator 13 ............................................................................................................................ Chapter 5: Basic Set Operations 14 ......................................................................................................................... Section 5.1: Filtering: Where-Object / where / ? 14 ...................................................................................................... Section 5.2: Ordering: Sort-Object / sort 14 .................................................................................................................. Section 5.3: Grouping: Group-Object / group 15 .......................................................................................................... Section 5.4: Projecting: Select-Object / select 16 .......................................................................................................... Chapter 6: Conditional logic 17 .................................................................................................................................. Section 6.1: if, else and else if 17 ..................................................................................................................................... Section 6.2: Negation 17 .................................................................................................................................................. Section 6.3: If conditional shorthand 18 ......................................................................................................................... Chapter 7: Loops 19 ......................................................................................................................................................... Section 7.1: Foreach 19 ..................................................................................................................................................... Section 7.2: For 19 ............................................................................................................................................................ Section 7.3: ForEach() Method 19 ................................................................................................................................... Section 7.4: ForEach-Object 20 ....................................................................................................................................... Section 7.5: Continue 21 ................................................................................................................................................... Section 7.6: Break 21 ........................................................................................................................................................ Section 7.7: While 22 ......................................................................................................................................................... Section 7.8: Do 22 ............................................................................................................................................................. Chapter 8: Switch statement 24 ................................................................................................................................
Page
3
Section 8.1: Simple Switch 24 ........................................................................................................................................... Section 8.2: Switch Statement with CaseSensitive Parameter 24 ............................................................................... Section 8.3: Switch Statement with Wildcard Parameter 24 ........................................................................................ Section 8.4: Switch Statement with File Parameter 25 ................................................................................................. Section 8.5: Simple Switch with Default Condition 25 ................................................................................................... Section 8.6: Switch Statement with Regex Parameter 26 ............................................................................................ Section 8.7: Simple Switch With Break 26 ...................................................................................................................... Section 8.8: Switch Statement with Exact Parameter 27 .............................................................................................. Section 8.9: Switch Statement with Expressions 27 ...................................................................................................... Chapter 9: Strings 28 ....................................................................................................................................................... Section 9.1: Multiline string 28 .......................................................................................................................................... Section 9.2: Here-string 28 .............................................................................................................................................. Section 9.3: Concatenating strings 28 ............................................................................................................................ Section 9.4: Special characters 29 .................................................................................................................................. Section 9.5: Creating a basic string 29 ........................................................................................................................... Section 9.6: Format string 30 .......................................................................................................................................... Chapter 10: HashTables 31 ........................................................................................................................................... Section 10.1: Access a hash table value by key 31 ........................................................................................................ Section 10.2: Creating a Hash Table 31 .......................................................................................................................... Section 10.3: Add a key value pair to an existing hash table 31 .................................................................................. Section 10.4: Remove a key value pair from an existing hash table 32 ..................................................................... Section 10.5: Enumerating through keys and Key-Value Pairs 32 .............................................................................. Section 10.6: Looping over a hash table 32 ................................................................................................................... Chapter 11: Working with Objects 34 ....................................................................................................................... Section 11.1: Examining an object 34 ............................................................................................................................... Section 11.2: Updating Objects 35 ................................................................................................................................... Section 11.3: Creating a new object 35 ............................................................................................................................ Section 11.4: Creating Instances of Generic Classes 37 ................................................................................................ Chapter 12: PowerShell Functions 39 ...................................................................................................................... Section 12.1: Basic Parameters 39 ................................................................................................................................... Section 12.2: Advanced Function 39 ............................................................................................................................... Section 12.3: Mandatory Parameters 41 ........................................................................................................................ Section 12.4: Parameter Validation 41 ............................................................................................................................ Section 12.5: Simple Function with No Parameters 43 .................................................................................................. Chapter 13: PowerShell Classes 44 ........................................................................................................................... Section 13.1: Listing available constructors for a class 44 ............................................................................................ Section 13.2: Methods and properties 45 ....................................................................................................................... Section 13.3: Constructor overloading 45 ....................................................................................................................... Section 13.4: Get All Members of an Instance 46 ........................................................................................................... Section 13.5: Basic Class Template 46 ............................................................................................................................ Section 13.6: Inheritance from Parent Class to Child Class 47 ..................................................................................... Chapter 14: PowerShell Modules 48 ........................................................................................................................ Section 14.1: Create a Module Manifest 48 ..................................................................................................................... Section 14.2: Simple Module Example 48 ....................................................................................................................... Section 14.3: Exporting a Variable from a Module 49 ................................................................................................... Section 14.4: Structuring PowerShell Modules 49 .......................................................................................................... Section 14.5: Location of Modules 49 .............................................................................................................................. Section 14.6: Module Member Visibility 49 ..................................................................................................................... Chapter 15: PowerShell profiles 50 ..........................................................................................................................
Page
4
Section 15.1: Create an basic profile 50 .......................................................................................................................... Chapter 16: Calculated Properties 51 ..................................................................................................................... Section 16.1: Display file size in KB - Calculated Properties 51 ..................................................................................... Chapter 17: Using existing static classes 52 ........................................................................................................ Section 17.1: Adding types 52 ........................................................................................................................................... Section 17.2: Using the .Net Math Class 52 ..................................................................................................................... Section 17.3: Creating new GUID instantly 52 ................................................................................................................ Chapter 18: Built-in variables 54 ................................................................................................................................ Section 18.1: $PSScriptRoot 54 ......................................................................................................................................... Section 18.2: $Args 54 ...................................................................................................................................................... Section 18.3: $PSItem 54 ................................................................................................................................................... Section 18.4: $? 54 ............................................................................................................................................................. Section 18.5: $error 54 ...................................................................................................................................................... Chapter 19: Automatic Variables 56 ........................................................................................................................ Section 19.1: $OFS 56 ........................................................................................................................................................ Section 19.2: $? 56 ............................................................................................................................................................. Section 19.3: $null 56 ......................................................................................................................................................... Section 19.4: $error 57 ...................................................................................................................................................... Section 19.5: $pid 57 ......................................................................................................................................................... Section 19.6: Boolean values 57 ...................................................................................................................................... Section 19.7: $_ / $PSItem 58 .......................................................................................................................................... Section 19.8: $PSVersionTable 58 ................................................................................................................................... Chapter 20: Environment Variables 59 .................................................................................................................. Section 20.1: Windows environment variables are visible as a PS drive called Env: 59 ............................................ Section 20.2: Instant call of Environment Variables with $env: 59 .............................................................................. Chapter 21: Splatting 60 ................................................................................................................................................ Section 21.1: Piping and Splatting 60 ............................................................................................................................... Section 21.2: Passing a Switch parameter using Splatting 60 ...................................................................................... Section 21.3: Splatting From Top Level Function to a Series of Inner Function 61 .................................................... Section 21.4: Splatting parameters 61 ............................................................................................................................ Chapter 22: PowerShell "Streams"; Debug, Verbose, Warning, Error, Output and Information 63 .................................................................................................................................................................... Section 22.1: Write-Output 63 .......................................................................................................................................... Section 22.2: Write Preferences 63 ................................................................................................................................. Chapter 23: Sending Email 65 ..................................................................................................................................... Section 23.1: Send-MailMessage with predefined parameters 65 ............................................................................... Section 23.2: Simple Send-MailMessage 66 ................................................................................................................... Section 23.3: SMTPClient - Mail with .txt file in body message 66 ............................................................................... Chapter 24: PowerShell Remoting 67 .................................................................................................................... Section 24.1: Connecting to a Remote Server via PowerShell 67 ................................................................................ Section 24.2: Run commands on a Remote Computer 67 ........................................................................................... Section 24.3: Enabling PowerShell Remoting 69 ........................................................................................................... Section 24.4: A best practise for automatically cleaning-up PSSessions 70 .............................................................. Chapter 25: Working with the PowerShell pipeline 71 ................................................................................... Section 25.1: Writing Functions with Advanced Lifecycle 71 ........................................................................................ Section 25.2: Basic Pipeline Support in Functions 71 .................................................................................................... Section 25.3: Working concept of pipeline 72 ............................................................................................................... Chapter 26: PowerShell Background Jobs 73 ....................................................................................................
Page
5
Section 26.1: Basic job creation 73 .................................................................................................................................. Section 26.2: Basic job management 73 ........................................................................................................................ Chapter 27: Return behavior in PowerShell 75 .................................................................................................. Section 27.1: Early exit 75 ................................................................................................................................................. Section 27.2: Gotcha! Return in the pipeline 75 ............................................................................................................. Section 27.3: Return with a value 75 ............................................................................................................................... Section 27.4: How to work with functions returns 75 .................................................................................................... Section 27.5: Gotcha! Ignoring unwanted output 77 ..................................................................................................... Chapter 28: CSV parsing 78 ......................................................................................................................................... Section 28.1: Basic usage of Import-Csv 78 ................................................................................................................... Section 28.2: Import from CSV and cast properties to correct type 78 ..................................................................... Chapter 29: Working with XML Files 80 .................................................................................................................. Section 29.1: Accessing an XML File 80 ........................................................................................................................... Section 29.2: Creating an XML Document using XmlWriter() 81 ................................................................................. Section 29.3: Adding snippets of XML to current XMLDocument 82 ........................................................................... Chapter 30: Communicating with RESTful APIs 88 ........................................................................................... Section 30.1: Post Message to hipChat 88 ...................................................................................................................... Section 30.2: Using REST with PowerShell Objects to GET and POST many items 88 .............................................. Section 30.3: Use Slack.com Incoming Webhooks 88 .................................................................................................. Section 30.4: Using REST with PowerShell Objects to Get and Put individual data 89 ............................................. Section 30.5: Using REST with PowerShell to Delete items 89 ..................................................................................... Chapter 31: PowerShell SQL queries 90 ................................................................................................................. Section 31.1: SQLExample 90 ............................................................................................................................................ Section 31.2: SQLQuery 90 ............................................................................................................................................... Chapter 32: Regular Expressions 91 ........................................................................................................................ Section 32.1: Single match 91 .......................................................................................................................................... Section 32.2: Replace 93 .................................................................................................................................................. Section 32.3: Replace text with dynamic value using a MatchEvalutor 93 ................................................................ Section 32.4: Escape special characters 94 ................................................................................................................... Section 32.5: Multiple matches 94 ................................................................................................................................... Chapter 33: Aliases 97 ..................................................................................................................................................... Section 33.1: Get-Alias 97 ................................................................................................................................................. Section 33.2: Set-Alias 97 ................................................................................................................................................. Chapter 34: Using the progress bar 98 ................................................................................................................. Section 34.1: Simple use of progress bar 98 .................................................................................................................. Section 34.2: Usage of inner progress bar 98 ............................................................................................................... Chapter 35: PowerShell.exe Command-Line 100 ............................................................................................... Section 35.1: Executing a command 100 ........................................................................................................................ Section 35.2: Executing a script file 101 ......................................................................................................................... Chapter 36: Cmdlet Naming 102 ................................................................................................................................ Section 36.1: Verbs 102 ..................................................................................................................................................... Section 36.2: Nouns 102 ................................................................................................................................................... Chapter 37: Running Executables 103 .................................................................................................................... Section 37.1: GUI Applications 103 .................................................................................................................................. Section 37.2: Console Streams 103 ................................................................................................................................. Section 37.3: Exit Codes 103 ............................................................................................................................................ Chapter 38: Enforcing script prerequisites 104 ................................................................................................. Section 38.1: Enforce minimum version of PowerShell host 104 ..................................................................................
Page
6
Section 38.2: Enforce running the script as administrator 104 .................................................................................... Chapter 39: Using the Help System 105 ................................................................................................................. Section 39.1: Updating the Help System 105 ................................................................................................................. Section 39.2: Using Get-Help 105 .................................................................................................................................... Section 39.3: Viewing online version of a help topic 105 .............................................................................................. Section 39.4: Viewing Examples 105 ............................................................................................................................... Section 39.5: Viewing the Full Help Page 106 ................................................................................................................ Section 39.6: Viewing help for a specific parameter 106 ............................................................................................. Chapter 40: Modules, Scripts and Functions 107 ............................................................................................. Section 40.1: Function 107 ............................................................................................................................................... Section 40.2: Script 107 .................................................................................................................................................... Section 40.3: Module 108 ................................................................................................................................................. Section 40.4: Advanced Functions 109 .......................................................................................................................... Chapter 41: Naming Conventions 112 ..................................................................................................................... Section 41.1: Functions 112 ............................................................................................................................................... Chapter 42: Common parameters 113 .................................................................................................................. Section 42.1: ErrorAction parameter 113 ....................................................................................................................... Chapter 43: Parameter sets 115 ............................................................................................................................... Section 43.1: Parameter set to enforce the use of a parameter when a other is selected 115 ............................... Section 43.2: Parameter set to limit the combination of parameters 115 ................................................................. Chapter 44: PowerShell Dynamic Parameters 116 ......................................................................................... Section 44.1: "Simple" dynamic parameter 116 ............................................................................................................ Chapter 45: GUI in PowerShell 118 ........................................................................................................................... Section 45.1: WPF GUI for Get-Service cmdlet 118 ....................................................................................................... Chapter 46: URL Encode/Decode 120 .................................................................................................................... Section 46.1: Encode Query String with `[System.Web.HttpUtility]::UrlEncode()` 120 ............................................... Section 46.2: Quick Start: Encoding 120 ......................................................................................................................... Section 46.3: Quick Start: Decoding 120 ........................................................................................................................ Section 46.4: Encode Query String with `[uri]::EscapeDataString()` 121 .................................................................... Section 46.5: Decode URL with `[uri]::UnescapeDataString()` 121 .............................................................................. Section 46.6: Decode URL with `[System.Web.HttpUtility]::UrlDecode()` 123 ............................................................ Chapter 47: Error handling 126 ................................................................................................................................. Section 47.1: Error Types 126 .......................................................................................................................................... Chapter 48: Package management 128 ............................................................................................................... Section 48.1: Create the default PowerShell Module Repository 128 .......................................................................... Section 48.2: Find a module by name 128 .................................................................................................................... Section 48.3: Install a Module by name 128 .................................................................................................................. Section 48.4: Uninstall a module my name and version 128 ....................................................................................... Section 48.5: Update a module by name 128 ............................................................................................................... Section 48.6: Find a PowerShell module using a pattern 128 ...................................................................................... Chapter 49: TCP Communication with PowerShell 129 .................................................................................. Section 49.1: TCP listener 129 .......................................................................................................................................... Section 49.2: TCP Sender 129 ......................................................................................................................................... Chapter 50: PowerShell Workflows 131 ................................................................................................................. Section 50.1: Workflow with Input Parameters 131 ....................................................................................................... Section 50.2: Simple Workflow Example 131 ................................................................................................................ Section 50.3: Run Workflow as a Background Job 131 ............................................................................................... Section 50.4: Add a Parallel Block to a Workflow 131 .................................................................................................
Page
7
Chapter 51: Embedding Managed Code (C# | VB) 133 .................................................................................... Section 51.1: C# Example 133 ........................................................................................................................................... Section 51.2: VB.NET Example 133 .................................................................................................................................. Chapter 52: How to download latest artifact from Artifactory using PowerShell script (v2.0 or below)? 135 ......................................................................................................................................................... Section 52.1: PowerShell Script for downloading the latest artifact 135 .................................................................... Chapter 53: Comment-based help 136 ................................................................................................................... Section 53.1: Function comment-based help 136 .......................................................................................................... Section 53.2: Script comment-based help 138 .............................................................................................................. Chapter 54: Archive Module 141 ............................................................................................................................... Section 54.1: Compress-Archive with wildcard 141 ....................................................................................................... Section 54.2: Update existing ZIP with Compress-Archive 141 ................................................................................... Section 54.3: Extract a Zip with Expand-Archive 141 .................................................................................................... Chapter 55: Infrastructure Automation 142 ........................................................................................................ Section 55.1: Simple script for black-box integration test of console applications 142 ............................................ Chapter 56: PSScriptAnalyzer - PowerShell Script Analyzer 143 .............................................................. Section 56.1: Analyzing scripts with the built-in preset rulesets 143 ........................................................................... Section 56.2: Analyzing scripts against every built-in rule 143 ................................................................................... Section 56.3: List all built-in rules 143 ............................................................................................................................. Chapter 57: Desired State Configuration 145 .................................................................................................... Section 57.1: Simple example - Enabling WindowsFeature 145 ................................................................................... Section 57.2: Starting DSC (mof) on remote machine 145 .......................................................................................... Section 57.3: Importing psd1 (data file) into local variable 145 ................................................................................... Section 57.4: List available DSC Resources 145 ............................................................................................................ Section 57.5: Importing resources for use in DSC 146 .................................................................................................. Chapter 58: Using ShouldProcess 147 .................................................................................................................... Section 58.1: Full Usage Example 147 ............................................................................................................................ Section 58.2: Adding -WhatIf and -Confirm support to your cmdlet 148 .................................................................. Section 58.3: Using ShouldProcess() with one argument 148 ..................................................................................... Chapter 59: Scheduled tasks module 149 ............................................................................................................ Section 59.1: Run PowerShell Script in Scheduled Task 149 ......................................................................................... Chapter 60: ISE module 150 ......................................................................................................................................... Section 60.1: Test Scripts 150 .......................................................................................................................................... Chapter 61: Creating DSC Class-Based Resources 151 .................................................................................. Section 61.1: Create a DSC Resource Skeleton Class 151 ............................................................................................. Section 61.2: DSC Resource Skeleton with Key Property 151 ...................................................................................... Section 61.3: DSC Resource with Mandatory Property 151 .......................................................................................... Section 61.4: DSC Resource with Required Methods 152 ............................................................................................. Chapter 62: WMI and CIM 153 ...................................................................................................................................... Section 62.1: Querying objects 153 ................................................................................................................................. Section 62.2: Classes and namespaces 155 .................................................................................................................. Chapter 63: ActiveDirectory module 158 .............................................................................................................. Section 63.1: Users 158 ..................................................................................................................................................... Section 63.2: Module 158 ................................................................................................................................................. Section 63.3: Groups 158 .................................................................................................................................................. Section 63.4: Computers 159 ........................................................................................................................................... Section 63.5: Objects 159 ................................................................................................................................................. Chapter 64: SharePoint Module 160 ........................................................................................................................
Page
8
Section 64.1: Loading SharePoint Snap-In 160 .............................................................................................................. Section 64.2: Iterating over all lists of a site collection 160 ......................................................................................... Section 64.3: Get all installed features on a site collection 160 ................................................................................... Chapter 65: Introduction to Psake 161 .................................................................................................................. Section 65.1: Basic outline 161 ......................................................................................................................................... Section 65.2: FormatTaskName example 161 .............................................................................................................. Section 65.3: Run Task conditionally 161 ....................................................................................................................... Section 65.4: ContinueOnError 162 ................................................................................................................................. Chapter 66: Introduction to Pester 163 .................................................................................................................. Section 66.1: Getting Started with Pester 163 ................................................................................................................ Chapter 67: Handling Secrets and Credentials 164 ......................................................................................... Section 67.1: Accessing the Plaintext Password 164 ..................................................................................................... Section 67.2: Prompting for Credentials 164 ................................................................................................................. Section 67.3: Working with Stored Credentials 164 ...................................................................................................... Section 67.4: Storing the credentials in Encrypted form and Passing it as parameter when Required 165 ............................................................................................................................................................................. Chapter 68: Security and Cryptography 166 ...................................................................................................... Section 68.1: Calculating a string's hash codes via .Net Cryptography 166 ............................................................... Chapter 69: Signing Scripts 167 ................................................................................................................................. Section 69.1: Signing a script 167 .................................................................................................................................... Section 69.2: Bypassing execution policy for a single script 167 ................................................................................ Section 69.3: Changing the execution policy using Set-ExecutionPolicy 168 ............................................................. Section 69.4: Get the current execution policy 168 ....................................................................................................... Section 69.5: Getting the signature from a signed script 168 ...................................................................................... Section 69.6: Creating a self-signed code signing certificate for testing 168 ............................................................ Chapter 70: Anonymize IP (v4 and v6) in text file with PowerShell 170 ................................................ Section 70.1: Anonymize IP address in text file 170 ....................................................................................................... Chapter 71: Amazon Web Services (AWS) Rekognition 171 ......................................................................... Section 71.1: Detect Image Labels with AWS Rekognition 171 ..................................................................................... Section 71.2: Compare Facial Similarity with AWS Rekognition 171 ........................................................................... Chapter 72: Amazon Web Services (AWS) Simple Storage Service (S3) 173 ...................................... Section 72.1: Create a new S3 Bucket 173 ...................................................................................................................... Section 72.2: Upload a Local File Into an S3 Bucket 173 ............................................................................................. Section 72.3: Delete a S3 Bucket 173 ............................................................................................................................. Credits 174 ............................................................................................................................................................................ You may also like 176 ......................................................................................................................................................
Page
9
GoalKicker.com – PowerShell® Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/PowerShellBook This PowerShell® Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official PowerShell® group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
Page
10
GoalKicker.com – PowerShell® Notes for Professionals 2 Chapter 1: Getting started with PowerShell Version Included with Windows Notes Release Date 1.0 XP / Server 2008 2006-11-01 2.0 7 / Server 2008 R2 2009-11-01 3.0 8 / Server 2012 2012-08-01 4.0 8.1 / Server 2012 R2 2013-11-01 5.0 10 / Server 2016 Tech Preview 2015-12-16 5.1 10 Anniversary edition / Server 2016 2017-01-27 Section 1.1: Allow scripts stored on your machine to run un- signed For security reasons, PowerShell is set up by default to only allow signed scripts to execute. Executing the following command will allow you to run unsigned scripts (you must run PowerShell as Administrator to do this). Set-ExecutionPolicy RemoteSigned Another way to run PowerShell scripts is to use Bypass as ExecutionPolicy: powershell.exe -ExecutionPolicy Bypass -File "c:\MyScript.ps1" Or from within your existing PowerShell console or ISE session by running: Set-ExecutionPolicy Bypass Process A temporary workaround for execution policy can also be achieved by running the PowerShell executable and passing any valid policy as -ExecutionPolicy parameter. The policy is in effect only during process' lifetime, so no administrative access to the registry is needed. C:\>powershell -ExecutionPolicy RemoteSigned There are multiple other policies available, and sites online often encourage you to use Set-ExecutionPolicy Unrestricted. This policy stays in place until changed, and lowers the system security stance. This is not advisable. Use of RemoteSigned is recommended because it allows locally stored and written code, and requires remotely acquired code be signed with a certificate from a trusted root. Also, beware that the Execution Policy may be enforced by Group Policy, so that even if the policy is changed to Unrestricted system-wide, Group Policy may revert that setting at its next enforcement interval (typically 15 minutes). You can see the execution policy set at the various scopes using Get-ExecutionPolicy -List TechNet Documentation: Set-ExecutionPolicy about_Execution_Policies Section 1.2: Aliases & Similar Functions In PowerShell, there are many ways to achieve the same result. This can be illustrated nicely with the simple & familiar Hello World example: Using Write-Host:
Page
11
GoalKicker.com – PowerShell® Notes for Professionals 3 Write-Host "Hello World" Using Write-Output: Write-Output 'Hello world' It's worth noting that although Write-Output & Write-Host both write to the screen there is a subtle difference. Write-Host writes only to stdout (i.e. the console screen), whereas Write-Output writes to both stdout AND to the output [success] stream allowing for redirection. Redirection (and streams in general) allow for the output of one command to be directed as input to another including assignment to a variable. > $message = Write-Output "Hello World" > $message "Hello World" These similar functions are not aliases, but can produce the same results if one wants to avoid "polluting" the success stream. Write-Output is aliased to Echo or Write Echo 'Hello world' Write 'Hello world' Or, by simply typing 'Hello world'! 'Hello world' All of which will result with the expected console output Hello world Another example of aliases in PowerShell is the common mapping of both older command prompt commands and BASH commands to PowerShell cmdlets. All of the following produce a directory listing of the current directory. C:\Windows> dir C:\Windows> ls C:\Windows> Get-ChildItem Finally, you can create your own alias with the Set-Alias cmdlet! As an example let's alisas Test-NetConnection, which is essentially the PowerShell equivalent to the command prompt's ping command, to "ping". Set-Alias -Name ping -Value Test-NetConnection Now you can use ping instead of Test-NetConnection! Be aware that if the alias is already in use, you'll overwrite the association. The Alias will be alive, till the session is active. Once you close the session and try to run the alias which you have created in your last session, it will not work. To overcome this issue, you can import all your aliases from an excel into your session once, before starting your work. Section 1.3: The Pipeline - Using Output from a PowerShell
Page
12
GoalKicker.com – PowerShell® Notes for Professionals 4 cmdlet One of the first questions people have when they begin to use PowerShell for scripting is how to manipulate the output from a cmdlet to perform another action. The pipeline symbol | is used at the end of a cmdlet to take the data it exports and feed it to the next cmdlet. A simple example is using Select-Object to only show the Name property of a file shown from Get-ChildItem: Get-ChildItem | Select-Object Name #This may be shortened to: gci | Select Name More advanced usage of the pipeline allows us to pipe the output of a cmdlet into a foreach loop: Get-ChildItem | ForEach-Object { Copy-Item -Path $_.FullName -destination C:\NewDirectory\ } #This may be shortened to: gci | % { Copy $_.FullName C:\NewDirectory\ } Note that the example above uses the $_ automatic variable. $_ is the short alias of $PSItem which is an automatic variable which contains the current item in the pipeline. Section 1.4: Calling .Net Library Methods Static .Net library methods can be called from PowerShell by encapsulating the full class name in third bracket and then calling the method using :: #calling Path.GetFileName() C:\> [System.IO.Path]::GetFileName('C:\Windows\explorer.exe') explorer.exe Static methods can be called from the class itself, but calling non-static methods requires an instance of the .Net class (an object). For example, the AddHours method cannot be called from the System.DateTime class itself. It requires an instance of the class: C:\> [System.DateTime]::AddHours(15) Method invocation failed because [System.DateTime] does not contain a method named 'AddHours'. At line:1 char:1 + [System.DateTime]::AddHours(15) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound In this case, we first create an object, for example: C:\> $Object = [System.DateTime]::Now Then, we can use methods of that object, even methods which cannot be called directly from the System.DateTime class, like the AddHours method: C:\> $Object.AddHours(15)
Page
13
GoalKicker.com – PowerShell® Notes for Professionals 5 Monday 12 September 2016 01:51:19 Section 1.5: Installation or Setup Windows PowerShell is included with the Windows Management Framework. Installation and Setup are not required on modern versions of Windows. Updates to PowerShell can be accomplished by installing a newer version of the Windows Management Framework. Other Platforms PowerShell 6 can be installed on other platforms. The installation packages are available here. For example, PowerShell 6, for Ubuntu 16.04, is published to package repositories for easy installation (and updates). To install run the following: # Import the public repository GPG keys curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - # Register the Microsoft Ubuntu repository curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | sudo tee /etc/apt/sources.list.d/microsoft.list # Update apt-get sudo apt-get update # Install PowerShell sudo apt-get install -y powershell # Start PowerShell powershell After registering the Microsoft repository once as superuser, from then on, you just need to use sudo apt-get upgrade powershell to update it. Then just run powershell Section 1.6: Commenting To comment on power scripts by prepending the line using the # (hash) symbol # This is a comment in PowerShell Get-ChildItem You can also have multi-line comments using <# and #> at the beginning and end of the comment respectively. <# This is a multi-line comment #> Get-ChildItem
Page
14
GoalKicker.com – PowerShell® Notes for Professionals 6 Section 1.7: Creating Objects The New-Object cmdlet is used to create an object. # Create a DateTime object and stores the object in variable "$var" $var = New-Object System.DateTime # calling constructor with parameters $sr = New-Object System.IO.StreamReader -ArgumentList "file path" In many instances, a new object will be created in order to export data or pass it to another commandlet. This can be done like so: $newObject = New-Object -TypeName PSObject -Property @{ ComputerName = "SERVER1" Role = "Interface" Environment = "Production" } There are many ways of creating an object. The following method is probably the shortest and fastest way to create a PSCustomObject: $newObject = [PSCustomObject]@{ ComputerName = 'SERVER1' Role = 'Interface' Environment = 'Production' } In case you already have an object, but you only need one or two extra properties, you can simply add that property by using Select-Object: Get-ChildItem | Select-Object FullName, Name, @{Name='DateTime'; Expression={Get-Date}}, @{Name='PropertyName'; Expression={'CustomValue'}} All objects can be stored in variables or passed into the pipeline. You could also add these objects to a collection and then show the results at the end. Collections of objects work well with Export-CSV (and Import-CSV). Each line of the CSV is an object, each column a property. Format commands convert objects into text stream for display. Avoid using Format-* commands until the final step of any data processing, to maintain the usability of the objects.
Page
15
GoalKicker.com – PowerShell® Notes for Professionals 7 Chapter 2: Variables in PowerShell Variables are used for storing values. Let the value be of any type , we need to store it somewhere so that we can use it throughout the console/script. Variable names in PowerShell begin with a $, as in $Variable1, and values are assigned using =, like $Variable1 = "Value 1".PowerShell supports a huge number of variable types; such as text strings, integers, decimals, arrays, and even advanced types like version numbers or IP addresses. Section 2.1: Simple variable All variables in PowerShell begin with a US dollar sign ($). The simplest example of this is: $foo = "bar" This statement allocates a variable called foo with a string value of "bar". Section 2.2: Arrays Array declaration in Powershell is almost the same as instantiating any other variable, i.e. you use a $name = syntax. The items in the array are declared by separating them by commas(,): $myArrayOfInts = 1,2,3,4 $myArrayOfStrings = "1","2","3","4" Adding to an array Adding to an array is as simple as using the + operator: $myArrayOfInts = $myArrayOfInts + 5 # now contains 1,2,3,4 & 5! Combining arrays together Again this is as simple as using the + operator $myArrayOfInts = 1,2,3,4 $myOtherArrayOfInts = 5,6,7 $myArrayOfInts = $myArrayOfInts + $myOtherArrayOfInts # now 1,2,3,4,5,6,7 Section 2.3: List Assignment of Multiple Variables Powershell allows multiple assignment of variables and treats almost everything like an array or list. This means that instead of doing something like this: $input = "foo.bar.baz" $parts = $input.Split(".") $foo = $parts[0] $bar = $parts[1] $baz = $parts[2] You can simply do this: $foo, $bar, $baz = $input.Split(".")
Page
16
GoalKicker.com – PowerShell® Notes for Professionals 8 Since Powershell treats assignments in this manner like lists, if there are more values in the list than items in your list of variables to assign them to, the last variable becomes an array of the remaining values. This means you can also do things like this: $foo, $leftover = $input.Split(".") #Sets $foo = "foo", $leftover = ["bar","baz"] $bar = $leftover[0] # $bar = "bar" $baz = $leftover[1] # $baz = "baz" Section 2.4: Scope The default scope for a variable is the enclosing container. If outside a script, or other container then the scope is Global. To specify a scope, it is prefixed to the variable name $scope:varname like so: $foo = "Global Scope" function myFunc { $foo = "Function (local) scope" Write-Host $global:foo Write-Host $local:foo Write-Host $foo } myFunc Write-Host $local:foo Write-Host $foo Output: Global Scope Function (local) scope Function (local) scope Global Scope Global Scope Section 2.5: Removing a variable To remove a variable from memory, one can use the Remove-Item cmdlet. Note: The variable name does NOT include the $. Remove-Item Variable:\foo Variable has a provider to allow most *-item cmdlets to work much like file systems. Another method to remove variable is to use Remove-Variable cmdlet and its alias rv $var = "Some Variable" #Define variable 'var' containing the string 'Some Variable' $var #For test and show string 'Some Variable' on the console Remove-Variable -Name var $var #also can use alias 'rv' rv var
Page
17
GoalKicker.com – PowerShell® Notes for Professionals 9 Chapter 3: Operators An operator is a character that represents an action. It tells the compiler/interpreter to perform specific mathematical, relational or logical operation and produce final result. PowerShell interprets in a specific way and categorizes accordingly like arithmetic operators perform operations primarily on numbers, but they also affect strings and other data types. Along with the basic operators, PowerShell has a number of operators that save time and coding effort (eg: -like, -match, -replace, etc). Section 3.1: Comparison Operators PowerShell comparison operators are comprised of a leading dash (-) followed by a name (eq for equal, gt for greater than, etc...). Names can be preceded by special characters to modify the behavior of the operator: i # Case-Insensitive Explicit (-ieq) c # Case-Sensitive Explicit (-ceq) Case-Insensitive is the default if not specified, ("a" -eq "A") same as ("a" -ieq "A"). Simple comparison operators: 2 -eq 2 # Equal to (==) 2 -ne 4 # Not equal to (!=) 5 -gt 2 # Greater-than (>) 5 -ge 5 # Greater-than or equal to (>=) 5 -lt 10 # Less-than (<) 5 -le 5 # Less-than or equal to (<=) String comparison operators: "MyString" -like "*String" # Match using the wildcard character (*) "MyString" -notlike "Other*" # Does not match using the wildcard character (*) "MyString" -match '^String$' # Matches a string using regular expressions "MyString" -notmatch '^Other$' # Does not match a string using regular expressions Collection comparison operators: "abc", "def" -contains "def" # Returns true when the value (right) is present # in the array (left) "abc", "def" -notcontains "123" # Returns true when the value (right) is not present # in the array (left) "def" -in "abc", "def" # Returns true when the value (left) is present # in the array (right) "123" -notin "abc", "def" # Returns true when the value (left) is not present # in the array (right) Section 3.2: Arithmetic Operators 1 + 2 # Addition 1 - 2 # Subtraction -1 # Set negative value 1 * 2 # Multiplication 1 / 2 # Division 1 % 2 # Modulus
Page
18
GoalKicker.com – PowerShell® Notes for Professionals 10 100 -shl 2 # Bitwise Shift-left 100 -shr 1 # Bitwise Shift-right Section 3.3: Assignment Operators Simple arithmetic: $var = 1 # Assignment. Sets the value of a variable to the specified value $var += 2 # Addition. Increases the value of a variable by the specified value $var -= 1 # Subtraction. Decreases the value of a variable by the specified value $var *= 2 # Multiplication. Multiplies the value of a variable by the specified value $var /= 2 # Division. Divides the value of a variable by the specified value $var %= 2 # Modulus. Divides the value of a variable by the specified value and then # assigns the remainder (modulus) to the variable Increment and decrement: $var++ # Increases the value of a variable, assignable property, or array element by 1 $var-- # Decreases the value of a variable, assignable property, or array element by 1 Section 3.4: Redirection Operators Success output stream: cmdlet > file # Send success output to file, overwriting existing content cmdlet >> file # Send success output to file, appending to existing content cmdlet 1>&2 # Send success and error output to error stream Error output stream: cmdlet 2> file # Send error output to file, overwriting existing content cmdlet 2>> file # Send error output to file, appending to existing content cmdlet 2>&1 # Send success and error output to success output stream Warning output stream: (PowerShell 3.0+) cmdlet 3> file # Send warning output to file, overwriting existing content cmdlet 3>> file # Send warning output to file, appending to existing content cmdlet 3>&1 # Send success and warning output to success output stream Verbose output stream: (PowerShell 3.0+) cmdlet 4> file # Send verbose output to file, overwriting existing content cmdlet 4>> file # Send verbose output to file, appending to existing content cmdlet 4>&1 # Send success and verbose output to success output stream Debug output stream: (PowerShell 3.0+) cmdlet 5> file # Send debug output to file, overwriting existing content cmdlet 5>> file # Send debug output to file, appending to existing content cmdlet 5>&1 # Send success and debug output to success output stream Information output stream: (PowerShell 5.0+) cmdlet 6> file # Send information output to file, overwriting existing content cmdlet 6>> file # Send information output to file, appending to existing content
Page
19
GoalKicker.com – PowerShell® Notes for Professionals 11 cmdlet 6>&1 # Send success and information output to success output stream All output streams: cmdlet *> file # Send all output streams to file, overwriting existing content cmdlet *>> file # Send all output streams to file, appending to existing content cmdlet *>&1 # Send all output streams to success output stream Differences to the pipe operator (|) Redirection operators only redirect streams to files or streams to streams. The pipe operator pumps an object down the pipeline to a cmdlet or the output. How the pipeline works differs in general from how redirection works and can be read on Working with the PowerShell pipeline Section 3.5: Mixing operand types, the type of the left operand dictates the behavior For Addition "4" + 2 # Gives "42" 4 + "2" # Gives 6 1,2,3 + "Hello" # Gives 1,2,3,"Hello" "Hello" + 1,2,3 # Gives "Hello1 2 3" For Multiplication "3" * 2 # Gives "33" 2 * "3" # Gives 6 1,2,3 * 2 # Gives 1,2,3,1,2,3 2 * 1,2,3 # Gives an error op_Multiply is missing The impact may have hidden consequences on comparison operators: $a = Read-Host "Enter a number" Enter a number : 33 $a -gt 5 False Section 3.6: Logical Operators -and # Logical and -or # Logical or -xor # Logical exclusive or -not # Logical not ! # Logical not Section 3.7: String Manipulation Operators Replace operator: The -replace operator replaces a pattern in an input value using a regular expression. This operator uses two arguments (separated by a comma): a regular expression pattern and its replacement value (which is optional and an empty string by default). "The rain in Seattle" -replace 'rain','hail' #Returns: The hail in Seattle
Page
20
GoalKicker.com – PowerShell® Notes for Professionals 12 "kenmyer@contoso.com" -replace '^[\w]+@(.+)', '$1' #Returns: contoso.com Split and Join operators: The -split operator splits a string into an array of sub-strings. "A B C" -split " " #Returns an array string collection object containing A,B and C. The -join operator joins an array of strings into a single string. "E","F","G" -join ":" #Returns a single string: E:F:G
The above is a preview of the first 20 pages. Register to read the complete e-book.
Comments 0
Loading comments...
Reply to Comment
Edit Comment