powershell basics Flashcards

1
Q

What are Execution policy?

A

PowerShell’s execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts. This feature helps prevent the execution of malicious scripts.

On a Windows computer you can set an execution policy for the local computer, for the current user, or for a particular session. You can also use a Group Policy setting to set execution policies for computers and users.

Execution policies for the local computer and current user are stored in the registry. You don’t need to set execution policies in your PowerShell profile. The execution policy for a particular session is stored only in memory and is lost when the session is closed.

The execution policy isn’t a security system that restricts user actions. For example, users can easily bypass a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What execution policies are available in Powershell?

A

The PowerShell execution policies are as follows:

AllSigned

  • Scripts can run.
  • Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on the local computer.
  • Prompts you before running scripts from publishers that you haven’t yet classified as trusted or untrusted.
  • Risks running signed, but malicious, scripts.

Bypass

  • Nothing is blocked and there are no warnings or prompts.
  • This execution policy is designed for configurations in which a PowerShell script is built in to a larger application or for configurations in which PowerShell is the foundation for a program that has its own security model.

Default

  • Sets the default execution policy.
  • Restricted for Windows clients.
  • RemoteSigned for Windows servers.

RemoteSigned

  • The default execution policy for Windows server computers.
  • Scripts can run.
  • Requires a digital signature from a trusted publisher on scripts and configuration files that are downloaded from the internet which includes email and instant messaging programs.
  • Doesn’t require digital signatures on scripts that are written on the local computer and not downloaded from the internet.
  • Runs scripts that are downloaded from the internet and not signed, if the scripts are unblocked, such as by using the Unblock-File cmdlet.
  • Risks running unsigned scripts from sources other than the internet and signed, but malicious, scripts.

Restricted

  • The default execution policy for Windows client computers.
  • Permits individual commands, but will not run scripts.
  • Prevents running of all script files, including formatting and configuration files (.ps1xml), module script files (.psm1), and PowerShell profiles (.ps1).

Undefined

  • There is no execution policy set in the current scope.
  • If the execution policy in all scopes is Undefined, the effective execution policy is Restricted, which is the default execution policy.

Unrestricted

  • The default execution policy for non-Windows computers and cannot be changed.
  • Unsigned scripts can run. There is a risk of running malicious scripts.
  • Warns the user before running scripts and configuration files that are downloaded from the internet.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the Scope of the execution policy in Powershell?

A

You can set an execution policy that is effective only in a particular scope.

The valid values for Scope are MachinePolicy, UserPolicy, Process, CurrentUser, and LocalMachine. LocalMachine is the default when setting an execution policy.

The Scope values are listed in precedence order. The policy that takes precedence is effective in the current session, even if a more restrictive policy was set at a lower level of precedence.

For more information, see Set-ExecutionPolicy.

MachinePolicy

Set by a Group Policy for all users of the computer.

UserPolicy

Set by a Group Policy for the current user of the computer.

Process

The Process scope only affects the current PowerShell session. The execution policy is saved in the environment variable $env:PSExecutionPolicyPreference, rather than the registry. When the PowerShell session is closed, the variable and value are deleted.

CurrentUser

The execution policy affects only the current user. It’s stored in the HKEY_CURRENT_USER registry subkey.

LocalMachine

The execution policy affects all users on the current computer. It’s stored in the HKEY_LOCAL_MACHINE registry subkey.

SHORT TEXT TO REMEMBER THE POLICIES

Many Users Possess Cuttingedge Laptops

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the execution policy precedence?

A

When determining the effective execution policy for a session, PowerShell evaluates the execution policies in the following precedence order:

Group Policy: MachinePolicy

Group Policy: UserPolicy

Execution Policy: Process (or pwsh.exe -ExecutionPolicy)

Execution Policy: CurrentUser

Execution Policy: LocalMachine

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between set-variable & new-variable cmdlets in Powershell?

A

new-variable cmdlet would always create a new variable whereas Set-variable cmdlet would first check if the variable exists and if it does it will change the value of the variable to what you provide as a parameter to set-variable. If the variable does not exists it will create the variable with the value you provide.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are variables in Powershell?

A

You can store all types of values in PowerShell variables. They are typically used to store the results of commands and to store elements that are used in commands and expressions, such as names, paths, settings, and values.

A variable is a unit of memory in which values are stored. In PowerShell, variables are represented by text strings that begin with a dollar sign ($), such as $a, $process, or $my_var.

You can store any type of object in a variable, including integers, strings, arrays, hash tables, and objects that represent processes, services, event logs, and computers.

PowerShell variables are “loosely typed,” which means that they are not limited to a particular type of object. A single variable can even contain a collection (an “array”) of different types of objects at the same time.

The data type of a variable is determined by the .NET types of the values of the variable.

For example:

