The Beginner’s Guide to PowerShell Scripting
If you’re an IT professional, chances are you’ve heard of PowerShell scripting and know the advantages it offers over the traditional command prompt. But what exactly is PowerShell? Where did it come from? Why should you care? And how can you use it to streamline your day-to-day administrative tasks? This beginner’s guide answers all these questions and more!
What Is PowerShell?
PowerShell is a cross-platform command-line shell and scripting language designed for system administration and automation. Windows system administrators are already familiar with the program because it is included in every copy of Windows since 2008. While the syntax differs from traditional shells like cmd.exe, the benefit of learning it far outweighs any extra time it takes to learn some new syntax.
Getting Started with Windows PowerShell 4.0
Windows PowerShell 4.0 includes a number of new features and enhancements to existing cmdlets and language elements. Windows PowerShell 4.0 is available on Windows 7 SP1 and higher, Windows Server 2008 R2 SP1 and higher, including Datacenter editions, Windows 8, Windows 8.1, Windows Server 2012 R2, including Essentials editions; these are all 64-bit versions of the operating system.
Writing Your First Powershell Script
There are two basic things that you need to know before beginning to write scripts: syntax and commands. The syntax defines how a command is structured and in what order it should be included in a script. For example, you may have a list of files and folders on your computer, but they are not organized in any particular way; when you try to open one, the screen displays all of the contents of the folder at once. If you wanted your computer to show only files with extensions pptx or xlsx, then you would use the following syntax: dir *.pptx*.xlsx /s.
Basic Syntax Reference
Here are some basic syntax tips for scripts in PowerShell:
- A comment is any text between the pound signs that does not affect the operation of the command.
- The redirection operator sends output from a command into a file. Example: Out-File.
- To redirect standard output (like console windows) enter > in front of your filename or even use Out-Default. Example: get-process out-default.
Creating User Defined Variables in Powershell
A variable is a name that corresponds to a value that may change. The type of the variable determines the information it can hold and what operations can be performed on it. Using variables simplifies coding by giving you a way to abstract commonly used information as well as represent changing values. Variables are declared with either Global or Local scope, which determines whether they are available from all places in your script or only where they’re created.