powershell basics Flashcards
(36 cards)
What are Execution policy?
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.
What execution policies are available in Powershell?
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.
What is the Scope of the execution policy in Powershell?
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
What are the execution policy precedence?
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
What is the difference between set-variable & new-variable cmdlets in Powershell?
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.
What are variables in Powershell?
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
Are variable names in Powershell case sensitive?
Variable names are not case-sensitive. Variable names can include spaces and special characters, but these are difficult to use and should be avoided.
What are the different types of variables in Powershell?
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 do you delete the value of a variable in powershell?
how do you delete the variable in Powershell?
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 do you get the list of all variables in a Powershell session?
To get a list of all the variables in your PowerShell session, type:
Get-Variable
How can you ensure that a variable can contain only objects of the specified type or objects that can be converted to that type?
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 do you use variables in commands and expressions?
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 to use variables that include special characters?
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
What are the scope of variables in Powershell?
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 do you ensure that a variable exists in every powershell session that you create?
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"
what is a VARIABLE: Drive?
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
What are the various cmdlets in powershell to manage variables?
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.
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’
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.
How do you avoid resolving a variable inside double quotes?
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”
What is the Read-Host cmdlet?
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"
What are Here-strings in Powershell?
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
What are the Data types in Powershell?
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.
What are automatic Variables in Powershell?
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.
What are the types of Comparison operators in Powershell?
Powershell has the following types of comparison operators
- Equality
- Matching
- Containment
- Replacement
- Type
$
character before the group identifier.