powershell basics Flashcards
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"