PowerShell variables
PowerShell variables are also somewhat like variables in other languages.
Variables are unit of memory used to store values. PowerShell variables start with “$” e.g. $testvar
Variable name can be any number, alphabet or even include underscore. These are also not case sensitive.
From this session we will use another tool called PowerShell ISE(Integrated Scripting Environment). This tool has the PowerShell script editor and the debug console.
Step 1) Search for ISE in Windows. Select and Click
Step 2) PowerShell ISE Window Opens
Below example shows,
1. how you can create a variable.
2. Assign it some value
3. Get its value to display
Write-host used to write value to host.
Remember Get-Help command from previous article on Basic PowerShell commands, you can use that to get more info on this
Get-Help Write-Host
OR
Get-Help Write-Host -online
If you want to change value of variable. Use “=“ to assign different value.
Want to delete variable :
Clear-variable -Name testvar
PowerShell variables are loosely typed, which means that they aren't limited to a particular data type. A single variable can even contain a collection, or array, of different types of objects at the same time.
In line 8, integer value assigned to $testvar.
We can use Get-Member for that. Let me show you.
$testvar | Get-Member
$testvar | Get-Member
Returned data type of value stored in variable which is String
Can we force variable to contain value of particular data type?
Enter the type name, enclosed in brackets, before the variable name to do that.
[int] cast $testvar to store only integer values.
When you try to assigned some string. It try to convert that value into integer first.
You can verify it using Get-Member
If you try to assign some value which can not be converted into integer, error will be thrown. As we have created variable which can store only integer value.
How to use these variables in commands?
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 aren't enclosed in quotation marks, or if they're 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.
Comments
Post a Comment