16 Essential PowerShell Commands to Know - Make Tech Easier
Windows PowerShell is a powerful application based on the .NET framework. It relies on PowerShell commands called cmdlets. By combining them in a specific order, you can do almost anything in a PowerShell window. To explain how it works, we list the most basic PowerShell commands.
It is worth mentioning : If Windows cannot find "Powershell.exe", please learn how to retrieve it.
Table of contents
- How to use PowerShell commands
- Basic PowerShell Commands
- Clear-Host or Cls
- Convert-to-HTML
- Get-Command
- Get-Help
- Get-Process
- Get-Service
- Install-Module or Install-Script
- mkdir, md, rmdir
- New-Item
- Remove-Item
- Set-ExecutionPolicy
- Select-Object and Sort-Object
- Start- and Stop-Process
- Suspend- and Resume-Service
- Test-Path
- Wait-Process
- Other basic PowerShell commands
- Frequently Asked Questions
How to use PowerShell commands
To start using cmdlets, you need to start PowerShell in administrator mode from the search menu.
Basic PowerShell Commands
PowerShell is not only an active command-line interface in Windows, but also a script and programming window that can run any application or process you want. Although there are hundreds of cmdlets, to get started, you only need to learn the most basic ones.
Clear-Host or Cls
If you make a mistake while typing, or something doesn't go as planned, luckily, you can start over in PowerShell. The convenient clear-host command clears text on the entire screen. Simply enter the command on any line on the screen and everything will disappear immediately.
You can also use the simpler cls command commonly used in command prompts to work with PowerShell. These two text-clearing commands are very useful when encountering error messages.
To avoid typing errors in the command prompt or PowerShell window, copy and paste the command for efficiency.
Tip : Use PowerShell to hide Windows updates, as shown in this guide.
Convert-to-HTML
Having a bunch of HTML is more beautiful than browsing messy PowerShell screenshots. This is also useful when you need to share script errors and other PowerShell events with non-technical team members.
All PowerShell components use .NET objects that we can view on the PowerShell screen. To display them in the full browser window, use the Convert-to-HTML cmdlet. Here is an example of viewing all PowerShell alias. Remember to use a separate line before "Invoke-Item".
<code>Get-Alias | ConvertTo-Html | Out-File aliases.htm<br>Invoke-Item aliases.htm</code>
Once the HTML conversion command is executed, PowerShell will ask you to open the output file using another application. Use the browser to generate a list of objects, such as alias.
Get-Command
There are two main types of commands: alias and functions. The PowerShell alias is the nickname of a function or cmdlet. Windows stores some aliases by default, and you can retrieve them using Get-Command. You can also create your own alias.
Another type of command in PowerShell is functions. These use approved verbs (such as “get”) and simple nouns (such as “StorageNode”).
We use the "Select-object" function (note the combination of verbs and nouns) with an environment variable called the computer name to display the name of the local computer.
<code>$env:computername | Select-Object</code>
Functions are the starting point for advanced PowerShell encoding. You can use functions such as Start-process, to create your own batch script with parameters and variables, performing a series of tasks.
Get-Help
PowerShell has its own self-taught troubleshooting cmdlet, Get-Help, which displays all quick fixes and help articles in one window. Enter a command at the end of any output to get help from various modules. You may need to press the Y key to allow updates to the version of the help content.
There are various help options via Get-help. For example, if you want to know what Get-process does and its exact syntax, enter the following:
<code>Get-Help Get-Process</code>
Tip : Worrying about the keyboard recorder monitoring your activity on your PC? Learn how to detect a keyboard logger on Windows.
Get-Process
Get-Process is a basic PowerShell command that lists all processes on a local device or remote computer.
To obtain more detailed process information, you need to specify additional parameters such as process ID (PID) or process name.
When defining the process you are looking for, you can include many specific parameters:
- List process file sizes by MB
- List processes by priority
- Find the owner of the process
Get-Service
There are many running programs and processes on your Windows computer. While you can view them directly in Task Manager, it will be easier to view the full list with Get-service, which you can convert to HTML later.
Don't remember the exact name of the service you need? You can use wildcard symbols (*) and a few letters you can recall.
<code>Get-service "xyz*"</code>
Common flags used with Get-Service include -DisplayName, -DependentServices, -InputObject, and -RequiredServices.
Install-Module or Install-Script
PowerShell is one of the most secure options for installing packages for Windows software such as Microsoft Teams, McAfee Security, Bing Translator, the latest Xbox games, and more. To get a complete list of all user-supported software in PowerShell, enter:
<code>Get-AppxPackage -AllUsers</code>
A better approach is to search for required packages in PowerShell Gallery, a one-stop resource for the latest packages. Once it is found, enter a command such as Install-module, Install-Script, or Install-Package. The following shows the command to install the minesweeping game.
<code>Install-Script -Name Minesweeper</code>
Wait for a few seconds or minutes to allow the package to be installed through PowerShell. It will be available in Windows later.
Another useful command is Find-package, which searches for packages on your computer or the web.
Tip : You can also use Windows Package Manager to install and update programs.
mkdir, md, rmdir
mkdir is not a native command for PowerShell. However, it is a widely used alias for new-item and is used to create directories, as this syntax is very popular in DOS and Linux. When you use mkdir to add the name of your choice, it creates an empty folder.
<code>mkdir "您选择的空文件夹名称"</code>
Use a simple cd command to let PowerShell point to your newly created folder.
<code>cd "新创建的文件夹名称"</code>
The newly created folder is always located under the C:\Windows\System32 path, but you can use cd to point to a different folder.
You can replace mkdir with md for the same purpose. To delete any directory contents, use the rmdir (delete directory) command:
<code>rmdir "内容为空的文件夹名称"</code>
New-Item
Unlike aliases such as mkdir and md, New-item is the official cmdlet in PowerShell for creating new projects and setting their values. In addition to creating files and folders, you can also use it to create registry keys and entries.
- To create a new directory using the New-item command, enter:
<code>New-item -Path "目录路径位置\" -Name "您选择的名称" -ItemType "directory"</code>
- Once the directory has been created, you can place new files in that folder using New-item.
<code>New-item -path "已创建的目录路径位置\" -Name "文件名.txt" -ItemType "file" -Value "插入您选择的任何文本"</code>
- The newly created file can be found in its target folder.
Remove-Item
Do you want to delete all files with extensions from the folder, such as .TXT, .DOC, .PDF, .WMV? First, use cd to point to the exact folder path, and then use the Remove-Item cmdlet as shown below:
<code>Remove-Item * -Include *(文件类型) -Exclude *(任何变量或数字)"</code>
The above method is very useful for identifying and deleting any hidden or read-only files or for deleting files with special characters.
It's worth mentioning : If you can't delete files from your PC, learn how to force delete files that cannot be deleted in Windows.
Set-ExecutionPolicy
For security purposes, PowerShell has its own execution policy that affects configuration files, scripts, and other parameters. This security feature can be executed using the Set-executionPolicy command and overwrites existing projects with the -force flag. The syntax is as follows.
<code>Set-ExecutionPolicy<br>[-ExecutionPolicy]<br>[[-Scope] ]<br>[-Force]<br>[-WhatIf]<br>[-Confirm]<br>[]</code>
For example, the code for installing Chocolatey software using the Set-ExecutionPolicy command is as follows. Once executed, it will download and install the official Chocolatey software on your computer.
<code>Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))</code>
Select-Object and Sort-Object
If you have many files and extensions in your folder or subfolder, you may want to sort or select them in ascending or descending order based on predefined properties. This is where Sort-Object and Select-Object cmdlets can help you rearrange multiple objects at once.
Sort and selection can be applied to any file in different folders as well as existing processes on your computer. Here is an example of sorting and selecting the ten most important processes in megabytes based on the working set (WS) size.
<code>Get-process | Sort-Object -Property WS | Select-Object -Last "项目数量"</code>
You can use sorting and selection for various other parameters, such as history information for various files, sorting all list items contained in Notepad files, and sorting various events on your computer.
Start- and Stop-Process
Whether you want to start a new process in Windows or stop an existing process, you can quickly use the PowerShell cmdlet to achieve this.
To kill a process quickly, use the Stop-Process cmdlet. The following example shows how to close the process of WordPad.
<code>Stop-process -Name "进程或应用程序名称"</code>
Similarly, to start a new application directly from the PowerShell window, enter the Start-process cmdlet and -FilePath flags.
<code>Start-Process -FilePath "应用程序名称"</code>
Tip : Learn how to stop background applications and processes running in Windows to avoid them consuming your resources.
Suspend- and Resume-Service
Instead of starting or stopping it, you can pause a running service directly. The Suspend-service cmdlet is simple to use, helping you reduce the RAM and CPU usage of services you are not currently using.
Note : You can use Get-service to get the name of the service you want to pause.
<code>Suspend-service -DisplayName "服务全名"</code>
Any terminated service can be restored later using the simple Resume-service command. If you are not sure which services can be paused without negatively affecting the system, use the following command:
<code>Get-Service | Where-Object {$_.CanPauseAndContinue -eq "True"} | Suspend-Service -Confirm</code>
Test-Path
If you want to avoid making file path errors in programming, you need to make sure that the file paths in the syntax are accurate. While you can always use File Explorer for verification, it is more accurate to confirm this with the Test-path cmdlet, which will only answer "True" or "False" to indicate whether the given path exists.
<code>Test-Path -Path "路径名称"</code>
You can modify the command to test the availability of a given file, check that the registry path is accurate, and determine whether there are files other than a specific file type on your computer.
Wait-Process
When multiple processes are running at the same time, you may want to wait for one or more of the processes to stop before using them. Wait-Process cmdlet can help you a lot. You can specify the timeout for PowerShell to wait for before the process stops.
<code>Wait-Process -Name "进程名称" -Timeout (以秒为单位)</code>
Other basic PowerShell commands
In addition to the PowerShell commands listed above, it is also helpful to learn the following cmdlets and functions:
- Echo is a cmdlet for printing any value on the PowerShell console
- Get-Host provides complete details about PowerShell hosting programs in Windows
- Test-JSON is a high-level cmdlet used to test whether a string is a valid JSO object
- Trace-command tracks the entire expression or command to find the parameters and flags contained in it
- Write-output, as its name, outputs the output of the last command in the console window.
Tip : Quickly learn about these legitimate Windows processes that look like malware to avoid removing them from the system.
Frequently Asked Questions
How to fix the error "PowerShell script not recognized as cmdlet name"?
If PowerShell fails to recognize the cmdlet's name, it may be because the path variable is not set correctly. Fix any path variable errors by correcting its invalid folder path.
How to capture error output as a variable in PowerShell?
PowerShell has an error variable parameter, $ErrorVariable, designed to capture all error output when you enter various cmdlets. These can be used for troubleshooting.
Image source: DepositPhotos. All screenshots were taken by Sayak Boral .
The above is the detailed content of 16 Essential PowerShell Commands to Know - Make Tech Easier. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Nanoleaf's Pegboard Desk Dock: A Stylish and Functional Desk Organizer Tired of the same old charging setup? Nanoleaf's new Pegboard Desk Dock offers a stylish and functional alternative. This multifunctional desk accessory boasts 32 full-color RGB