PS> $a = 12 # System.Int32
PS> $a = "Word" # System.String
PS> $a = 12, "Word" # array of System.Int32, System.String
PS> $a = dir C:\Windows\System32 # FileInfo and DirectoryInfo types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Are variable names in Powershell case sensitive?

A

Variable names are not case-sensitive. Variable names can include spaces and special characters, but these are difficult to use and should be avoided.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the different types of variables in Powershell?

A

There are several different types of variables in PowerShell.

  • User-created variables: User-created variables are created and maintained by the user. By default, the variables that you create at the PowerShell command line exist only while the PowerShell window is open, and they are lost when you close the window. To save a variable, add it to your PowerShell profile. You can also create variables in scripts with global, script, or local scope.
  • Automatic variables: Automatic variables store the state of PowerShell. These variables are created by PowerShell, and PowerShell changes their values as required to maintain their accuracy. Users cannot change the value of these variables. For example, the $PSHome variable stores the path to the PowerShell installation directory.
  • Preference variables: Preference variables store user preferences for PowerShell. These variables are created by PowerShell and are populated with default values. Users can change the values of these variables. For example, the $MaximumHistoryCount variable determines the maximum number of entries in the session history.

For more information, a list, and a description of the preference variables, see about_Preference_Variables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you delete the value of a variable in powershell?

how do you delete the variable in Powershell?

A

To delete the value of a variable, use the Clear-Variable cmdlet or change the value to $null.

PS> Clear-Variable -name MyVariable

-or-

PS> $MyVariable = $null

To delete the variable, use the Remove-Variable or Remove-Item cmdlets. These cmdlets are discussed later in this topic.

PS> Remove-Variable -name MyVariable

PS> Remove-Item -path Variable:\MyVariable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you get the list of all variables in a Powershell session?

A

To get a list of all the variables in your PowerShell session, type:

Get-Variable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you ensure that a variable can contain only objects of the specified type or objects that can be converted to that type?

A

You can use a type attribute and cast notation to ensure that a variable can contain only objects of the specified type or objects that can be converted to that type. If you try to assign a value of another type, PowerShell tries to convert the value to its type. If it cannot, the assignment statement fails.

To use cast notation, enter a type name, enclosed in brackets, before the variable name (on the left side of the assignment statement). The following example creates an $number variable that can contain only integers, a $words variable that can contain only strings, and a $dates variable that can contain only DateTime objects.

PS> [int]$number = 8
PS> $number = "12345" (The string is converted to an integer.)
PS> $number = "Hello"
Cannot convert value "Hello" to type "System.Int32". Error: "Input string
 was not in a correct format."
At line:1 char:3
\+ $a <<<< = "Hello"
    \+ CategoryInfo : MetadataError: (:) [], ArgumentTransformati
onMetadataException
    \+ FullyQualifiedErrorId : RuntimeException

PS> [string]$words = "Hello"
PS> $words = 2 (The integer is converted to a string.)
PS> $words + 10 (The strings are concatenated.)
210

PS> #The string is converted to a DateTime object.
PS> [datetime] $dates = "09/12/91"
PS> $dates
Thursday, September 12, 1991 12:00:00 AM

PS> $dates = 10 #The integer is converted to a DateTime object.
PS> $dates
Monday, January 01, 0001 12:00:00 AM
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you use variables in commands and expressions?

A

To use a variable in a command or expression, type the variable name, preceded by the dollar sign ($).

If the variable name (and dollar sign) are not enclosed in quotation marks, or if they are enclosed in double quotation marks (“), the value of the variable is used in the command or expression.

If the variable name (and dollar sign) are enclosed in single quotation marks, (‘), the variable name is used in the expression.

For example, the first command gets the value of the $profile variable, which is the path to the PowerShell user profile file in the PowerShell console. The second command opens the file in Notepad, and the third and fourth commands use the name of the variable in an expression.

PS> $profile
C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microso
ft.PowerShell_profile.ps1

PS> notepad $profile
- or -
PS> notepad "$profile"
C:\Documents and Settings\User01\My Documents\WindowsPowerShell\Microso
ft.PowerShell_profile.ps1

PS> '$profile'
$profile

PS> 'Use the $profile variable.'
Use the $profile variable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to use variables that include special characters?

A

Variable names begin with a dollar sign. They can include alphanumeric characters and special characters. The length of the variable name is limited only by available memory.

Whenever possible, variable names should include only alphanumeric characters and the underscore character (_). Variable names that include spaces and other special characters, are difficult to use and should be avoided.

To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs PowerShell to interpret the characters in the variable name literally.

For example, the following command creates and then displays a variable named “save-items”.

PS> ${save-items} = "a", "b", "c"
PS> ${save-items}
a
b
c

The following command gets the child items in the directory that is represented by the “ProgramFiles(x86)” environment variable.

PS> Get-ChildItem ${env:ProgramFiles(x86)}

