Why do we need a variable?
Variable is a storage place for data. In PowerShell we can store almost anything, from strings to Objects.
How do you define a Variable?
To define a variable just prefix $ to any sequence of characters. PowerShell variables are not case sensitive. Variable can have any thing, starting from (A-Z) and (0-9) and (_).
There is no length restriction to the variable name but it is always good to follow the same naming conventions, which we use in .Net or in T-SQL programming languages.
Built-in Variables
When PowerShell is started, a number of variables are defined and assigned the environmental values.
PS H:\> set-location variable:
PS Variable:\> get-childitem
There are two types of built-in variables. One type of variable stores the configuration information for the current session and another type of variable stores the personal preferences.
Make your life easy with Alias
Alias makes the life very easy. PowerShell has alias names for most of its commands. So you don’t have to remember the complete command to use. You can use the alias to perform the same operation.
Get-process is the command to get all the processes on your machine and the alias for this is gps.
To get all the aliases just use get-alias method.
Working with alias
Several alias cmdlets enable you to define new aliases, export aliases, import aliases and display existing aliases. By using the following command, you can get a list of all related alias cmdlets.
Export and Import aliases are to export and import the aliases from different sessions. Get-Alias is to get the all aliases. New and Set Aliases are to define new aliases with in current session. If you want to persist your aliases then you need to set these things in profile.ps1.
One thing to remember is you can’t use predefined alias names to your own commands.
If you try to do that then you will get below error.
PS Variable:\> set-alias gps pwd
Set-Alias : Alias is not writeable because alias gps is read-only or constant and cannot be written to.
Scope of variables
Scope is a logical boundary in PowerShell. Scopes can be defined as global, local, script, and private.
Global scope applies to an entire PowerShell instance. These variables can’t be shared between the sessions. To declare these kinds of variables just prefix the $Global: to the variable.
Local scope variables are declared inside the function. Once the processing is completed you can’t access this variable.
Script scope variables are declared inside the script. The lifetime of this variable is as long as the script is running.
Private scope is similar to Local but only difference is this value can’t be inherited. To declare these kinds of variables just prefix the $Private: to the variable.
No comments:
Post a Comment