<<

PowerShell 7.0 - Quick Reference www.practicalpowershell.com V 0.1 https://devblogs.microsoft.com/powershell/announcing-PowerShell-7-0/ Get-Help / Helpful Commands Operators Comparison Operators Update-Help Updates local help files. [] Cast operator. Converts or limits object to type. -eq equal -ne not equal Get-Help Provides information on a command, it’s [DateTime]Today = ‘2/5/1999’ -lt less than -gt greater than [Int32]$Counter = 59 parameters and available switches. -ge greater than or equal -le less than or equal Get-Command Lists all commands. Can be filtered. -replace Replace string pattern , Comma operator, creates an array. Get-Module Lists modules that are or can be loaded. -like Returns true when string matches Get-Package Lists packages that are or can be loaded. -notlike Returns true when string does not match $ThisArray = 1, 2, 5 Get-PSRepository Lists available PowerShell Repositories -match Returns true when string matches regex registered to the current user. -notmatch Returns true when string does not match regex . Dot sourcing operator runs a script in the current Get-Member Gets properties and methods of objects. -contains Returns true when reference value in a collection scope. -notcontains Returns true when reference value not in a collection Get-PackageProviders Lists all loaded package provides. . C:\Scripts\QA\GetAll.ps1 -in Returns true when test value contained in a collection (i.e. NuGet, PowerShellGet, etc.) -notin Returns true when test value not contained in a collection Show-Command List of available commands (GUI) | Pipeline operator. Sends output (‘pipes’) to another cmdlet for processing. Logical Operators Operators Get-Mailbox | Set-Mailbox -RetentionPolicy ‘CorpReten’ -and TRUE when both are TRUE New Operators e.g. ‘(3 -eq 3) -and (1 -lt 3)’ is TRUE ? : Ternary operator -or TRUE when either is TRUE .. Range Operator $Path = ‘C:\Scripts’ e.g. (3 -lt 3) -or (2 -eq 2) is TRUE 20..33 # Lists numbers 20 through 33, incremented by 1's (Test-Path $path) ? "Path exists" : "Path not found" -xor TRUE when only one is TRUE # Result is ‘Path exists’ if the c:\scripts path is present e.g. (1 -eq 1) -xor (2 -eq 2) Redirection Operators || , && Pipeline chain operators FALSE >,>>,&> Sends the output of a stream to a file as well as #If process named ‘Chrome’ is found (left)/stop it (right) -not/! When a condition is not TRUE output of a particular type. Get-Process Chrome && Stop-Process -Name Chrome e.g. -not (1 -eq 1) is FALSE # If the npm install fails, removenode_modules dir. Other Operators Output Streams * All Output npm install || Remove-Item -Recurse ./node_modules -split Splits a string Null coalescing operators ‘FirstName.LastName’ -Split ‘.’ 1 Success $x = $null $x = $null # Results - ‘FirstName’ and ‘LastName’ 2 Error $x ?? 476 $x ??= 456 -join Join’s multiple strings 3 Warning # Result 476 $x ‘John’,‘Smith’,‘IT’,‘Chicago’ -Join ‘,’ 4 Verbose infor # Result 476, $x is assigned this value # Results - John,Smith,IT,Chicago 5 Debug messages Assignment Operators -replace Replaces a value 6 Information = Equal += Increments Value ‘Dog.runs.down.street’ -Replace ( ‘.’ , ‘ ’) -= Decrements value *= Multiplies value # Results – ‘Dog runs down street Redirection Operator examples: /= Divides value %= Divide and assigns remainder Type Operators # Writes warning output to warning.txt ++ Increment value (+1) -- Decrement Value (-1) -is,-isnot Used to validate a .Net Type (Get-Date) -is [DateTime] #Returns True Get-Mailbox 3> warning.txt BitWise Operators (Get-Date) -is [Int32] #Returns False ** Only works with integers and works in binary form -as Converts input to .Net Type # Appends verbose.txt with the verbose output -band Bitwise AND ‘4/1/2020’ -as [DateTime ] Set- 4>> verbose.txt -bor Bitwise OR (inclusive) #Returns Wednesday, April 1, 2020 12:00:00 AM -bxor Bitwise OR (exclusive) -f Format output of string objects # Writes debug output to the output stream -bnot Bitwise NOT “{1} {0} {4}” -f ‘runs’ , ‘dog’ , ‘fast’ , ‘yellow’ , ‘slow’ Remove-AzVM 5>&1 -shl Bit shift left # Result - ‘Dog runs slow’ -shr Bit shift right ** https://codesteps.com/2019/03/28/powershell-bitwise-logical- https://docs.microsoft.com/en-us/powershell/module/ # Redirects output to ADDCs.txt file operators/ microsoft.powershell.core/about/about_operators Get-ADDomainContrller > ADDCs.txt PowerShell 7.0 - Quick Reference www.practicalpowershell.com V 0.1

