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
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 user interface (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 Operating system is Linux. responds to progress updates. $IsMacOS $True if Operating system is Mac. Scoped $PSEmailServer Specifies the default e-mail server $IsWindows $True if Operating system is Windows. $Global:Server=’Ex01' Global variable, visible everywhere that is used to send email 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 Windows Server 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
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