Variables In PowerShell
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have discussed what is PowerShell and how to get started with PowerShell.
https://cloudaffaire.com/getting-started-with-powershell/
In this blog post, we will discuss variables in PowerShell. Like any other scripting language, PowerShell also supports variables. Variable in a nutshell is a temporary space to store some value. In PowerShell, you can store different data types as a variable value. Variables can be user-defined or system-defined and the scope of the variables can be local or global.
A variable is defined as $<variable_name> = <variable_value> and variable value can be retrieved using $<variable_name>. Variable names aren’t case-sensitive, and can include spaces and special characters. But variable names that include special characters and spaces are difficult to use and should be avoided.
Variables In PowerShell:
You can define a new variable using $<variable_name> = <variable_value> syntax. You don’t need to explicitly define variable data type as PowerShell automatically determines the variable data type based on the assigned value. Variable can be reassigned a different value based on the requirement. To get all variables available in current session you can use cmdlet Get-Variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
############################ ## PowerShell | Variables ## ############################ ## PowerShell latest version (5) ## ------------------------------------ ## variable assignment and manipulation ## ------------------------------------ $myvar = "hello world" $a = 10 $b = 6 $myvar ## returns "hello world" $c = $a + $b; $c ## returns 16 $a += $c; $a ## returns 26 $myvar = $null; $myvar ## returns empty |
PowerShell Variables Data Type:
PowerShell variables are loosely typed, which means that they aren’t limited to a particular type of object. A single variable can contain integers, strings, characters, arrays, hash tables or a collection of different types of objects etc. You can get the a variable data type using GetType() in-built function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
## ------------------ ## variable data type ## ------------------ ## char $mycharecter = [char]0x0061 ## type casting $mycharecter ## returns "a" $mycharecter.GetType().FullName ## returns "System.Char" ## string $mystring = "hello world" $mystring ## returns "hello world" $mystring.GetType().FullName ## returns "System.String" ## int $myinteger = 100 $myinteger ## returns 100 $myinteger.GetType().FullName ## returns "System.Int32" ## long $mylong = 1000000000000000 $mylong ## returns 1000000000000000 $mylong.GetType().FullName ## returns "System.Int64" ## decimal $mydecimal = 1234567.1234567d ## 'd' stands for decimal $mydecimal ## returns 1234567.1234567 $mydecimal.GetType().FullName ## returns "System.Decimal" ## double $mydouble = [double]$mydecimal ## type casting $mydouble ## returns 1234567.1234567 $mydouble.GetType().FullName ## returns "System.Double" ## single $mysingle = [single]$mydouble $mysingle ## returns 1234567 $mysingle.GetType().FullName ## returns "System.Single" ## bool $mybool = $true $mybool ## returns "True" $mybool.GetType().FullName ## returns "System.Boolean" ## datetime $mydate = Get-Date $mydate ## returns "18 July 2020 20:00:56" $mydate.GetType().FullName ## returns "System.DateTime" ## hash table $myhashtable = @{1="one"; 2="two"} $myhashtable ## returns a table $myhashtable.GetType().FullName ## returns "System.Collections.Hashtable" ## array $myarray = @("one", "two", "three") $myarray ## returns "one", "two", "three" $myarray[0] ## returns "one" $myarray.GetType().FullName ## returns "System.Object[]" ## objects $myobject = Get-Process $myobject ## returns output of Get-Process $myobject.GetType().FullName ## returns "System.Object[]" |
PowerShell Variable Typecasting:
You can use a type attribute and cast notation to ensure that a variable can contain only specific object types 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 the type can’t be converted, 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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
## ----------------------------------- ## variable conversion or type casting ## ----------------------------------- ## explicit type casting $mystr = "10" $myint = 10 $myvar = $mystr + $myint; $myvar ## returns 1010 $myvar = [int]$mystr + $myint; $myvar ## returns 20 ## implicit type casting $myint1 = 10; $myint1.GetType().FullName ## returns "System.Int32" $myint2 = 3; $myint2.GetType().FullName ## returns "System.Int32" $myvar1 = $myint1 / $myint2; $myvar1 ## returns 3.33333333333333 $myvar1.GetType().FullName ## returns "System.Double" ## some type casting not allowed $mystr = "ten" $myvar = [int]$mystr + $myint; $myvar ## returns Cannot convert value "ten" to type "System.Int32" |
PowerShell Variable Scope:
A variable can have different scope based on the variable declaration method used and by default, variables are only available in the scope in which they’re 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. If you dot-source the script, the variable is added to the current scope. You can use a scope modifier to change the default scope of the variable. Below is the different scope available in PowerShell –
- Global: The scope that is in effect when PowerShell starts. Variables and functions that are present when PowerShell starts have been created in the global scope, such as automatic variables and preference variables. The variables, aliases, and functions in your PowerShell profiles are also created in the global scope.
- Local: The current scope. The local scope can be the global scope or any other scope.
- Script: The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope.
- Private: Private is not a scope. It is an option that changes the visibility of an item outside of the scope where the item is defined.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
## -------------- ## variable scope ## -------------- ## local variable $myvar1 = "old" ## decalre a new variable myvar1 $myvar1 ## returns "old" ## create a function Function myfun1() { $myvar1 ## myvar1 available inside finction $myvar2 = "new" ## decalre a new variable myvar2 $myvar2 ## myvar2 available inside function } ## call the function myfun1 ## returns "old" & "new" $myvar1 ## returns "old" $myvar2 ## returns empty as myvar2 is not available outside function Invoke-Command -ScriptBlock {$myvar1; $myvar2 = "new"; $myvar2} ## returns "old" & "new" $myvar1 ## returns "old" $myvar2 ## returns empty as myvar2 is not available outside function ## private variable Remove-Variable -Name "myvar1" $private:myvar1 = "one" ## decalre a new variable myvar1 $myvar1 ## returns "one" ## create a function Function myfun2() { $myvar1 ## myvar1 is not available inside finction $myvar2 = "two" ## decalre a new variable myvar2 $myvar2 ## myvar2 available inside function } ## call the function myfun2 ## returns "two" $myvar1 ## returns "one" $myvar2 ## returns empty as myvar2 is not available outside function Invoke-Command -ScriptBlock {$myvar1; $myvar2 = "two"; $myvar2} ## returns "two" $myvar1 ## returns "one" $myvar2 ## returns empty as myvar2 is not available outside function ## global variable Remove-Variable -Name "myvar1" $global:myvar1 = "a" ## decalre a new variable myvar1 $myvar1 ## returns "a" ## create a function Function myfun3() { $myvar1 ## myvar1 is not available inside finction $global:myvar2 = "b" ## decalre a new variable myvar2 $myvar2 ## myvar2 available inside function } ## call the function myfun3 ## returns "a" & "b" $myvar1 ## returns "a" $myvar2 ## returns "b" Invoke-Command -ScriptBlock {$myvar1; $global:myvar2 = "c"; $myvar2} ## returns "a" & "c" $myvar1 ## returns "a" $myvar2 ## returns "c" ## exit PowerShell and open again $myvar1 ## returns empty $myvar2 ## returns empty ## system wide variable notepad $PROFILE ## declare a new variable in PowerShell profile file $myvar3 = "old" $myvar1 ## returns empty $myvar2 ## returns empty $myvar3 ## returns old |
PowerShell Variable Types:
A variable can be user defined or generated by the system itself. Below are different types of variables available 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. When the PowerShell windows is closed, the variables are deleted. 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 can’t 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
## -------------- ## variable types ## -------------- ## user defined variables $myvar = "debjeet" ## automatic variables $$ ## Contains the last token in the last line received by the session $? ## Contains the execution status of the last command $^ ## Contains the first token in the last line received by the session. $_ ## Contains the current object in the pipeline object. $args ## Contains an array of values for undeclared parameters that are passed to a function, script, or script block. $ConsoleFileName ## Contains the path of the console file (.psc1) that was most recently used in the session. $Error ## Contains an array of error objects that represent the most recent errors. $Event ## Contains a PSEventArgs object that represents the event that is being processed $EventArgs ## Contains an object that represents the first event argument that derives from EventArgs of the event that is being processed. $EventSubscriber ## Contains a PSEventSubscriber object that represents the event subscriber of the event that is being processed. $ExecutionContext ## Contains an EngineIntrinsics object that represents the execution context of the PowerShell host. $false ## Contains False. You can use this variable to represent False in commands and scripts instead of using the string "false". $foreach ## Contains the enumerator (not the resulting values) of a ForEach loop. $HOME ## Contains the full path of the user's home directory. $Host ## Contains an object that represents the current host application for PowerShell. $input ## Contains an enumerator that enumerates all input that is passed to a function. $IsCoreCLR ## Contains $True if the current session is running on the .NET Core Runtime (CoreCLR). $IsLinux ## Contains $True if the current session is running on a Linux operating system. $IsMacOS ## Contains $True if the current session is running on a MacOS operating system. $IsWindows ## Contains $TRUE if the current session is running on a Windows operating system. $LastExitCode ## Contains the exit code of the last Windows-based program that was run. $Matches ## The Matches variable works with the -match and -notmatch operators. $MyInvocation ## Contains information about the current command, such as the name, parameters, parameter values $NestedPromptLevel ## Contains the current prompt level. $null ## Contains a null or empty value. $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. $PSBoundParameters ## Contains a dictionary of the parameters that are passed to a script or function and their current values. $PSCmdlet ## Contains an object that represents the cmdlet or advanced function that's being run. $PSCommandPath ## Contains the full path and file name of the script that's being run. $PSDebugContext ## Contains information about the debugging environment while debugging. $PSHOME ## Contains the full path of the installation directory for PowerShell $PSItem ## Contains the current object in the pipeline object. Same as $_. $PSScriptRoot ## Contains the directory from which a script is being run. $PSSenderInfo ## Contains information about the user who started the PSSession, including the user identity and the time zone of the originating computer. $PSUICulture ## Contains the name of the user interface (UI) culture that's currently in use in the operating system. $PSVersionTable ## Contains a read-only hash table that displays details about the version of PowerShell $PWD ## Contains a path object that represents the full path of the current directory. $Sender ## Contains the object that generated this event. $ShellId ## Contains the identifier of the current shell. $StackTrace ## Contains a stack trace for the most recent error. $switch ## Contains the enumerator not the resulting values of a Switch statement. $this ## In a script block that defines a script property or script method, the $this variable refers to the object that is being extended. $true ## Contains True. You can use this variable to represent True in commands and scripts. ## preference variables $ConfirmPreference ## Determines whether PowerShell automatically prompts you for confirmation before running a cmdlet or function. $DebugPreference ## Determines how PowerShell responds to debugging messages generated by a script, cmdlet or provider, or by a Write-Debug command at the command line. $ErrorActionPreference ## Determines how PowerShell responds to a non-terminating error, an error that doesn't stop the cmdlet processing. $ErrorView ## Determines the display format of error messages in PowerShell. $FormatEnumerationLimit ## Determines how many enumerated items are included in a display. $InformationPreference ## The $InformationPreference variable lets you set information stream preferences that you want displayed to users. $Log*Event ## The Log*Event preference variables determine which types of events are written to the PowerShell event log in Event Viewer. $MaximumHistoryCount ## Determines how many commands are saved in the command history for the current session. $OFS ## The Output Field Separator (OFS) specifies the character that separates the elements of an array that is converted to a string. $OutputEncoding ## Determines the character encoding method that PowerShell uses when it sends text to other applications. $ProgressPreference ## Determines how PowerShell responds to progress updates generated by a script, cmdlet, or provider $PSEmailServer ## Specifies the default e-mail server that is used to send email messages. $PSDefaultParameterValues ## Specifies default values for the parameters of cmdlets and advanced functions. $PSModuleAutoloadingPreference ## Enables and disables automatic importing of modules in the session. $PSSessionApplicationName ## Specifies the default application name for a remote command that uses Web Services for Management (WS-Management) technology. $PSSessionConfigurationName ## Specifies the default session configuration that is used for PSSessions created in the current session. $PSSessionOption ## Establishes the default values for advanced user options in a remote session. $Transcript ## Used by Start-Transcript to specify the name and location of the transcript file. $VerbosePreference ## Determines how PowerShell responds to verbose messages generated by a script, cmdlet, or provider $WarningPreference ## Determines how PowerShell responds to warning messages generated by a script, cmdlet, or provider $WhatIfPreference ## Determines whether WhatIf is automatically enabled for every command that supports it. |
PowerShell Variable cmdlets:
PowerShell includes a set of cmdlets that are designed to manage variables. Below is the list of available cmdlets
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
## ---------------- ## variable cmdlets ## ---------------- ## get all cmdlets for variable manupulation Get-Command -Noun Variable ## create a new variable using cmdlet New-Variable myvar $myvar ## returns empty as no value is assigned ## assign value to the variable Set-Variable -Name "myvar" -Value "debjeet" $myvar ## returns "debjeet" ## get variable details Get-Variable | Where-Object {$_.Name -eq "myvar"} ## clear variable value Clear-Variable -Name "myvar" $myvar ## returns empty Get-Variable | Where-Object {$_.Name -eq "myvar"} ## delete variable Remove-Variable -Name "myvar" $myvar Get-Variable | Where-Object {$_.Name -eq "myvar"} |
Hope you have enjoyed this article. In the next blog post, we will discuss operators in PowerShell.
To get more details on PowerShell, kindly follow below official documentation