Automatic Variables (not exhaustive) Preference Variables $ConfirmPreference Determines whether PowerShell Variables that store state information, created/maintained by $PSItem, $_. Contains the current object in the pipeline automatically prompts you for PowerShell and should be treated as Read-Only. object. confirmation before running a $PSScriptRoot Directory from which a script is being run. cmdlet or function. $$ Last token in the last line received by the $PSSenderInfo Contains the directory from which a script is $DebugPreference Determines how PowerShell session being run. responds to debugging. $? Contains the execution status of the last $PSUICulture Name of the (UI) culture for OS. $ErrorActionPreference Determines how PowerShell command. $PSVersionTable Read-only hash table that displays details about responds to a non-terminating error. $^ Contains the first token in the last line received the version of PowerShell that is running in the $ErrorView Determines the display format of by the session. current session. error messages in PowerShell. $_,$PSItem Current object in the pipeline object. $PWD Path Object - full path of the current directory. $FormatEnumerationLimit Determines how many enumerated $args Contains an array of values for undeclared $ShellID Identifier of the current shell. items are included in a display. parameters that are passed to a function, script, $StackTrace Stack trace for the most recent error. $InformationPreference Lets you set information stream or script block. $Switch Contains the enumerator not the resulting preferences that you want displayed $ConsoleFileName Contains the path of the console file (.psc1) values of a Switch statement. to users. that was most recently used in the session. $MaximumHistoryCount Determines how many commands $Error Array of errors from previous commands. Variables are saved in the command history $ExecutionContext Contains an EngineIntrinsics object that Examples: Change value of variable for the current session. represents the execution context of the $Path = ‘C:\Scripts\TestScript’ $Path = ‘C:\Windows\System32’ $OFS The Output Field Separator specifies PowerShell host. $Date = Get-Date $Date = ($Date).AddDays(-90) the character that separates the $foreach Contains the enumerator of a ForEach loop. $Processes = Get-Process $Processes = (Get-Process).Name elements of an array that is $HOME Full path of the user's home directory. converted to a string. Default (“ “) $Host Represents the current host application for Clear Variable of values $OutputEncoding Determines the character encoding PowerShell. Clear-Variable -Name $Path method that PowerShell uses when it $input Enumerates all input passed to a function. Clear-Variable -Name $Date sends text to other applications. $IsCoreCLR .NET Core Runtime check. $True/$False Clear-Variable -Name $Processes $ProgressPreference Determines how PowerShell $IsLinux $True if is Linux. responds to progress updates. $IsMacOS $True if Operating system is Mac. Scoped $PSEmailServer Specifies the default e- server $IsWindows $True if Operating system is Windows. $Global:Server=’Ex01' Global variable, visible everywhere that is used to send messages. $LastExitCode Exit code of the last Windows-based program $Local:Count=1 Visible in local scope and child scopes $PSSessionConfigurationName Specifies the default session that was run. $Private:State=’Test’ Visible in local scope, but not child scopes configuration that is used for $Matches Hash table of any string values matched with PSSessions created in the current the -match and -notmatch operators. Multi-Assignment session. $MyInvocation Contains information about the current $State,$Count,$PC = ‘Enabled’, ‘1', ‘Windows10’ $PSSessionOption Establishes the default values for command, such as the name, parameters, advanced user options in a remote parameter values, and more. Flip Variables session. $null Represents an empty or null value. $Count1=3 ; $Count2=5 ; $Count1,$Count2 = $Count2,$Count1 $VerbosePreference Determines how PowerShell $PID Process identifier (PID) of PowerShell session. responds to verbose messages $PROFILE Full path of the PowerShell profile for the Read-Only Variable (can be overwritten with -Force) generated. current user and the current host application. Set-Variable 'PermRef' -Value '1973' -Option ReadOnly $WarningPreference Determines how PowerShell $PSCulture Reflects the culture of the current session. responds to warning messages $PSDebugContext This variable contains information about the Constant Variable Cannot be overwritten generated. debugging environment. Set-Variable 'Important' -Value '1973' -Option Constant $WhatIfPreference Determines whether WhatIf is $PSHome Full path of the installation directory for automatically enabled for every PowerShell Variable Acceptable Values: command that supports it. https://docs.microsoft.com/en-us/powershell/module/ [ValidateRange(90,150)][int]$Tolerance = 99 https://docs.microsoft.com/en-us/powershell/module/ $Tolerance = 151 #Returns error – not valid for the variable microsoft.powershell.core/about/about_automatic_variables microsoft.powershell.core/about/about_preference_variables PowerShell 7.0 - Quick Reference www.practicalpowershell.com V 0.1 Arrays Comments Strings 'bob','r','smith' Array of strings Starting a line with a ‘#’ makes the line a comment ‘String – this is an example’ 10,45,100 Array of integers # Load PowerShell Modules “Contains a $Variable that displays its value” @() Empty array (initiate) $Var = ‘#Not a comment example’ ‘Single quotes $Variable whose content is not displayed’ @(3) Array of 1 element # Write-Host ‘But this is an example’ @” @(3,4,5) Array of 3 elements $State = ‘Enabled’ # Set the State variable This is a more versatile string that can store quotes, returns 2,(5,7),10 Array within an array and can also evaluate variables. For example. Today’s date: $Process[0] First element in an array Multi-Line Comments $Date $Computer[2] Third element in an array <# Then we can close it off like we started this string. $User[5..14] Elements 6 through 15 Synopsis: This is a section of comments. “@ $Server[-1] Returns last element Purpose: To enclose a large section of text. Possibly to be @’ $Num[-4..-1] Returns last 4 elements used as a header for a script. This one is less versatile as it will not evaluate variables: @(Get-AzVM) Stores results in an array Version: 1.0 $Date Parameters: None Then we can close it off like we started this string. Reverse an Array #> ‘@ $a = 1,2,3,4,5 [array]::Reverse($a) Helpful Tips Loops # $a would then store the values as 5,4,3,2,1 Use tab to autocomplete cmdlets Foreach Tab through parameters to see all available The Foreach statement steps (iterates) through a series of values in Combine Arrays (+) a collection of items. Check for latest module versions $CSVFileData = Import-CSV “C:\Data.csv” $A = 1,2,3 ; $B = 4,5,6 ; $C = $A+$B Read latest Microsoft Docs for PowerShell Foreach ($Line in $CSVFileData) { Read PowerShell MVP blogs for more tips $DisplayName = $Line.DisplayName Create new array based on existing array Remove line wrapping from PowerShell session $Size = $Line.MailboxSizeMB $SomePCs = $AllPCs[1,3,5,7+9..13] Write-host “$DisplayName mailbox = $Size MB .” } Hash Tables TAB Autocomplete or cycle through all options Ctrl+Space Display all available parameters/switches ForEach-Object (Parallel – New Feature) $Hash = @ { } Creates an empty hash table Ctrl+V Copy data to session $Logs | Foreach-Object -Parallel {$File = $_+'.txt';get-winevent - $Hash =@{ColorOne = ‘Red’} Creates hash table with data LogName $_ -MaxEvents 5000 > $File } -ThrottleLimit 10 $Hash.ColorOne Display ColorOne key Do While $Hash.ColorTwo = ‘Green’ Assigns ‘Green’ to this key Object Properties Traverses list one or more times, subject to a While condition. Add values to hash Properties for an object can be accessed with ‘.’ followed by $Counter = 1 $Color = ‘ColorThree’ ; $Value = ‘White’ the property name. For example: Do { $Hash.Add($Color,$Value) $Process = Get-Process 'Chrome' Write-Host “This is pass # $counter for this loop.” Remove value from hash $Process.ID $Counter++ $Hash.Remove(‘ColorTwo’) $DC = get-adcomputer dc01 -Properties * } While ($Counter -ne 1000) Sort table by Key values $DC.dSCorePropagationData Do Until $Hash =@{ColorOne = 'Red'} If there are sub-properties, add with the ‘.’ separator: Traverses list one or more times, subject to a Until condition. $Users = Get-ADUser $Hash.ColorTwo = 'Green' $DC.dSCorePropagationData.Date Do { $Color = 'ColorThree' ; $Value = 'Blue' For Static Properties use :: Foreach ($User in $Users) { $Hash.Add($Color,$Value) [datetime]::Now $State = $Users.Enabled $Hash.Remove('ColorTwo') $FirstDisabledUserAccount = $User $Hash.GetEnumerator() | Sort-Object -Property Value } https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_hash_tables } Until ($State -eq ‘Disabled) PowerShell 7.0 - Quick Reference www.practicalpowershell.com V 0.1 Compatibility Experimental Features Reference: https://github.com/powershell/powershell#get-powershell New to PowerShell 7.0 is the concept of Experimental Features. These features are testing newly 2008 R2, 2012, 2012 R2, 2016, and 2019 developed modules, in test and not production. Windows 7, 8.1, and 10 macOS 10.13+ List any Experimental Features available to PowerShell 7.0's shell: Red Hat Enterprise Linux (RHEL) / CentOS 7+ Fedora 29+ Get-ExperimentalFeature Disable an Experimental Feature (if further development is needed, for example): Debian 9+ Ubuntu 16.04+ Disable-ExperimentalFeature openSUSE 15+ Alpine Linux 3.8+ Enable a new experimental feature or to enable an existing disabled feature (Microsoft’s examples): ARM32 and ARM64 flavors of Debian and Ubuntu ARM64 Alpine Linux. Enable-ExperimentalFeature Other Topics Supported Modules Troubleshooting List all executed commands for the current session: * All modules supported by PowerShell 6 New cmdlet – Get-Error Get-History List all previous commands th Use this cmdlet to retrieve past error messages. Get-History -Id 17 | Fl List the 17 executed command Incompatible modules Examples Clear-History Remove all entries from the history Import-Module -UseWindowsPowerShell Get-Error # Diplays the last error message Add-History Add additional entries to the history # Uses local WindowsPowerShell for this module Get-Error -Newest 2 # Displays last two error messages Invoke-History -Id 12 Re-runs item 12 from the history Pause and Sleep Add a pause or have PowerShell ‘Sleep’ for a matter of seconds https://docs.microsoft.com/en-us/powershell/module/ Working with Modules Pause # waits for operator to hit the ‘Enter’ key microsoft.powershell.core/about/about_history?view=powershell-7 Sleep 10 # Waits 10 seconds and then moves on PowerShell cmdlets are grouped my modules. We can work with Dates can be important in PowerShell supported cmdlets from any module. We can also load and Write-Host Get-Date Displays the current date and time unload modules as needed depending on if we need more cmdlets. Can be used to display variable content, known possible errors (Get-Date).AddDays(-30) Displays the date from 30 days ago Write-Host ‘Step 1’ (Get-Date).AddHours(4) Displays the time 4 hours from now List Modules Write-Host ‘Step 2’ Get-Module Lists loaded modules Write-Host ‘Step 3’ Format date examples: Get-Module -ListAvailable Lists all available modules Get-Date -Format yyyymmdd-hhmmss Write a Windows Event Get-Date -Format "MM.dd.yyyy-hh.mm-tt" Load and unload modules New-winevent -ProviderName Microsoft-Windows-PowerShell Import-Module ActiveDirectory Loads ActiveDirectory module -ID 8196 List items in a graphic format Remove-Module AZ Unloads the AZ module Get-WinEvent -ProviderName Microsoft-Windows-PowerShell $Processes | Out-GridView Displays running process in a grid -MaxEvents 100 List cmdlets for a module List Providers List items in a grid, allows selection and pass back to session $Module = ‘SharePointPnPPowerShellOnline’ Get-NetEventProvider -ShowInstalled | Ft Name $Processes | Out-GridView -PassThru Import-Module $Module Get-Command |Where {$_.Source -eq 'SharePointPnPPowerShellOnline'} Comments Measure how long a function takes to execute: Use comments to remove a one-liner or cmdlet from executing $StopWatch = [Diagnostics.Stopwatch]::StartNew() Locate a Module in a repository # Set-Mailbox -RetentionPolicies Temp & $FunctionToExecute Find-module MicrosoftTeams $StopWatch.Stop() Find-module ExchangeOnline* #Can use wildcards Try and Catch $StopWatch.Elapsed Used to catch errors and perform secondary/final actions. Or Install Module Try { Measure-Command {$FunctionToExecute} Install-Module MicrosoftTeams Set-ADForestMode -Identity corp.loc -ForestMode Find-module ExchangeOnlineManagement Windows2016Forest File Output } Catch { Get-AzVM | Export-CSV AzureVirtualMachines.csv Other Module functions Write-Host ‘AD cmdlet failed to execute.’ -ForegroundColor Red Get-AdComputer - * | Out-File AllDomainComputers.txt Uninstall-Module LyncOnlineConnector } Get-Process | Out-File AllProcesses.txt -Append -NoClobber Update-Module ExchangeOnlineManagement PowerShell 7.0 - Quick Reference www.practicalpowershell.com V 0.1 PowerShell Reference Links PowerShell Tools PowerShell Dev Blog Pester PowerShell Script Analyzer https://devblogs.microsoft.com/powershell/ https://github.com/pester/Pester https://github.com/PowerShell/PSScriptAnalyzer Scripting Blog PowerShell Editors https://devblogs.microsoft.com/scripting/ Microsoft premier PowerShell editor, replaces ISE. Supports more than just PowerShell editing. PowerShell 7.0 PowerShell ISE The original Microsoft PowerShell editor https://docs.microsoft.com/en-us/powershell/scripting/overview ** ISE does not support PowerShell 7.0 ** Notepad++ Notepad++ free editor, supports more than PowerShell editing DSC PowerShell Plus Free PowerShell editor by Idera https://docs.microsoft.com/en-us/powershell/scripting/dsc/overview/overview PowerShell Studio Paid editor by Sapien Technologies Windows PowerShell Forum Notepad OK. It’s an editor, but it’s not an IDE. https://social.technet.microsoft.com/Forums/windowsserver/en-US/home?forum=winserverpowershell Popular GitHub Repos PowerShell Survival Guide PSReadLine https://social.technet.microsoft.com/wiki/contents/articles/183.windows-powershell-survival-guide.aspx https://github.com/PowerShell/PSReadLine

