LOGO

Geek School: PowerShell Variables, Input & Output - Learn PowerShell

April 10, 2013
Geek School: PowerShell Variables, Input & Output - Learn PowerShell

The Role of Variables in PowerShell Scripting

Transitioning from executing individual commands to developing complete scripts necessitates a method for temporary data storage. Variables fulfill this crucial function within PowerShell.

Prerequisites: Previous Articles in the Series

To ensure a comprehensive understanding, it is recommended to review the preceding articles in this series before proceeding.

  • Learn How to Automate Windows with PowerShell
  • Learning to Use Cmdlets in PowerShell
  • Learning How to Use Objects in PowerShell
  • Learning Formatting, Filtering and Comparing in PowerShell
  • Learn to Use Remoting in PowerShell
  • Using PowerShell to Get Computer Information
  • Working with Collections in PowerShell

These articles provide foundational knowledge essential for grasping the concepts discussed here.

Further installments of this series will be published throughout the week, offering continued insights into PowerShell scripting.

Variables in PowerShell

Within the realm of programming, variables serve as fundamental containers for storing values. PowerShell is no exception, offering a straightforward method for utilizing these essential elements. Let's illustrate how to define a variable named “FirstName” and assign it the value “Taylor”.

$FirstName = “Taylor”

A common inquiry arises regarding the purpose of the dollar sign preceding the variable name. This is a valid question. The dollar sign functions as an indicator to the shell, signaling that we intend to access the variable's content—what it holds—rather than the variable itself.

It’s important to note that in PowerShell, variable names are defined without the dollar sign. Therefore, in the preceding example, the variable’s actual name is “FirstName”.

Accessing and Removing Variables

PowerShell organizes all created variables within the 'variable' PSDrive, allowing for easy access.

gci variable:

Consequently, variables can be removed from the shell environment at any time using the following command:

Remove-Item Variable:\FirstName

Storing Multiple Objects

Variables aren't limited to holding single values. They can equally accommodate multiple objects. For instance, to store a list of currently running processes, you can assign the output of the 'Get-Process' cmdlet to a variable.

$Proc = Get-Process

Understanding this concept hinges on recognizing that the expression on the right side of the equals sign is always evaluated first. This allows for complex pipelines to be used for assignment.

$CPUHogs = Get-Process | Sort CPU -Descending | select -First 3

The $CPUHogs variable will now contain the three processes consuming the most CPU resources.

geek-school-learning-powershell-variables-input-and-output-1.jpg

Working with Collections of Objects

When a variable contains a collection of objects, specific behaviors should be considered. Applying a method to the variable will execute that method on each object within the collection.

$CPUHogs.Kill()

This command would terminate all three processes stored in the $CPUHogs collection. To access a specific object within the variable, treat it as an array.

$CPUHogs[0]

This will retrieve the first object from the collection.

geek-school-learning-powershell-variables-input-and-output-2.jpg
geek-school-learning-powershell-variables-input-and-output-3.jpg

Avoiding Common PowerShell Pitfalls

PowerShell variables are, by default, loosely typed. This characteristic frequently surprises individuals new to the scripting environment.

Consider the following variable assignments:

$a = 10

$b = ‘20’

Here, we define two variables: one holding a numerical value and the other a string. The outcome of adding these variables is dependent on the order of operations.

$a + $b = 30

Conversely:

$b + $a = 2010

In the initial instance, because the first operand, $a, is an integer, PowerShell interprets the operation as arithmetic. Consequently, it attempts to convert subsequent operands into integers as well.

However, when the string variable, $b, is the first operand, PowerShell treats the operation as string concatenation, converting all operands to strings.

Experienced PowerShell developers mitigate these potential issues by explicitly casting variables to their expected data types.

[int]$Number = 5

[int]$Number = ‘5’

Both of these statements will result in the variable $Number containing an integer object with a value of 5.

Understanding Type Casting

Type casting ensures that variables are treated as the intended data type, preventing unexpected behavior during operations.

This practice is crucial for writing robust and predictable PowerShell scripts.

  • Explicitly defining variable types enhances code clarity.
  • It minimizes the risk of runtime errors caused by implicit type conversions.
  • Consistent type handling improves script maintainability.

By proactively managing variable types, developers can avoid common pitfalls and create more reliable PowerShell solutions.

Gathering User Input and Displaying Results

PowerShell's primary function is task automation, therefore minimizing user prompts is generally recommended. However, situations arise where user input becomes necessary. For these instances, the Read-Host cmdlet provides a straightforward solution.

Utilizing Read-Host

The cmdlet is remarkably easy to implement. A simple command allows you to request information from the user and store it within a variable.

For example:

$FirstName = Read-Host –Prompt ‘Enter your first name’

The value entered by the user will then be assigned to the specified variable, in this case, $FirstName.

geek-school-learning-powershell-variables-input-and-output-4.jpg

Presenting Information with Write-Output

Displaying information to the user is equally simple, achieved through the Write-Output cmdlet. This cmdlet allows you to present text or variable contents on the console.

Consider this example:

Write-Output “How-To Geek Rocks!”

This command will display the text "How-To Geek Rocks!" to the user.

geek-school-learning-powershell-variables-input-and-output-6.jpg

We will continue our exploration tomorrow by integrating these concepts into a comprehensive example.

#PowerShell#variables#input#output#scripting#Geek School