Quick Reference

Quick Reference

V 0.1 PowerShell 7.0 - Quick Reference www.practicalpowershell.com 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 <Condition> ? <if-true> : <if-false> 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-Computer 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 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

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    5 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us