📚 Table of Contents
- 💡 Unmasking PowerShell
- 🔑 Your First Step: Opening PowerShell
- 🧭 Navigating the Terrain: Interface Exploration
- 🥊 Basic Moves: Executing Simple Commands
- 🧱 Building Blocks: Scripting
- 🛡️ Adjusting Script Execution Policy
- 📦 Storage Boxes: Variables
- 🛠️ Power Tools: Functions
- 📚 Further Exploration: More Useful Cmdlets
💡 Unmasking PowerShell
PowerShell isn’t just another command-line shell. It’s a scripting superhero, born and bred by Microsoft. Its journey started in 2006, making Windows administration easier, but it has grown beyond its roots and become a cross-platform marvel, empowering admins on macOS and Linux as well.
Riding on the powerful .NET Framework, it can manipulate a vast array of system and application features. Whether you’re automating tasks, managing systems, or performing administrative feats, PowerShell is your go-to tool.
In this guide, we’ll start with the basics - opening the shell, exploring the interface, and executing your first commands. Then we’ll delve deeper into scripting, variables, and functions. This guide is suitable for novices, but also packs in advanced topics for the experienced users.
🔑 Your First Step: Opening PowerShell
For Windows users:
- Press the Windows key or click the Start button.
- Type “PowerShell” in the search bar.
- Click on “Windows PowerShell” in the search results.
For macOS and Linux users, you can install PowerShell by following the instructions on the official PowerShell GitHub repository.
🧭 Navigating the Terrain: Interface Exploration
When you first open PowerShell, you’ll see a command prompt displaying your current user and system information. It typically looks something like this:
powershell
PS C:UsersYourUsername>
To navigate the file system, you can use the following commands:
cd <directory>
: Change the current directory to the specified directory.dir
orls
: List the contents of the current directory.mkdir <directory>
: Create a new directory with the specified name.rmdir <directory>
: Remove the specified directory.
🥊 Basic Moves: Executing Simple Commands
PowerShell employs “cmdlets” (pronounced “command-lets”) to perform tasks. Cmdlets follow a Verb-Noun format, such as Get-ChildItem
or Set-Location
.
Here are some basic cmdlets to help you start:
Get-ChildItem
: List the contents of the current directory.Set-Location <directory>
: Change the current directory to the specified directory.Get-Content <file>
: Display the contents of the specified file.Copy-Item <source> <destination>
: Copy a file or directory from the source to the destination.Remove-Item <item>
: Delete the specified file or directory.
Pro Tip: Need help with a cmdlet? Use the Get-Help
cmdlet followed by the cmdlet name:
powershell
PS C:UsersYourUsername> Get-Help Get-ChildItem
The output provides a description of the cmdlet, the syntax, aliases, and other useful information:
powershell
PS C:UsersYourUsername> Get-Help Get-ChildItemNAMEGet-ChildItemSYNTAXGet-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes {ReadOnly | Hidden |System | Directory | Archive | Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}] [-FollowSymlink][-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]Get-ChildItem [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint32>] [-Force] [-Name] [-UseTransaction] [-Attributes {ReadOnly | Hidden |System | Directory | Archive | Device | Normal | Temporary | SparseFile | ReparsePoint | Compressed | Offline | NotContentIndexed | Encrypted | IntegrityStream | NoScrubData}] [-FollowSymlink][-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>]ALIASESgcilsdirREMARKSGet-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.-- To download and install Help files for the module that includes this cmdlet, use Update-Help.-- To view the Help topic for this cmdlet online, type: "Get-Help Get-ChildItem -Online" orgo to https://go.microsoft.com/fwlink/?LinkID=113308.
🧱 Building Blocks: Scripting
PowerShell scripts are files with a .ps1
extension that contain a series of cmdlets and other PowerShell code. To create a script, open a text editor, write your code, and save the file with a .ps1
extension.
For example, create a file called hello-world.ps1
with the following content:
powershell
Write-Host "Hello, World!"
In the image below, I’ve created a file called hello-world.ps1
, opened it in notepad and saved “Write-Host “Hello, World!” in the file.
To run the script, navigate to the directory containing the script and execute the following command:
powershell
PS C:UsersYourUsername>.\hello-world.ps1
🛡️ Adjusting Script Execution Policy
By default, PowerShell has a security measure in place known as the “execution policy” that controls how scripts are run. The default policy, “Restricted”, does not allow scripts to run.
To view the current execution policy, use this command:
powershell
C:UsersYourUsername> Get-ExecutionPolicy
If you need to run scripts from sources you trust, you might need to change this policy. However, be aware of the security implications. The “Unrestricted” policy allows all scripts to run, which can be dangerous if you’re not certain the scripts are safe.
To set the execution policy to “Unrestricted”, use this command:
powershell
C:UsersYourUsername> Set-ExecutionPolicy Unrestricted
This command will prompt you for confirmation before changing the policy. If you’re sure you want to proceed, type Y and press Enter.
Remember to only run scripts that you trust. When you’re done running scripts, consider setting the execution policy back to a safer level. This can be done with the Set-ExecutionPolicy command as well, replacing Unrestricted with the desired level, for example, Restricted or RemoteSigned.
📦 Storage Boxes: Variables
Variables in PowerShell are containers for storing data, identified with a $
symbol. Here’s how to create a variable:
powershell
PS C:UsersYourUsername> $variableName = "value"
For instance, to create a variable called greeting
with the value “Hello, World!”, use the following code:
powershell
PS C:UsersYourUsername> $greeting = "Hello, World!"PS C:UsersYourUsername> Write-Host $greeting# Result"Hello, World!"
🛠️ Power Tools: Functions
Functions in PowerShell are the tools of your scripting toolbox - reusable blocks of code that can be called with a specific name. Here’s the basic syntax for creating a function:
powershell
function FunctionName {# Your code here}
For example, create a function called PrintGreeting
that prints “Hello, World!“:
powershell
function PrintGreeting {Write-Host "Hello, World!"}PrintGreeting# Result'Hello, World!'
You can also pass parameters to functions using the param
keyword:
powershell
function PrintGreetingWithName {param($name)Write-Host "Hello, $name!"}PrintGreetingWithName -name "John"# Result'Hello, John!'
📚 Further Exploration: More Useful Cmdlets
Get-Command
: Retrieve a list of all available cmdlets and functions.Get-Process
: Get a list of running processes on the system.Stop-Process
: Terminate a running process.Get-Service
: Get a list of installed services on the system.Start-Service
: Start a stopped service.Stop-Service
: Stop a running service.Restart-Service
: Restart a running service.New-Item
: Create a new file or directory.Rename-Item
: Rename a file or directory.Move-Item
: Move a file or directory to a new location.Get-Date
: Display the current date and time.Set-Date
: Set the system date and time.Get-History
: Get a list of previously executed commands.Clear-History
: Clear the command history.Invoke-WebRequest
: Send an HTTP or HTTPS request to a web page and parse the response.ConvertTo-Json
: Convert an object to a JSON-formatted string.ConvertFrom-Json
: Convert a JSON-formatted string to a custom object.Export-Csv
: Export data as a comma-separated values (CSV) file.Import-Csv
: Import data from a CSV file.Select-Object
: Select specific properties from an object or set of objects.Where-Object
: Filter objects based on a specific condition.ForEach-Object
: Perform an action on each item in a collection.Sort-Object
: Sort objects by property values.Measure-Object
: Calculate the numeric properties of objects.
Congratulations Fellow Nomad!
You’ve just taken your first steps into the fascinating world of PowerShell scripting. With this foundation, you can go on to automate tasks, manage systems, and make your daily computer life significantly easier. Remember, practice makes perfect, so don’t be afraid to experiment, explore, and build your scripting prowess. The sky is the limit!