Visual Studio Code TabExpansionPlusPlus https://code.visualstudio.com/ https://github.com/lzybkr/TabExpansionPlusPlus Visual Studio Code Extensions Windows OS Hardening with DSC https://marketplace.visualstudio.com/VSCode https://github.com/NVISO-BE/posh-dsc-windowsserver-hardening PowerShell Documentation https://docs.microsoft.com/en-us/powershell/ PoSH Git https://github.com/dahlbyk/posh-git PowerShell Podcast https://powershell.org/category/podcast/ Ninja https://github.com/ahmedkhlief/Ninja PowerShell Magazine http://powershellmagazine.com Detection Lab Good Blogs (Community and MVP blogs) https://github.com/clong/DetectionLab https://powershell.org/ https://www.planetpowershell.com/ Atomic Red Team https://mikefrobbins.com/ https://github.com/redcanaryco/atomic-red-team http://jdhitsolutions.com/blog/ https://richardspowershellblog.wordpress.com/ Free eBooks and Guides https://www.powershellmagazine.com/ https://evotec.xyz/category/powershell/ https://leanpub.com/u/devopscollective https://adamtheautomator.com/ https://books.goalkicker.com/PowerShellBook/ https://learn-powershell.net/ https://blog.netnerds.net/ PowerShell About Pages (Good read!)

PowerShell Tips of the Week https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/ www.practicalpowershell.com/blog