
close
close
In a previous article, I introduced you to PowerShell variables. With variables, you can easily define a variable to store a piece of information or to hold the contents of a command. This latter idea is very important. If you have a PowerShell expression that takes a bit of time to run, and you want to try different things with the results, you don’t want to be re-running the command. Instead, define a variable.
$Scripts = dir c:\scripts\*.ps1 –Recurse
Now I can use the variable, Scripts, as much as I want without having to re-run the directory listing.
Using a PowerShell variable (Image Credit: Jeff Hicks)
advertisment
$scripts = dir c:\scripts\ -Recurse –file
This is why I suggest using meaningful variable names instead of something like X or VAR. On a related note, you can also run into situations like this where you tell PowerShell to turn something into a specific type of object.
Defining a variable type (Image Credit: Jeff Hicks)
The problem with a typed variable (Image Credit: Jeff Hicks)
Re-typing the variable (Image Credit: Jeff Hicks)
If you need to keep track of what variables you’ve defined, you can use the Get-Variable cmdlet. Remember, variables only exist for as long as your PowerShell session is running. Once you close PowerShell, the variables go away.
Getting all variables (Image Credit: Jeff Hicks)
Getting a single variable (Image Credit: Jeff Hicks)
Clearing a variable (Image Credit: Jeff Hicks)
Removing a variable (Image Credit: Jeff Hicks)
Errors with non-existent variables (image Credit: Jeff Hicks)
New-Variable Options (Image Credit: Jeff Hicks)
Creating a read-only variable (Image Credit: Jeff Hicks)
More from Jeff Hicks
advertisment
Petri Newsletters
Whether it’s Security or Cloud Computing, we have the know-how for you. Sign up for our newsletters here.
advertisment
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri
Log in to save content to your profile.
Article saved!
Access saved content from your profile page. View Saved
Join The Conversation
Create a free account today to participate in forum conversations, comment on posts and more.
Copyright ©2019 BWW Media Group