Tuesday, February 13, 2024

#101 : Variables in Powershell

 In PowerShell, variables are used to store data that can be referenced and manipulated throughout your script. 

Variable Declaration in Powershell:

Variables in PowerShell do not require explicit declaration of data types. You can simply assign a value to a variable using the $ symbol followed by the variable name.

$myVariable = "Hello, World!"

Variable Naming Convention:
PowerShell variable names are not case-sensitive, but it's a good practice to use camelCase or PascalCase for readability.

Variable Data Types:
PowerShell variables can hold various types of data, including strings, numbers, arrays, and objects.

Accessing Variables:
You can access the value of a variable by simply referencing its name preceded by the $ symbol.

Example: 

Write-Output $myVariable

What is scope of variable?
PowerShell variables can have different scopes, such as
1. Script scope
2. Global scope
3. Function scope
4. Local scope.

The default scope for variables is the script scope. You can specify the scope using the appropriate scope modifier ($script:, $global:, $local:, etc.).

Example:

$globalVariable = "I'm a global variable"

function Test-Scope {

    $localVariable = "I'm a local variable"

    Write-Output $globalVariable

    Write-Output $localVariable

}

Test-Scope


Variable Expansion:

PowerShell supports variable expansion within strings enclosed in double quotes, allowing you to include variable values directly within a string.

Example:

$name = "John"
Write-Output "Hello, $name!"

Automatic Variables:
PowerShell also provides a set of automatic variables that store various system and environment information, such as $PSVersionTable, $PID, $HOME, etc.

Variable Manipulation:
You can manipulate variables using various operators and methods, such as assignment (=), addition (+=), subtraction (-=), multiplication (*=), division (/=), and so on.

$num = 5

$num += 10

Write-Output $num  # Output: 15

These are some of the fundamental concepts related to variables in PowerShell. As you become more familiar with PowerShell scripting, you'll discover additional techniques and best practices for working with variables effectively.

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...