ASUS ROG Zephyrus G14 Esports Laptop Special Offer! Buy ASUS ROG Zephyrus G14 Esports Laptop now and enjoy a $300 offer! Original price is $1999, current price is only $1699! Enjoy immersive gaming experience anytime, anywhere, or use it as a reliable portable workstation. Best Buy currently offers offers on this 2024 14-inch ASUS ROG Zephyrus G14 e-sports laptop. Its powerful configuration and performance are impressive. This ASUS ROG Zephyrus G14 e-sports laptop costs 16 on Best Buy

Unlock Hidden Windows Features for a Smoother Experience! Discover surprisingly useful Windows functionalities that can significantly enhance your computing experience. Even seasoned Windows users might find some new tricks here. Dynamic Lock: Auto

In today's touchscreen world, the satisfying tactile feedback of physical controls is a welcome change. That's why a keyboard with a large volume knob is surprisingly appealing. I recently experienced this firsthand, and it's been a revelation. For

The mouse is a vital component to getting work done on your PC. But when you’re stuck with a faulty mouse, you can run into a few problems including the inability to right-click. But the good news is that there are definitely ways t

Acer's latest gaming laptop series is stunning, but the company has also launched a desktop computer that is awkward in Acer's product line and has its own advantages and disadvantages compared to other small desktop computers. Acer today added four new laptops and a redesigned compact desktop to its popular Nitro gaming lineup. However, let's talk about desktop computers first, because it's the most unique. What makes it unique is that it uses laptop specifications. The Nitro 20 N20-100 uses an AMD Ryzen AI 9 365 processor, or the Intel Core i5-13420H desktop processor is also available. Graphics card can be equipped with up to

The RTX 50-series GPUs: Incremental Upgrades, Competitive Pricing (Mostly) The RTX 50-series represents a measured evolution rather than a revolutionary leap in GPU technology. While performance gains are modest, AI enhancements are a key feature.

Logitech quietly raises prices on many products, citing no specific reason. Observers note price increases of up to 25% on various items, strongly suggesting the impact of ongoing US tariffs on goods imported from China, where Logitech's main manufa