To reference a variable name that includes braces, enclose the variable name in braces, and use the backtick (escape) character to escape the braces. For example, to create a variable named “this{value}is” with a value of 1, type:

PS> ${this`{value`}is} = 1
PS> ${this`{value`}is}
1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the scope of variables in Powershell?

A

By default, variables are available only in the scope in which they are created.

For example, a variable that you create in a function is available only within the function. A variable that you create in a script is available only within the script (unless you dot-source the script, which adds it to the current scope).

You can use a scope modifier to change the default scope of the variable. The following expression creates a variable named “Computers”. The variable has a global scope, even when it is created in a script or function.

$global:Computers = "Server01"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you ensure that a variable exists in every powershell session that you create?

A

Variables that you create are available only in the session in which you create them. They are lost when you close your session.

To create the in every PowerShell session that you start, add the variable to your PowerShell profile.

For example, to change the value of the $VerbosePreference variable in every PowerShell session, add the following command to your PowerShell profile.

$VerbosePreference = "Continue"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

what is a VARIABLE: Drive?

A

PowerShell Variable provider creates a Variable: drive that looks and acts like a file system drive, but it contains the variables in your session and their values.

To change to the Variable: drive, type:

Set-Location Variable:

To list the items (variables) in the Variable: drive, use the Get-Item or Get-ChildItem cmdlets. For example:

Get-ChildItem Variable:

To get the value of a particular variable, use file system notation to specify the name of the drive and the name of the variable. For example, to get the $PSCulture automatic variable, use the following command.

Get-Item Variable:\PSCulture

Name Value
---- -----
PSCulture en-US
17
Q

What are the various cmdlets in powershell to manage variables?

A

owerShell includes a set of cmdlets that are designed to manage variables.

Cmdlet Name Description

Clear-Variable Deletes the value of a variable.

Get-Variable Gets the variables in the current console.

New-Variable Creates a new variable.

Remove-Variable Deletes a variable and its value.

Set-Variable Changes the value of a variable.

18
Q

what is the output of the following script? what is the difference in using doublt quotes and single quotes when printing the variable name?

$temperature=42

Write-Output “Temperature : $temperature”
Write-Output ‘Temperature : $temperature’

A

the output would be as follows

$temperature=42

Write-Output “Temperature : $temperature”

Output

Temperature : 42

Write-Output ‘Temperature : $temperature’

Output

Temperature : $temperature

the reason is because double quotes can resolve the variable and print the actual value of the variable whereas single quotes cannot resolve the value of the variable.

19
Q

How do you avoid resolving a variable inside double quotes?

A

you can use the character ` to prevent powershell from resolving the variables inside double quotes

for example in the following script the value of the variable $temperature is 42. you can use the escape character to avoid the resolution of the variable inside doublt quotes.. script as follows

$temperature=42

Write-Output “Temperature : `$temperature

20
Q

What is the Read-Host cmdlet?

A

The Read-Host cmdlet enables you to interactively prompt a user for information. For example, this command prompts the user to enter his or her name, then stores that name in the variable $Name (to answer the prompt, type a name and then press ENTER):

$Name = Read-Host "Please enter your name"

Read-Host requires just one parameter: the prompt to be presented to the user. Note that you do not have to add a colon at the end of the prompt (e.g., “Please enter your name:”); Windows PowerShell will add the colon to the end of the prompt for you.

y adding the -assecurestring parameter you can mask the data entered at the prompt. For example, this command uses the -assecurestring parameter to ask a user to enter his or her password:

$Password = Read-Host -assecurestring "Please enter your password"
21
Q

What are Here-strings in Powershell?

A

HERE-STRINGS

The quotation rules for here-strings are slightly different.

A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally. A here-string can span multiple lines. All the lines in a here-string are interpreted as strings even though they are not enclosed in quotation marks.

Like regular strings, variables are replaced by their values in double-quoted here-strings. In single-quoted here-strings, variables are not replaced by their values.

You can use here-strings for any text, but they are particularly useful for the following kinds of text:

  • Text that contains literal quotation marks
  • Multiple lines of text, such as the text in an HTML or XML
  • The Help text for a script or function document

A here-string can have either of the following formats, where <enter> represents the linefeed or newline hidden character that is added when you press the ENTER key.</enter>

Double-quotes:

@"
 [string] ...
"@

Single-quotes:

@' [string] ... '@

In either format, the closing quotation mark must be the first character in the line.

A here-string contains all the text between the two hidden characters. In the here-string, all quotation marks are interpreted literally. For example:

PowerShell

@"
For help, type "get-help"
"@

The output of this command is:

output

For help, type "get-help"

Using a here-string can simplify using a string in a command. For example:

PowerShell

