PowerShell has emerged as a powerful alternative when it comes to executing commands on Windows, providing enthusiasts with more options than the traditional Windows command line, which had limited capabilities for years.
PowerShell, equipped with its unique programming language resembling Perl, provides its own command-line interface. Initially developed to handle object management on users’ computers, PowerShell has evolved into a comprehensive environment for executing and automating system management tasks. This versatile platform allows users to access various resources, ranging from Active Directory to Exchange Server, all within a single program.
Thanks to its open-source nature, PowerShell is now accessible to Linux and Unix-based users as well. Its primary purpose remains aiding users in automating administrative tasks, relieving them from tedious and repetitive work. By creating scripts and issuing commands, users can leverage PowerShell’s automatic completion feature to swiftly accomplish their desired tasks. Furthermore, PowerShell allows extensive customization with hundreds of commands, known as cmdlets, at the user’s disposal.
The Basic 25
With further fuss, here are 25 basic PowerShell commands that you need to know. Buckle up, though. Below this simple table is a more in-depth explanation of each command. This is going to be a looong post!
Command name | Alias | Description |
---|---|---|
Set-Location | cd, chdir, sl | Sets the current working location to a specified location. |
Get-Content | cat, gc, type | Gets the content of the item at the specified location. |
Add-Content | ac | Adds content to the specified items, such as adding words to a file. |
Set-Content | sc | Writes or replaces the content in an item with new content. |
Copy-Item | copy, cp, cpi | Copies an item from one location to another. |
Remove-Item | del, erase, rd, ri, rm, rmdir | Deletes the specified items. |
Move-Item | mi, move, mv | Moves an item from one location to another. |
Set-Item | si | Changes the value of an item to the value specified in the command. |
New-Item | ni | Creates a new item. |
Start-Job | sajb | Starts a Windows PowerShell background job. |
Compare-Object | compare, dif | Compares two sets of objects. |
Group-Object | group | Groups objects that contain the same value for specified properties. |
Invoke-WebRequest | curl, iwr, wget | Gets content from a web page on the Internet. |
Measure-Object | measure | Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files. |
Resolve-Path | rvpa | Resolves the wildcard characters in a path, and displays the path contents. |
Resume-Job | rujb | Restarts a suspended job |
Set-Variable | set, sv | Sets the value of a variable. Creates the variable if one with the requested name does not exist. |
Show-Command | shcm | Creates Windows PowerShell commands in a graphical command window. |
Sort-Object | sort | Sorts objects by property values. |
Start-Service | sasv | Starts one or more stopped services. |
Start-Process | saps, start | Starts one or more processes on the local computer. |
Suspend-Job | sujb | Temporarily stops workflow jobs. |
Wait-Job | wjb | Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are completed. |
Where-Object | ?, where | Selects objects from a collection based on their property values. |
Write-Output | echo, write | Sends the specified objects to the next command in the pipeline. |
Examples
Below, I’ve listed examples of use for each of the above commands.
Set-Location
The Set-Location cmdlet in PowerShell is used to change the current location (working directory) in the PowerShell session. Here’s an example:
Let’s say you want to navigate to the “Documents” folder on your computer. You can use the Set-Location cmdlet to accomplish this. Open PowerShell and enter the following command:
Set-Location -Path "C:\Users\YourUsername\Documents"
Replace “YourUsername” with your actual username. This command will change the current location to the specified path, which in this case is the “Documents” folder. After executing the command, you should see the prompt reflecting the new location.
You can also use relative paths to navigate to a folder within the current directory. For example, if you are currently in the “C:\Users\YourUsername” directory and want to navigate to the “Downloads” folder within it, you can use the following command:
Set-Location -Path ".\Downloads"
The .\ represents the current directory, so this command will change the location to the “Downloads” folder within the current directory.
These examples demonstrate how you can use the Set-Location cmdlet to navigate to different folders within your file system using PowerShell.
Get-Content
The Get-Content cmdlet in PowerShell is used to read the content of a file and return it as an object in PowerShell. Here’s an example:
Let’s say you have a text file named “example.txt” with the following content:
Hello, world!
This is an example file.
To read the content of this file using Get-Content, open PowerShell and enter the following command:
Get-Content -Path "C:\path\to\example.txt"
Replace “C:\path\to\example.txt” with the actual path to your file. This command will read the content of the file and display it in the PowerShell console.
If you want to store the content of the file in a variable for further manipulation, you can do so by assigning the result of Get-Content to a variable. Here’s an example:
$content = Get-Content -Path "C:\path\to\example.txt"
Now, the variable $content will contain the content of the file. You can perform various operations on this variable, such as displaying specific lines, searching for specific patterns, or processing the content in any other way you require.
The Get-Content cmdlet is useful for reading and working with the content of files within PowerShell scripts or interactive sessions. It provides flexibility in accessing and manipulating file content using the power of PowerShell.
Add-Content
The Add-Content cmdlet in PowerShell is used to append content to a file. It allows you to add new lines or data to the end of an existing file. Here’s an example:
Let’s say you have a text file named “example.txt” with the following content:
Line 1
Line 2
To append a new line to this file using Add-Content, open PowerShell and enter the following command:
Add-Content -Path "C:\path\to\example.txt" -Value "Line 3"
Replace “C:\path\to\example.txt” with the actual path to your file. This command will add a new line with the value “Line 3” to the end of the file.
If the file doesn’t exist at the specified path, Add-Content will create a new file with the given content.
You can also append multiple lines or content from a variable. Here’s an example:
$content = "This is a new line.`nThis is another line."
Add-Content -Path "C:\path\to\example.txt" -Value $content
In this example, the variable $content contains multiple lines of text. The -Value parameter is used to specify the content to be appended to the file.
After executing the command, the file will have the following content:
Line 1
Line 2
This is a new line.
This is another line.
The Add-Content cmdlet is useful for appending data to files within PowerShell scripts or interactive sessions. It allows you to easily extend the content of existing files without overwriting their previous content.
Set-Content
The Set-Content cmdlet in PowerShell is used to replace the content of a file with new content. It allows you to overwrite the existing content of a file or create a new file with the specified content. Here’s an example:
Let’s say you want to create a new text file named “example.txt” with the following content:
This is line 1.
This is line 2.
To create or replace the content of this file using Set-Content, open PowerShell and enter the following command:
Set-Content -Path "C:\path\to\example.txt" -Value "This is line 1. `r`n This is line 2."
Replace “C:\path\to\example.txt” with the desired path and filename for your file. This command will create a new file or replace the existing file at the specified path with the provided content.
The -Value parameter is used to specify the content to be written to the file. In this example, the content is a string containing the desired lines, with `r`n representing a line break (carriage return and newline) between the lines.
If the file already exists, Set-Content will overwrite its existing content with the new content. If the file doesn’t exist, Set-Content will create a new file with the given content.
After executing the command, the file “example.txt” will have the specified content.
The Set-Content cmdlet is useful for creating or replacing the content of files within PowerShell scripts or interactive sessions. It allows you to easily manage and modify the content of files using the power of PowerShell.
Copy-Item
The Copy-Item cmdlet in PowerShell is used to copy files and directories from one location to another. It allows you to duplicate files and directories within the file system. Here’s an example:
Let’s say you have a file named “source.txt” located in the “C:\path\to” directory, and you want to make a copy of it in the “C:\destination” directory.
To copy the file using Copy-Item, open PowerShell and enter the following command:
Copy-Item -Path "C:\path\to\source.txt" -Destination "C:\destination"
Replace “C:\path\to\source.txt” with the actual path to your source file, and “C:\destination” with the desired destination directory where you want to create the copy.
This command will create a duplicate of the “source.txt” file in the specified destination directory.
If you want to copy an entire directory and its contents, you can use the -Recurse parameter. For example, to copy a directory named “source” and all its files and subdirectories to a destination directory, you can use the following command:
Copy-Item -Path "C:\path\to\source" -Destination "C:\destination" -Recurse
Replace “C:\path\to\source” with the path to your source directory, and “C:\destination” with the desired destination directory.
This command will recursively copy the “source” directory and all its contents to the specified destination directory.
The Copy-Item cmdlet provides various options and parameters to customize the copying behavior, such as preserving file attributes, filtering specific files, or excluding certain directories. You can refer to the PowerShell documentation for more details on advanced usage of the Copy-Item cmdlet.
Remember to ensure you have appropriate permissions to read the source files and write to the destination location when using Copy-Item.
Remove-Item
The Remove-Item cmdlet in PowerShell is used to delete files and directories. It allows you to remove items from the file system. Here’s an example:
Let’s say you have a file named “file.txt” located in the “C:\path\to” directory, and you want to delete it.
To remove the file using Remove-Item, open PowerShell and enter the following command:
Remove-Item -Path "C:\path\to\file.txt"
Replace “C:\path\to\file.txt” with the actual path to the file you want to delete.
This command will permanently delete the specified file from the file system.
If you want to remove an entire directory and its contents, you can use the -Recurse parameter. For example, to delete a directory named “folder” and all its files and subdirectories, you can use the following command:
Remove-Item -Path "C:\path\to\folder" -Recurse
Replace “C:\path\to\folder” with the path to the directory you want to delete.
This command will recursively remove the “folder” directory and all its contents from the file system.
Be cautious when using the Remove-Item cmdlet, as it permanently deletes files and directories. Make sure you have the necessary permissions and double-check the items you are deleting to avoid unintended data loss.
The Remove-Item cmdlet provides various options and parameters to customize the deletion behavior, such as forcefully removing read-only files or prompting for confirmation before deleting. You can refer to the PowerShell documentation for more details on advanced usage of the Remove-Item cmdlet.
Move-Item
The Move-Item cmdlet in PowerShell is used to move files and directories from one location to another. It allows you to relocate items within the file system. Here’s an example:
Let’s say you have a file named “file.txt” located in the “C:\path\from” directory, and you want to move it to the “C:\path\to” directory.
To move the file using Move-Item, open PowerShell and enter the following command:
Move-Item -Path "C:\path\from\file.txt" -Destination "C:\path\to"
Replace “C:\path\from\file.txt” with the actual path to your source file, and “C:\path\to” with the desired destination directory where you want to move the file.
This command will move the “file.txt” from the source location to the specified destination directory.
If you want to move an entire directory and its contents, you can use the -Recurse parameter. For example, to move a directory named “folder” and all its files and subdirectories to a destination directory, you can use the following command:
Move-Item -Path "C:\path\from\folder" -Destination "C:\path\to" -Recurse
Replace “C:\path\from\folder” with the path to your source directory, and “C:\path\to” with the desired destination directory.
This command will recursively move the “folder” directory and all its contents to the specified destination directory.
The Move-Item cmdlet preserves the original file attributes, such as timestamps and permissions, when moving items. If the destination directory already contains an item with the same name, it will be overwritten unless you specify the -Force parameter.
It’s important to ensure you have appropriate permissions to read the source files, write to the destination location, and delete the source items when using Move-Item.
The Move-Item cmdlet provides various options and parameters to customize the moving behavior, such as excluding certain files or directories, and filtering items based on specific criteria. You can refer to the PowerShell documentation for more details on advanced usage of the Move-Item cmdlet.
Set-Item
The Set-Item cmdlet in PowerShell is used to modify the properties or attributes of an item, such as a file or directory. It allows you to change various aspects of an item within the file system. Here’s an example:
Let’s say you have a file named “file.txt” located in the “C:\path\to” directory, and you want to modify its attributes, such as the read-only flag.
To modify the file attributes using Set-Item, open PowerShell and enter the following command:
Set-Item -Path "C:\path\to\file.txt" -ReadOnly $true
Replace “C:\path\to\file.txt” with the actual path to your file.
This command will set the “file.txt” as read-only by changing its attribute to $true.
You can modify other properties of an item as well. For example, if you want to change the last write time of a file, you can use the following command:
Set-Item -Path "C:\path\to\file.txt" -LastWriteTime "2022-01-01 12:00 PM"
Replace “C:\path\to\file.txt” with the actual path to your file, and specify the desired date and time for the -LastWriteTime parameter.
This command will modify the last write time of the file to the specified date and time.
The specific properties that can be modified using Set-Item depend on the item type (file, directory, registry key, etc.). You can refer to the PowerShell documentation or use the Get-Help Set-Item command in PowerShell to explore the available options and properties for different types of items.
Please note that modifying certain properties may require elevated privileges or administrative access, especially for system-related items.
The Set-Item cmdlet provides various options and parameters to customize the modification behavior, such as recursively modifying items within a directory or specifying additional properties to change. You can refer to the PowerShell documentation for more details on advanced usage of the Set-Item cmdlet.
New-Item
The New-Item cmdlet in PowerShell is used to create a new item, such as a file or directory. Here are a few examples of its usage:
Create a new text file:
New-Item -Path "C:\path\to\newfile.txt" -ItemType File
This command creates a new text file named “newfile.txt” in the specified path, “C:\path\to”.
Create a new directory:
New-Item -Path "C:\path\to\newdirectory" -ItemType Directory
This command creates a new directory named “newdirectory” in the specified path, “C:\path\to”.
Create a new file with content:
New-Item -Path "C:\path\to\newfile.txt" -ItemType File -Value "This is the content of the file."
This command creates a new text file named “newfile.txt” in the specified path and sets its content to “This is the content of the file.”
Create multiple new directories:
1..5 | ForEach-Object { New-Item -Path "C:\path\to\folder$_" -ItemType Directory }
This command creates five new directories named “folder1” through “folder5” in the specified path.
These examples demonstrate how you can use the New-Item cmdlet to create files and directories in various ways. The -Path parameter specifies the location where the item will be created, and the -ItemType parameter indicates the type of item to create (File or Directory). Additionally, you can use the -Value parameter to set the content of a file when creating it.
Remember to ensure you have appropriate permissions to create items in the specified locations when using New-Item.
Start-Job
The Start-Job cmdlet in PowerShell is used to run a script or command as a background job, allowing it to execute asynchronously while you continue to interact with the console. Here’s an example of how you can use Start-Job:
$scriptBlock = {
# This is the script block that will be executed as a background job
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
}
$job = Start-Job -ScriptBlock $scriptBlock
# Wait for the job to complete
Wait-Job -Job $job
# Retrieve the output from the completed job
$jobOutput = Receive-Job -Job $job
# Display the output
Write-Output $jobOutput
In this example, the script block retrieves the top 5 processes based on CPU usage. By using Start-Job, the script block is executed as a background job, allowing you to continue working in the console while it runs.
After starting the job, the script waits for the job to complete using Wait-Job. Once the job has finished, the output is retrieved using Receive-Job, and then displayed using Write-Output.
Using Start-Job allows you to run lengthy or resource-intensive tasks in the background without blocking the current PowerShell session. It’s particularly useful when you want to perform tasks concurrently or when you need to keep the console responsive while a task is running.
Compare-Object
The purpose of Compare-Object in PowerShell is to compare two sets of objects. One set of objects is the reference, and the other set of objects is the difference. The cmdlet checks for available methods of comparing a whole object. If it can’t find a suitable method, it calls the ToString() methods of the input objects and compares the string results. The results indicate a property value appears only in the Reference set (indicated by <=), only in the Difference set (indicated by =>) or in both objects (indicated by == when -IncludeEqual parameter is specified).
Here’s an example of using Compare-Object in PowerShell:
$first = @(1,2,3)
$second = @(2,3,4)
Compare-Object $first $second
This will return the difference between the two arrays. In this case, it will return:
InputObject SideIndicator
----------- -------------
1 <=
4 =>
You can also compare two objects with the specific property name using the -Property parameter. Here’s an example:
$sfiles = Get-ChildItem C:\Test1 -Recurse $dfiles = Get-ChildItem C:\Test2 -Recurse Compare-Object $sfiles $dfiles -Property LastWriteTime -IncludeEqual
This will compare files LastWriteTime. The -IncludeEqual parameter will include the files that are equal in both directories.
Group-Object
The Group-Object cmdlet in PowerShell is used to group objects based on one or more properties. It’s a handy tool for aggregating and summarizing data. Here’s an example of how you can use the Group-Object cmdlet.
Let’s say we have a list of employees with their respective departments and we want to group them by department to get a count of employees in each department.
# Sample data
$employees = @(
[PSCustomObject]@{
Name = "John Doe"
Department = "HR"
},
[PSCustomObject]@{
Name = "Jane Smith"
Department = "IT"
},
[PSCustomObject]@{
Name = "Mike Johnson"
Department = "IT"
},
[PSCustomObject]@{
Name = "Sarah Lee"
Department = "Finance"
},
[PSCustomObject]@{
Name = "David Brown"
Department = "HR"
}
)
# Grouping employees by department
$groupedEmployees = $employees | Group-Object -Property Department
# Output the grouped data
$groupedEmployees | ForEach-Object {
Write-Host "Department: $($_.Name), Employee Count: $($_.Count)"
}
Output:
Department: HR, Employee Count: 2
Department: IT, Employee Count: 2
Department: Finance, Employee Count: 1
In this example, we create an array of employee objects with their names and departments. Then, we use the Group-Object cmdlet to group the employees by the “Department” property. The resulting grouped objects are stored in the $groupedEmployees variable.
Finally, we iterate over each grouped object and output the department name ($_.Name) and the count of employees in that department ($_.Count).
This demonstrates how the Group-Object cmdlet can be used to group and summarize data based on specific properties.
Invoke-WebRequest
The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of forms, links, images, and other significant HTML elements. This cmdlet was introduced in Windows PowerShell 3.0.
Here are some of the things that Invoke-WebRequest can be used for:
- Retrieve the content of a web page.
- Download a file from a web server.
- Post data to a web form.
- Make a REST API call.
- Automate web-based tasks.
Invoke-WebRequest is a powerful tool that can be used to interact with web pages and web services. It is a valuable tool for PowerShell scripting and automation.
Here are some of the differences between Invoke-WebRequest and Invoke-RestMethod:
- Invoke-WebRequest returns a more detailed response object, including the HTTP headers and status code.
- Invoke-WebRequest can be used to make requests to HTTP and HTTPS endpoints, while Invoke-RestMethod is specifically designed for REST APIs.
- Invoke-WebRequest is more flexible, as it allows you to specify the request method, body, and headers.
- Invoke-RestMethod is easier to use, as it automatically parses the response and returns the data in a more structured format.
Ultimately, the best cmdlet to use depends on your specific needs. If you need to make a complex request or need access to the full response object, then Invoke-WebRequest is the better choice. If you need to make a simple request or want to automate a REST API call, then Invoke-RestMethod is a good option.
Here are some examples:
# This script uses Invoke-WebRequest to retrieve the current weather forecast for San Francisco.
$url = "https://www.wunderground.com/weather/us/ca/san-francisco"
$response = Invoke-WebRequest -Uri $url
$weather = $response.Content | ConvertFrom-Json
# Print the weather forecast.
Write-Host "The current weather in San Francisco is:"
Write-Host $weather
This script first defines the URL of the weather forecast website. Then, it uses Invoke-WebRequest to send a web request to the website and retrieve the response. The response is then converted to JSON format and stored in the $weather variable. Finally, the weather forecast is printed to the console.
Here is another example of the use of Invoke-WebRequest:
# This script uses Invoke-WebRequest to download the latest version of the PowerShell documentation.
$url = "https://docs.microsoft.com/en-us/powershell/scripting/"
$response = Invoke-WebRequest -Uri $url -OutFile "powershell-docs.zip"
# Unzip the PowerShell documentation.
Expand-Archive "powershell-docs.zip"
This script first defines the URL of the PowerShell documentation website. Then, it uses Invoke-WebRequest to download the latest version of the documentation and save it to a file called “powershell-docs.zip”. Finally, it uses Expand-Archive to unzip the documentation.
These are just a few examples of the many ways that Invoke-WebRequest can be used. For more information, please see the Invoke-WebRequest documentation at this link.
Measure-Object
The Measure-Object cmdlet in PowerShell is used to measure the property values of objects. It can count objects, calculate the minimum, maximum, sum, and average of numeric values, and count the number of lines, words, and characters in string objects.
Here are some examples of how to use Measure-Object:
To count the number of files in a directory, you could use the following command:
Get-ChildItem | Measure-Object -property Count
To calculate the average size of all the files in a directory, you could use the following command:
Get-ChildItem | Measure-Object -property Length -average
To count the number of lines in a text file, you could use the following command:
Get-Content textfile.txt | Measure-Object -property Lines
To calculate the standard deviation of the values in a range of numbers, you could use the following command:
1..10 | Measure-Object -property Value -standardDeviation
The Measure-Object cmdlet is a powerful tool that can be used to gather a variety of information about objects. It is a valuable resource for PowerShell users who need to analyze data or troubleshoot problems.
Resolve-Path
The Resolve-Path cmdlet in PowerShell is used to resolve a path. This means that it will expand any wildcards in the path and return the full path to the file or folder that the path refers to.
For example, if you run the following command:
Resolve-Path "C:\Windows\*.exe"
PowerShell will expand the asterisk (*) wildcard and return a list of all the .exe files in the C:\Windows directory.
The Resolve-Path cmdlet can also be used to resolve UNC paths. For example, the following command will resolve the UNC path \\Server01\share\myfile.txt:
Resolve-Path "\\Server01\share\myfile.txt"
The Resolve-Path cmdlet is a useful tool for working with paths in PowerShell. It can be used to simplify paths, expand wildcards, and resolve UNC paths.
Here are some additional examples of how to use the Resolve-Path cmdlet:
To resolve the current path, you could use the following command:
Resolve-Path "~"
To resolve the path to the Windows directory, you could use the following command:
Resolve-Path "C:\Windows"
To resolve a path that contains a variable, you could use the following command:
$path = "C:\Users\$env:username"
Resolve-Path $path
To resolve a path that contains a wildcard, you could use the following command:
Resolve-Path "C:\Windows\*.exe"
Resume-Job
The Resume-Job cmdlet in PowerShell is used to resume a suspended job. A suspended job is a job that has been temporarily stopped. When a job is resumed, it will start running again from where it left off.
The Resume-Job cmdlet has the following syntax:
Resume-Job [-Id] <jobId>
The -Id parameter specifies the ID of the job that you want to resume. You can get the ID of a job by using the Get-Job cmdlet.
For example, the following command will resume the job with the ID 12345:
Resume-Job -Id 12345
The Resume-Job cmdlet can also be used to resume multiple jobs at once. To do this, you can use the -JobName parameter to specify the names of the jobs that you want to resume.
For example, the following command will resume all the jobs that have the name “MyJob”:
Set-Variable
The Set-Variable cmdlet in PowerShell is used to set the value of a variable or change the current value. If the variable does not exist, the cmdlet creates it.
The Set-Variable cmdlet has the following syntax:
Set-Variable [-Name] <variableName> [-Value] <value> [-Option] <option> [-Description] <description>
The -Name parameter specifies the name of the variable that you want to set. The -Value parameter specifies the value that you want to set for the variable. The -Option parameter specifies the options for the variable. The -Description parameter specifies a description for the variable.
For example, the following command will set the value of the variable $myVar to the string “Hello, world!”.
Set-Variable -Name $myVar -Value "Hello, world!"
The Set-Variable cmdlet can also be used to set the options for a variable. The following options are available:
- Readonly – The variable cannot be changed.
- Constant – The variable cannot be changed or deleted.
- Private – The variable is only visible in the current scope.
- AllScope – The variable is visible in all scopes.
For example, the following command will set the variable $myVar to be read-only.
Set-Variable -Name $myVar -Value "Hello, world!" -Option Readonly
The Set-Variable cmdlet does not return any output. However, you can use the Get-Variable cmdlet to check the value of the variable that you have set.
Here are some additional things to keep in mind about the Set-Variable cmdlet:
- The value of a variable can be any type of object.
- The name of a variable can be any combination of letters, numbers, and underscores.
- The name of a variable cannot start with a number.
Show-Command
The Show-Command cmdlet in PowerShell is used to create a PowerShell command in a command window. You can use the features of the command window to run the command or have it return the command to you. Show-Command is a very useful teaching and learning tool.
The Show-Command cmdlet has the following syntax:
Show-Command [-Name] <commandName> [-Parameters] [-CommonParameters] [-ShowWindow]
The -Name parameter specifies the name of the command that you want to show. The -Parameters parameter specifies whether you want to show the parameters for the command. The -CommonParameters parameter specifies whether you want to show the common parameters for the command. The -ShowWindow parameter specifies whether you want to show the command window.
For example, the following command will show the command window for the Get-ChildItem cmdlet:
Show-Command -Name Get-ChildItem
The Show-Command cmdlet can also be used to show the parameters for a command. To do this, you can use the -Parameters parameter.
For example, the following command will show the parameters for the Get-ChildItem cmdlet:
Show-Command -Name Get-ChildItem -Parameters
The Show-Command cmdlet can also be used to show the common parameters for a command. To do this, you can use the -CommonParameters parameter.
For example, the following command will show the common parameters for the Get-ChildItem cmdlet:
Show-Command -Name Get-ChildItem -CommonParameters
The Show-Command cmdlet is a useful tool for learning about PowerShell commands. It can be used to see the syntax of a command, the parameters that a command takes, and the common parameters that a command takes.
Here are some additional things to keep in mind about the Show-Command cmdlet:
- The Show-Command cmdlet does not return any output.
- The Show-Command cmdlet can be used to show commands that are not in the current session.
- The Show-Command cmdlet can be used to show commands that are in modules.
Sort-Object
In PowerShell, the Sort-Object cmdlet is used to sort objects based on one or more properties. It allows you to sort the output of a command in ascending or descending order. The Sort-Object cmdlet is particularly useful when working with collections of objects, such as arrays of custom objects or the output of other cmdlets.
Here’s the basic syntax of the Sort-Object cmdlet:
Sort-Object [-Property] <string[]> [-Descending] [-CaseSensitive] [-Unique]
Explanation of the parameters:
- -Property: Specifies the property or properties based on which the objects should be sorted. You can sort by a single property or multiple properties by providing an array of property names.
- -Descending: By default, objects are sorted in ascending order. When you use this switch, the objects will be sorted in descending order.
- -CaseSensitive: This switch is used to sort the objects in a case-sensitive manner. By default, sorting is case-insensitive.
- -Unique: This switch ensures that the sorted output contains only unique values. Duplicate entries will be removed.
Now, let’s go through some examples to understand how to use the Sort-Object cmdlet:
Example 1: Sorting numbers in ascending order
$numbers = 5, 2, 8, 1, 9, 3
$sortedNumbers = $numbers | Sort-Object
$sortedNumbers
Output:
1
2
3
5
8
9
Example 2: Sorting strings in descending order
$fruits = "apple", "orange", "banana", "grape", "pear"
$sortedFruits = $fruits | Sort-Object -Descending
$sortedFruits
Output:
pear
orange
grape
banana
apple
Example 3: Sorting objects based on a property
# Creating custom objects
$person1 = [PSCustomObject]@{
Name = "Alice"
Age = 30
} $person2 = [PSCustomObject]@{
Name = "Bob"
Age = 25
} $person3 = [PSCustomObject]@{
Name = "Charlie"
Age = 35
}
# Creating an array of objects
$people = $person1, $person2, $person3
# Sorting objects by the "Age" property in ascending order
$sortedPeople = $people | Sort-Object -Property Age
$sortedPeople
Output:
Name Age
---- ---
Bob 25
Alice 30
Charlie 35
Example 4: Sorting objects based on multiple properties
# Sorting by Age in descending order, and then by Name in ascending order
$sortedPeople = $people | Sort-Object -Property Age -Descending -Property Name
$sortedPeople
Output:
Name Age
---- ---
Charlie 35
Alice 30
Bob 25
These examples demonstrate the basic usage of the Sort-Object cmdlet. Depending on your specific needs, you can sort objects by different properties and in different orders to obtain the desired output.
Start-Service
The Start-Service cmdlet in PowerShell is used to start a service. A service is a program that runs in the background and provides a specific function. For example, the Windows Time service keeps your computer’s clock synchronized with other computers on the network.
The Start-Service cmdlet has the following syntax:
Start-Service [-Name] [-ComputerName] <computerName> [-Force]
The -Name parameter specifies the name of the service that you want to start. The -ComputerName parameter specifies the name of the computer that the service is running on. The -Force parameter specifies that the service should be started even if it is already running.
For example, the following command will start the Windows Time service on the local computer:
Start-Service -Name "Windows Time"
The Start-Service cmdlet does not return any output. However, you can use the Get-Service cmdlet to check the status of the service that you have started.
Here are some additional things to keep in mind about the Start-Service cmdlet:
- The service must be installed before you can start it.
- You cannot start a service that is already running.
- You can use the -Force parameter to start a service that is in a stopped or paused state.
Start-Process
The Start-Process cmdlet in PowerShell is used to start a process. A process is a program that is running on your computer. For example, the Notepad process is the program that runs when you open Notepad.
The Start-Process cmdlet has the following syntax:
Start-Process [-FilePath] <path> [[-ArgumentList] <argumentList>] [-Wait] [-NoNewWindow] [-PassThru] [-WindowStyle {Normal | Hidden | Minimized | Maximized}] [-WorkingDirectory <directory>] [CommonParameters]
The -FilePath parameter specifies the path to the executable file that you want to start. The -ArgumentList parameter specifies the arguments that you want to pass to the executable file. The -Wait parameter specifies that the Start-Process cmdlet should wait for the process to finish before continuing. The -NoNewWindow parameter specifies that the process should not be started in a new window. The -PassThru parameter specifies that the process object should be returned by the Start-Process cmdlet. The -WindowStyle parameter specifies the style of the window that the process should be started in. The -WorkingDirectory parameter specifies the working directory for the process.
For example, the following command will start the Notepad process and wait for it to finish:
Start-Process -FilePath "C:\Windows\notepad.exe" -Wait
The Start-Process cmdlet does not return any output. However, you can use the Get-Process cmdlet to get information about the process that you have started.
Here are some additional things to keep in mind about the Start-Process cmdlet:
- The executable file must be available on your computer before you can start it.
- You cannot start a process that is already running.
- You can use the -Wait parameter to wait for the process to finish before continuing.
- You can use the -PassThru parameter to get the process object back from the Start-Process cmdlet.
Suspend-Job
Suspend-Job is a cmdlet in PowerShell that allows you to suspend (pause) running background jobs. In PowerShell, a job is a background task or command that you can run asynchronously, allowing you to continue using the shell while the job runs in the background. These jobs are typically created using the Start-Job cmdlet.
The basic syntax of Suspend-Job is as follows:
Suspend-Job [-Id] <Int32[]> [-Wait] [<CommonParameters>]
Parameters:
- -Id <Int32[]> : Specifies the IDs of the jobs you want to suspend. You can provide one or more job IDs.
- -Wait : Waits for the job to be suspended before displaying the output.
Once you run Suspend-Job with the appropriate job ID(s), it will suspend the execution of the specified background job(s). The suspended jobs will remain in a paused state until you decide to resume them using the Resume-Job cmdlet.
Here’s an example of how to use Suspend-Job:
# Start a background job
$job = Start-Job -ScriptBlock { Get-Process }
# Wait for a moment to let the job run (optional)
Start-Sleep -Seconds 5
# Suspend the job
Suspend-Job -Id $job.Id
# Check the job's state (optional)
Get-Job $job.Id | Select-Object -Property State
In this example, we start a background job that runs the Get-Process cmdlet. After a brief wait, we use Suspend-Job to suspend the job’s execution. The Get-Job cmdlet is then used to verify the state of the job, which will now be set to “Suspended.”
Remember that you can use Resume-Job to continue the execution of a suspended job and Remove-Job to remove completed or suspended jobs from the job history.
Wait-Job
The Wait-Job cmdlet in PowerShell is used to wait for a job to finish. A job is a group of commands that are run in the background. The Wait-Job cmdlet will not continue execution until the job has finished.
The Wait-Job cmdlet has the following syntax:
Wait-Job [-Id] <jobId> [-Timeout] [-Force]
The -Id parameter specifies the ID of the job that you want to wait for. The -Timeout parameter specifies the maximum amount of time that you want to wait for the job to finish. The -Force parameter specifies that the Wait-Job cmdlet should continue to wait for the job even if it has been terminated.
For example, the following command will wait for the job with the ID 12345 to finish:
Wait-Job -Id 12345
The Wait-Job cmdlet does not return any output. However, you can use the Get-Job cmdlet to get information about the job that you have waited for.
Here are some additional things to keep in mind about the Wait-Job cmdlet:
- You can use the -Timeout parameter to specify a maximum amount of time that you want to wait for the job to finish.
- You can use the -Force parameter to continue to wait for the job even if it has been terminated.
- The Wait-Job cmdlet will not return any output until the job has finished.
Where-Object
The Where-Object cmdlet is a powerful filtering cmdlet in PowerShell, a command-line shell and scripting language developed by Microsoft. It is commonly abbreviated as Where or ?.
The primary purpose of Where-Object is to filter objects from a collection (usually an array) based on specific criteria defined by a script block. It allows you to retrieve only the elements that meet certain conditions, making it a useful tool for narrowing down data or selecting specific items from a larger dataset.
The basic syntax of the Where-Object cmdlet is as follows:
Where-Object { <Script Block> }
Here, <Script Block> is a piece of code enclosed in curly braces {} that specifies the filtering criteria. The cmdlet iterates through each object in the input collection and evaluates the script block for each item. If the script block returns $true for a particular item, that item is included in the output; otherwise, it is excluded.
Here’s a simple example using the Where-Object cmdlet to filter a collection of numbers:
$numbers = 1..10
$filteredNumbers = $numbers | Where-Object { $_ -gt 5 }
In this example, the Where-Object cmdlet filters the numbers array, and only elements greater than 5 are included in the $filteredNumbers variable.
The $_ (dollar underscore) variable represents the current item being evaluated in the script block.
The Where-Object cmdlet can be used with various types of PowerShell objects, such as files, processes, registry entries, and custom objects, allowing you to perform complex filtering and data manipulation tasks with ease.
Write-Output
In PowerShell, the Write-Output cmdlet is used to send data or objects to the output stream. It is commonly used within scripts or functions to display information, pass data to the pipeline, or store output in variables. Unlike Write-Host, which directly prints output to the console without returning any objects, Write-Output returns the specified data as objects that can be further processed or manipulated.
The basic syntax of the Write-Output cmdlet is as follows:
Write-Output [-InputObject] <Object> [-NoEnumerate]
Here, <Object> represents the data or objects you want to send to the output stream. The -NoEnumerate parameter, if specified, prevents the output from being enumerated (expanded) in the pipeline, which can be useful for preserving collections or arrays as single objects.
It’s important to note that Write-Output is used implicitly in PowerShell. If you run a command or script that returns a value or object without being assigned to a variable or used in a pipeline, PowerShell will automatically use Write-Output to display the output.
Here’s a simple example of using Write-Output:
$myVariable = "Hello, world!"
Write-Output $myVariable
In this example, the string “Hello, world!” is sent to the output stream, and it will be displayed in the console.
You can also use Write-Output within functions to send data back to the calling code:
function Get-Square {
param (
[int]$Number
)
$result = $Number * $Number
Write-Output $result
}
$resultValue = Get-Square -Number 5
Write-Output "The result is: $resultValue"
In this function, the result of squaring the input number is sent to the output stream and stored in the $resultValue variable. The final Write-Output statement then displays the result in the console.
While Write-Output is commonly used for displaying data, keep in mind that in many cases, PowerShell will automatically display the output without explicitly using this cmdlet.