A2oz

How to Print a Variable in PowerShell?

Published in PowerShell 1 min read

You can print a variable's value in PowerShell using the Write-Host cmdlet. This cmdlet displays the output to the console.

Example:

$myVariable = "Hello, World!"
Write-Host $myVariable

This code snippet first assigns the string "Hello, World!" to the variable $myVariable. Then, Write-Host $myVariable displays the value stored in $myVariable to the console.

Other Ways to Print Variables:

  • Echo: The echo command is a shortcut for Write-Host. You can use it like this: echo $myVariable.
  • Write-Output: This cmdlet outputs the value of a variable to the pipeline, which can be used in other commands. For example: Write-Output $myVariable | Out-File -FilePath output.txt. This writes the value of $myVariable to a file named "output.txt".

Conclusion:

PowerShell provides several ways to print variables, each with its own purpose and application. Write-Host is the simplest and most commonly used method for displaying output to the console.

Related Articles