@"
Use a quotation mark (') to begin a string.
"@

The output of this command is:

output

Use a quotation mark (') to begin a string.

In single-quoted here-strings, variables are interpreted literally and reproduced exactly. For example:

PowerShell

@'
The $profile variable contains the path
of your Windows PowerShell profile.
'@

The output of this command is:

output

The $profile variable contains the path
of your Windows PowerShell profile.

In double-quoted here-strings, variables are replaced by their values. For example:

PowerShell

@"
Even if you have not created a profile,
the path of the profile file is:
$profile.
"@

The output of this command is:

output

Even if you have not created a profile,
the path of the profile file is:
C:\Users\User1\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.

Here-strings are typically used to assign multiple lines to a variable. For example, the following here-string assigns a page of XML to the $page variable.

PowerShell

$page = [XML] @"

               Format-Table

            Formats the output as a table.

        format
        table

...

"@

Here-strings are also a convenient format for input to the ConvertFrom-StringData cmdlet, which converts here-strings to hash tables. For more information, see ConvertFrom-StringData

22
Q

What are the Data types in Powershell?

A

Data Types:
Data Type Name Description [Array] Array [Bool] Value is TRUE or FALSE [DateTime] Date and time [Guid] Globally unique 32-byte identifier [HashTable] Hash table, collection of key-value pairs [Int32], [Int] 32-bit integers [PsObject] PowerShell object [Regex] Regular expression [ScriptBlock] PowerShell script block [Single], [Float] Floating point number [String],

System.String

String [Switch] PowerShell switch parameter [TimeSpan] Time interval [XmlDocument] XML document

Short notations of Powershell data types

[string] Fixed-length string of Unicode characters [char] A Unicode 16-bit character [byte] An 8-bit unsigned character [int] 32-bit signed integer [long] 64-bit signed integer [bool] Boolean True/False value [decimal] A 128-bit decimal value [single] Single-precision 32-bit floating point number [double] Double-precision 64-bit floating point number [DateTime] Date and Time [xml] Xml object [array] An array of values [hashtable] Hashtable object

Note:

  • Windows PowerShell uses the Microsoft .NET Framework data types.
  • We don’t have to rely on PowerShell’s ability to automatically convert data types if we tell the interpreter that we are expecting a number as input.
  • This ensures that our script works as intended.
  • The explicitly declaring variable types can prevent unwanted results in your scripts and makes them more reliable.
23
Q

What are automatic Variables in Powershell?

A

Describes variables that store state information for PowerShell. These variables are created and maintained by PowerShell.

Conceptually, these variables are considered to be read-only. Even though they can be written to, for backward compatibility they should not be written to.

Here is a list of some automatic variables in PowerShell:

$?

Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

$_

Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

$ConsoleFileName

Contains the path of the console file (.psc1) that was most recently used in the session. This variable is populated when you start PowerShell with the PSConsoleFile parameter or when you use the Export-Console cmdlet to export snap-in names to a console file.

When you use the Export-Console cmdlet without parameters, it automatically updates the console file that was most recently used in the session. You can use this automatic variable to determine which file will be updated.

$Error

Contains an array of error objects that represent the most recent errors. The most recent error is the first error object in the array $Error[0].

To prevent an error from being added to the $Error array, use the ErrorAction common parameter with a value of Ignore. For more information,

$false

Contains FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string “false”. The string can be interpreted as TRUE if it is converted to a non-empty string or to a non-zero integer.

$foreach

Contains the enumerator (not the resulting values) of a ForEach loop. The $ForEach variable exists only while the ForEach loop is running; it is deleted after the loop is completed.

Enumerators contain properties and methods you can use to retrieve loop values and change the current loop iteration.

$HOME

Contains the full path of the user’s home directory. This variable is the equivalent of the “$env:homedrive$env:homepath” Windows environment variables, typically C:\Users<username>.</username>

$Host

Contains an object that represents the current host application for PowerShell. You can use this variable to represent the current host in commands or to display or change the properties of the host, such as $Host.version or $Host.CurrentCulture, or$host.ui.rawui.setbackgroundcolor(“Red”).

$NULL

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

For example, when $null is included in a collection, it is counted as one of the objects.

PowerShell

$a = "one", $null, "three"
$a.count

output

3

$PID

Contains the process identifier (PID) of the process that is hosting the current PowerShell session.

$PROFILE

Contains the full path of the PowerShell profile for the current user and the current host application. You can use this variable to represent the profile in commands. For example, you can use it in a command to determine whether a profile has been created:

PowerShell

Test-Path $PROFILE

Or, you can use it in a command to create a profile:

PowerShell

New-Item -ItemType file -Path $PSHOME -Force

You can also use it in a command to open the profile in Notepad:

PowerShell

notepad $profile

$PSHOME

Contains the full path of the installation directory for PowerShell, typically, $env:windir\System32\PowerShell\v1.0 in Windows systems. You can use this variable in the paths of PowerShell files.

$PSItem

Same as $_. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

$PSScriptRoot

Contains the directory from which a script is being run.

In PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in PowerShell 3.0, it is valid in all scripts.

$PSSenderInfo

Contains information about the user who started the PSSession, including the user identity and the time zone of the originating computer. This variable is available only in PSSessions.

$PSVersionTable

Contains a read-only hash table that displays details about the version of PowerShell that is running in the current session. The table includes the following items:

Property Description BuildVersion The build number of the current version CLRVersion The version of the common language runtime (CLR) GitCommitId The commit Id of the source files, in GitHub, used in this version of PowerShell PSCompatibleVersions Versions of PowerShell that are compatible with the current version PSEdition This property has the value of ‘Desktop’, for Windows Server and Windows client versions. This property has the value of ‘Core’ for PowerShell running under Nano Server or Windows IOT. PSRemotingProtocolVersion The version of the PowerShell remote management protocol. PSVersion The PowerShell version number SerializationVersion The version of the serialization method WSManStackVersion The version number of the WS-Management stack

$PWD

Contains a path object that represents the full path of the current directory.

$true

Contains TRUE. You can use this variable to represent TRUE in commands and scripts.

24
Q

What are the types of Comparison operators in Powershell?

A

Powershell has the following types of comparison operators

  1. Equality
  2. Matching
  3. Containment
  4. Replacement
  5. Type
25
Q

What are the comparison operators available in Powershell?

A

Powershell has the following comparision operators

Type: Equality

Operators

  • eq equals
  • ne not equals
  • gt greater than
  • ge greater than or equal
  • lt less than
  • le less than or equal

Category: Matching

Operators

  • like Returns true when string matches wildcard pattern
  • notlike Returns true when string does not match wildcard pattern
  • match Returns true when string matches regex pattern; $matches contains matching strings
  • notmatch Returns true when string does not match regex pattern; $matches contains matching strings

Category: Containment

Operators

  • contains Returns true when reference value contained in a collection
  • notcontains Returns true when reference value not contained in a collection
  • in Returns true when test value contained in a collection
  • notin Returns true when test value not contained in a collection

Category: Replacement

Operators

-replace Replaces a string pattern

Category: Type

Operators

  • is Returns true if both object are the same type
  • isnot Returns true if the objects are not the same type
26
Q

Are comparison operators in Powershell Case-insensitive or Case Sensitive?

A

By default, all comparison operators are case-insensitive.

27
Q

How to make a comparison operator in Powershell Case-sensitive?

A

By default, all comparison operators are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a c. For example, the case-sensitive version of -eq is -ceq. To make the case-insensitivity explicit, precede the operator with an i.

For example, the explicitly case-insensitive version of -eq is -ieq.

28
Q

what are the outputs of a comparison operator? What do they return?

A

When the input to an operator is a scalar value, comparison operators return a Boolean value. When the input is a collection of values, the comparison operators return any matching values. If there are no matches in a collection, comparison operators do not return anything.

The exceptions are the containment operators (-contains, -notcontains), the In operators (-in, -notin), and the type operators (-is, -isnot), which always return a Boolean value.

29
Q

what are equality operators?

A

Equality Operators

The equality operators (-eq, -ne) return a value of TRUE or the matches when one or more of the input values is identical to the specified pattern. The entire pattern must match an entire value.

Example:

-eq

Description: Equal to. Includes an identical value.

Example:

PowerShellCopy

C:PS> 2 -eq 2
True

C:PS> 2 -eq 3
False

C:PS> 1,2,3 -eq 2
2
PS> "abc" -eq "abc"
True

PS> "abc" -eq "abc", "def"
False

PS> "abc", "def" -eq "abc"
abc

-ne

Description: Not equal to. Includes a different value.

Example:

PowerShellCopy

PS> "abc" -ne "def"
True

PS> "abc" -ne "abc"
False

PS> "abc" -ne "abc", "def"
True

PS> “abc”, “def” -ne “abc”
def
~~~
```

-gt

Description: Greater-than.

Example:

PowerShellCopy

PS> 8 -gt 6
True

PS> 7, 8, 9 -gt 8
9

Note

This should not to be confused with >, the greater-than operator in many other programming languages. In PowerShell, > is used for redirection. For more information, see About_redirection.

-ge

Description: Greater-than or equal to.

Example:

PowerShellCopy

PS> 8 -ge 8
True

PS> 7, 8, 9 -ge 8
8
9

-lt

Description: Less-than.

Example:

PowerShellCopy

PS> 8 -lt 6
False

PS> 7, 8, 9 -lt 8
7

-le

Description: Less-than or equal to.

Example:

PowerShellCopy

PS> 6 -le 8
True

PS> 7, 8, 9 -le 8
7
8
30
Q

what are Matching operators?

A

Matching Operators

The like operators (-like and -notlike) find elements that match or do not match a specified pattern using wildcard expressions.

The syntax is:

PowerShellCopy

-like 
 -notlike

The match operators (-match and -notmatch) find elements that match or do not match a specified pattern using regular expressions.

The match operators populate the $Matches automatic variable when the input (the left-side argument) to the operator is a single scalar object. When the input is scalar, the -match and -notmatch operators return a Boolean value and set the value of the $Matches automatic variable to the matched components of the argument.

The syntax is:

PowerShellCopy

-match 
 -notmatch

-like

Description: Match using the wildcard character (*).

Example:

PowerShellCopy

PS> "PowerShell" -like "*shell"
True

PS> "PowerShell", "Server" -like "*shell"
PowerShell

-notlike

Description: Does not match using the wildcard character (*).

Example:

PowerShellCopy

PS> "PowerShell" -notlike "*shell"
False

PS> "PowerShell", "Server" -notlike "*shell"
Server

-match

Description: Matches a string using regular expressions. When the input is scalar, it populates the $Matches automatic variable.

The match operators search only in strings. They cannot search in arrays of integers or other objects.

If the input is a collection, the -match and -notmatch operators return the matching members of that collection, but the operator does not populate the $Matches variable.

For example, the following command submits a collection of strings to the -match operator. The -match operator returns the items in the collection that match. It does not populate the $Matchesautomatic variable.

PowerShellCopy

PS> "Sunday", "Monday", "Tuesday" -match "sun"
Sunday

PS> $Matches
PS>

In contrast, the following command submits a single string to the -match operator. The -matchoperator returns a Boolean value and populates the $Matches automatic variable. The $Matchesautomatic variable is a Hashtable. If no grouping or capturing is used, only one key is populated. The 0 key represents all text that was matched. For more information about grouping and capturing using regular expressions, see about_Regular_Expressions.

PowerShellCopy

PS> "Sunday" -match "sun"
True

PS> $Matches

Name Value
---- -----
0 Sun

It is important to note that the $Matches hashtable will only contain the first occurrence of any matching pattern.

PowerShellCopy

PS> "Banana" -match "na"
True

PS> $Matches

Name Value
---- -----
0 na

Important

The 0 key is an Integer. You can use any Hashtable method to access the value stored.

PowerShellCopy

PS> "Good Dog" -match "Dog"
True

PS> $Matches[0]
Dog

PS> $Matches.Item(0)
Dog

PS> $Matches.0
Dog

The -notmatch operator populates the $Matches automatic variable when the input is scalar and the result is False, that it, when it detects a match.

PowerShellCopy

PS> "Sunday" -notmatch "rain"
True

PS> $matches
PS>

PS> "Sunday" -notmatch "day"
False

PS> $matches

Name Value
---- -----
0 day

-notmatch

Description: Does not match a string. Uses regular expressions. When the input is scalar, it populates the $Matches automatic variable.

Example:

PowerShellCopy

PS> "Sunday" -notmatch "sun"
False

PS> $matches
Name Value
---- -----
0 sun

PS> "Sunday", "Monday" -notmatch "sun"
Monday

###

31
Q

what are Containment operators?

A

Find unapproved verbs in the functions in my module

Containment Operators

The containment operators (-contains and -notcontains) are similar to the equality operators. However, the containment operators always return a Boolean value, even when the input is a collection.

Also, unlike the equality operators, the containment operators return a value as soon as they detect the first match. The equality operators evaluate all input and then return all the matches in the collection.

-contains

Description: Containment operator. Tells whether a collection of reference values includes a single test value. Always returns a Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values.

When the test value is a collection, the Contains operator uses reference equality. It returns TRUE only when one of the reference values is the same instance of the test value object.

In a very large collection, the -contains operator returns results quicker than the equal to operator.

Syntax:

` -contains `

Examples:

PowerShellCopy

PS> "abc", "def" -contains "def"
True

PS> "Windows", "PowerShell" -contains "Shell"
False #Not an exact match

# Does the list of computers in $DomainServers include $ThisComputer?
PS> $DomainServers -contains $thisComputer
True

PS> "abc", "def", "ghi" -contains "abc", "def"
False

PS> $a = "abc", "def"
PS> "abc", "def", "ghi" -contains $a
False
PS> $a, "ghi" -contains $a
True

-notcontains

Description: Containment operator. Tells whether a collection of reference values includes a single test value. Always returns a Boolean value. Returns TRUE when the test value is not an exact matches for at least one of the reference values.

When the test value is a collection, the NotContains operator uses reference equality.

Syntax:

` -notcontains `

Examples:

PowerShellCopy

PS> "Windows", "PowerShell" -notcontains "Shell"
True #Not an exact match

# Get cmdlet parameters, but exclude common parameters
function get-parms ($cmdlet)
{
$Common = “Verbose”, “Debug”, “WarningAction”, “WarningVariable”,
“ErrorAction”, “ErrorVariable”, “OutVariable”, “OutBuffer”
~~~

$allparms = (Get-Command $Cmdlet).parametersets |
  foreach {$_.Parameters} |
    foreach {$_.Name} | Sort-Object | Get-Unique

$allparms | where {$Common -notcontains $_ } }

PS> $ApprovedVerbs = Get-Verb | foreach {$.verb}
PS> $myVerbs = Get-Command -Module MyModule | foreach {$
.verb}
PS> $myVerbs | where {$ApprovedVerbs -notcontains $_}
ForEach
Sort
Tee
Where
~~~

-in

Description: In operator. Tells whether a test value appears in a collection of reference values. Always return as Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values.

When the test value is a collection, the In operator uses reference equality. It returns TRUE only when one of the reference values is the same instance of the test value object.

The -in operator was introduced in PowerShell 3.0.

Syntax:

` -in `

Examples:

PowerShellCopy

PS> "def" -in "abc", "def"
True

PS> "Shell" -in "Windows", "PowerShell"
False #Not an exact match

PS> "Windows" -in "Windows", "PowerShell"
True #An exact match

PS> "Windows", "PowerShell" -in "Windows", "PowerShell", "ServerManager"
False #Using reference equality

PS> $a = "Windows", "PowerShell"
PS> $a -in $a, "ServerManager"
True #Using reference equality

# Does the list of computers in $DomainServers include $ThisComputer?
PS> $thisComputer -in $domainServers
True

-notin

Description: Tells whether a test value appears in a collection of reference values. Always returns a Boolean value. Returns TRUE when the test value is not an exact match for at least one of the reference values.

When the test value is a collection, the In operator uses reference equality. It returns TRUE only when one of the reference values is the same instance of the test value object.

The -notin operator was introduced in PowerShell 3.0.

Syntax:

` -notin `

Examples:

PowerShellCopy

PS> "def" -notin "abc", "def"
False

PS> "ghi" -notin "abc", "def"
True

PS> "Shell" -notin "Windows", "PowerShell"
True #Not an exact match

PS> "Windows" -notin "Windows", "PowerShell"
False #An exact match

# Find unapproved verbs in the functions in my module
PS> $ApprovedVerbs = Get-Verb | foreach {$.verb}
PS> $MyVerbs = Get-Command -Module MyModule | foreach {$
.verb}
~~~

PS> $MyVerbs | where {$_ -notin $ApprovedVerbs}
ForEach
Sort
Tee
Where
~~~

32
Q

what are Replacement operators?

A

Replacement Operator

The -replace operator replaces all or part of a value with the specified value using regular expressions. You can use the -replace operator for many administrative tasks, such as renaming files. For example, the following command changes the file name extensions of all .txt files to .log:

PowerShellCopy

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -replace '\.txt$','.log' }

The syntax of the -replace operator is as follows, where the <original> placeholder represents the characters to be replaced, and the <substitute> placeholder represents the characters that will replace them:</substitute></original>

` , `

By default, the -replace operator is case-insensitive. To make it case sensitive, use -creplace. To make it explicitly case-insensitive, use -ireplace.

Consider the following examples:

PowerShellCopy

PS> "book" -replace "B", "C"

outputCopy

Cook

PowerShellCopy

"book" -ireplace "B", "C"

outputCopy

Cook

PowerShellCopy

"book" -creplace "B", "C"

outputCopy

book

It is also possible to use capturing groups, and substitutions with the -replace operator. For more information, see about_Regular_Expressions.

Substitutions in Regular Expressions

Additionally, capturing groups can be referenced in the <substitute> string. This is done by using the <code>$</code> character before the group identifier.</substitute>

Two of the ways to reference capturing groups is by Number and by Name

  • By Number - Capturing Groups are numbered from left to right.

PowerShellCopy

"John D. Smith" -replace "(\w+) (\w+)\. (\w+)", '$1.$2.$3@contoso.com'

outputCopy

John.D.Smith@contoso.com
  • By Name - Capturing Groups can also be referenced by name.

PowerShellCopy

"CONTOSO\Administrator" -replace '\w+\\(?\w+)', 'FABRIKAM\${user}'

outputCopy

FABRIKOM\Administrator

Warning

Since the $ character is used in string expansion, you will need to use literal strings with substitution, or escape the $ character.

PowerShellCopy

'Hello World' -replace '(\w+) \w+', "`$1 Universe"

outputCopy

Hello Universe

Additionally, sicne the $ character is used in substitution, you will need to escape any instances in your string.

PowerShellCopy

'5.72' -replace '(.+)', '\$\$$1'

outputCopy

$5.72
33
Q

what are the type comparison operators?

A

Type comparison

The type comparison operators (-is and -isnot) are used to determine if an object is a specific type.

-is

Syntax:

` -is `

Example:

PowerShellCopy

PS> $a = 1
PS> $b = "1"
PS> $a -is [int]
True
PS> $a -is $b.GetType()
False

-isnot

Syntax:

` -isnot `

Example:

PowerShellCopy

PS> $a = 1
PS> $b = "1"
PS> $a -isnot $b.GetType()
True
PS> $b -isnot [int]
True
34
Q

what is the output of the following script

1,2,3,4,5,6,7,8,9 -lt 5

Also for this

$valueofnumbers=4,1,2,3,4
$valueofnumbers -lt 3

A

Output for first script

1,2,3,4,5,6,7,8,9 -lt 5

PS K:\> 1,2,3,4,5,6,7,8,9 -lt 5
1
2
3
4

Output for second script

$valueofnumbers=4,1,2,3,4
$valueofnumbers -lt 3

1
2

When using comparison operator -lt on an array or group of numbers seperated by comma(,) the oprerator would return the values which satisfies the condition. in the above example because we used an array or a group of numbers with the comparision operator -lt it returned all the values which were lesser than the condition.

35
Q

Describe the various types of operators in Powershell?

A

Arithmetic Operators: +, -, *, /, %

Assignment Operators: =, +=, -=, *=, /=, %=

Comparison Operators: -eq, -ne, -gt, -lt, -le, -ge, -match, -notmatch, -replace, -like, -notlike, -in, -notin, -contains, -notcontains, -bAND, -bOR, -bXOR, -bNOT

Use comparison operators (-eq, -ne, -gt, -lt, -le, -ge) to compare values and test conditions. For example, you can compare two string values to determine whether they are equal.

The comparison operators also include operators that find or replace patterns in text. The (-match, -notmatch, -replace) operators use regular expressions, and (-like, -notlike) use wildcards *.

Containment comparison operators determine whether a test value appears in a reference set (-in, -notin, -contains, -notcontains).

Bitwise comparison operators (-bAND, -bOR, -bXOR, -bNOT) manipulate the bit patterns in values.

Logical Operators: -and, -or, -xor, -not, !

Redirection Operators: >, >>, 2>, 2>>, and 2>&1

Use redirection operators (>, >>, 2>, 2>>, and 2>&1) to send the output of a command or expression to a text file. The redirection operators work like the Out-File cmdlet (without parameters) but they also let you redirect error output to specified files.

Split and Join Operators: -split, -join

The -split and -join operators divide and combine substrings. The -split operator splits a string into substrings. The -join operator concatenates multiple strings into a single string.

Type Operators: -is, -isnot, -as

Use the type operators (-is, -isnot, -as) to find or change the .NET Framework type of an object.

Unary Operators:

Use unary operators to increment or decrement variables or object properties and to set integers to positive or negative numbers. For example, to increment the variable $a from 9 to 10, you type $a++.

Array subexpression : @( )

Returns the result of one or more statements as an array. If there is only one item, the array has only one member.

@(Get-WmiObject win32_logicalDisk)

Call operator: &

Runs a command, script, or script block. The call operator, also known as the “invocation operator,” lets you run commands that are stored in variables and represented by strings or script blocks. The call operator executes in a child scope.

This example stores a command in a string and executes it using the call operator.

$c = “get-executionpolicy”

& $c

The call operator does not parse strings. This means that you cannot use command parameters within a string when you use the call operator.

Cast operator []

Converts or limits objects to the specified type. If the objects cannot be converted, PowerShell generates an error.

datetime$birthday = “1/20/88”

[int64]$a = 34

Comma operator: ,

As a binary operator, the comma creates an array. As a unary operator, the comma creates an array with one member. Place the comma before the member.

$myArray = 1,2,3
$SingleArray = ,1

Dot sourcing operator:.

Runs a script in the current scope so that any functions, aliases, and variables that the script creates are added to the current scope.

. c:\scripts\sample.ps1

Note:

The dot sourcing operator is followed by a space. Use the space to distinguish the dot from the dot (.) symbol that represents the current directory.

Property dereferences operator: .

Accesses the properties and methods of an object.

$myProcess.peakWorkingSet
(Get-Process PowerShell).kill()

Range operator: ..

Represents the sequential integers in an integer array, given an upper, and lower boundary.

1..10
10..1
foreach ($a in 1..$max) {Write-Host $a}

Beginning in PowerShell 6,the range operator works with Characters as well as Integers.

To create a range of characters, enclose the boundary characters in quotes.

PS> ‘a’..’f’
a
b
c
d
e
f

Static member operator” ::

Calls the static properties operator and methods of a .NET Framework class. To find the static properties and methods of an object, use the Static parameter of the Get-Member cmdlet.

Subexpression operator: $( )

Returns the result of one or more statements. For a single result, returns a scalar. For multiple results, returns an array.

$($x * 23)
$(Get-WmiObject win32_Directory)

36
Q
A