PowerShell is a scripting language and command-line shell designed for task automation and configuration management, primarily used by system administrators and advanced users. Built on the .NET framework (.Net Core for PowerShell 7), it supports Windows, Linux and macOS. It enables automation of administrative tasks such as managing user accounts, configuring networks and performing backups, thereby reducing human error.
While PowerShell simplifies administration, it can present challenges, particularly for beginners. Common issues include syntax mistakes, misconfigured paths, dependency problems and confusing error messages. In addition, to enhance security, script execution is restricted by default, requiring users to adjust execution policies to run scripts. To maximize PowerShell’s potential while maintaining security, users must combine careful handling of scripts with troubleshooting skills.
Why Use PowerShell Scripts?
PowerShell scripts are a vital tool for system administrators and developers in both Windows and cross-platform environments. Automating processes like account management, network monitoring and software deployment saves considerable time, freeing IT professionals to focus on strategic initiatives, workflow optimization and problem-solving, driving greater efficiency and innovation. They can even schedule scripts for automatic execution. PowerShell Remoting amplifies the value of PowerShell by enabling secure remote management of multiple systems from a central interface, reducing the need for physical access and enhancing response times to incidents.
Using PowerShell scripts also ensures consistent, accurate execution of complex operations. Eliminating human error is essential for maintaining uniform configurations as required for compliance and security. This reliability is invaluable in large-scale environments where even minor inconsistencies can lead to vulnerabilities or operational failures.
Understanding PowerShell Execution Policies
PowerShell uses execution policies to control whether PowerShell scripts can run on a system and, if so, under what conditions.
Execution Policy Settings
Execution policies can have the following settings:
- Restricted: No scripts can be run; only individual commands can be executed in the PowerShell prompt. Attempting to run a script leads to the error message: “Running scripts is disabled on this system.” This is the default setting for most systems.
- AllSigned: Only scripts that are signed by a trusted publisher can be run. This setting provides a high degree of security as it ensures that only verified scripts are executed.
- RemoteSigned: Scripts created locally can run without a signature, but scripts downloaded from the internet must be signed by a trusted publisher. This policy is commonly recommended for routine use.
- Unrestricted: All scripts can be run, regardless of their source or whether they are signed. However, users will receive a warning when they execute downloaded scripts to alert them about the risks.
How to Change an Execution Policy Using Set-ExecutionPolicy
To modify an execution policy, use the Set-ExecutionPolicy cmdlet. The -Scope parameter defines the scope: CurrentUser applies to only the currently logged in user, while LocalMachine applies to all users on the system (using this value requires admin rights).
Here is an example:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Confirm the change by typing Y (Yes) when prompted.
Checking Execution Policy Using Get-ExecutionPolicy
You can check the current execution policy with the following command:
Get-ExecutionPolicy -List
Here is a sample output:
Step-by-Step Guide to Running PowerShell Scripts
To run a PowerShell script from PowerShell, follow these steps:
Step 1: Launch PowerShell
Before running a script, you need to open PowerShell. Here are two options:
- Click the Start menu, type PowerShell and select Windows PowerShell.
- Launch the command prompt by typing cmd in the Start menu. Type powershell to open a PowerShell session.
Next, navigate to the directory where the .ps1 file is stored by runningthe cd command:
cd C:\Users\AbbeyCrawford\Scripts
Step 3: Run the Script
The command to run a PowerShell script depends on whether you are in the directory where your script is located:
- If you are in the directory where your script is located, here is how to run a script in PowerShell:
.\HelloWorld.ps1
- If you are not in the script’s directory, to run a PowerShell script, you must provide its full path:
C:\Users\JohnDoe\Scripts\HelloWorld.ps1
- If the script is in a subfolder of the current directory, use the .\ prefix to supply the relative path:
.\SubFolder\HelloWorld.ps1
- A dot (.) before the path indicates that you want to run the script in the current session to allow its variables or functions to remain available after execution. (Dot sourcing is explained in more detail later in this document.) Note the space between the two dots.
. .\HellowWorld.ps1
. C:\Scripts\MyScripts\HelloWorld.ps1
Running Scripts with Parameters
Many PowerShell scripts accept parameters to make them more flexible. You can pass arguments when executing the script.
For example, suppose you have the following script that accepts two parameters, Name and Age:
param(
[string]$Name,
[int]$Age
)
Write-Host "Hello, $Name! You are $Age years old."
When running the script, you can pass arguments to it as follows:
.\Get-UserInfo.ps1 -Name "John" -Age 30
How to Run PowerShell Script from CMD
To execute a PowerShell script from the command prompt, take the following steps:
- Open the command prompt by typing cmd in the search bar and hitting Enter.
- Use the following command to run your PowerShell script. The -File option is required; it specifies the script file to be run.
powershell -File C:\Scripts\Get-UserInfo.ps1
Using the -NoExit Option
In some cases, you might want the PowerShell window to remain open after your script finishes executing. This can be particularly useful for debugging or when the script is designed to display output that you want to see before the window closes.
To keep the PowerShell window open when running scripts from the command prompt, use the -NoExit option as shown below:
powershell -NoExit -File C:\Scripts\Backup.ps1
How to Run PowerShell as Administrator
Many administrative tasks require elevated permissions to execute successfully. Examples include installing software, modifying network settings and accessing system directories. Attempting to perform these tasks without administrative rights can result in errors, which could block important maintenance or configuration tasks.
To run PowerShell with administrative privileges, right-click on Windows PowerShell and choose Run as Administrator.
Using Start-Process for Administrative Execution
In some situations, you need to run another instance of PowerShell or a script from within a PowerShell session. The Start-Process cmdlet is a perfect tool. Adding the -Verb RunAs parameter instructs PowerShell to launch a new instance with administrative rights:
Start-Process PowerShell -Verb RunAs
To execute a specific script with elevated privileges, add the -ArgumentList parameter and use -File to specify the script’s path. Below are two examples:
Start-Process PowerShell -ArgumentList '-File "C:\Scripts\Update-Software.ps1"' -Verb RunAs
Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File “ C:\Scripts\Update-Software.ps1” -Verb RunAs
Common Errors and How to Fix Them
Troubleshooting errors might seem daunting at first, but resolving them is a significant step, akin to earning gold, silver and bronze badges for debugging skills. Below are some of the most common issues and how to resolve them effectively.
“Running scripts is disabled” Error
This error occurs because PowerShell’s default execution policy is set to Restricted, which prevents any scripts from running. For example, the screenshot below shows the error, “File C:\Scripts\Get-UserInfo.ps1 cannot be loaded because running scripts is disabled on this system”:
To resolve this issue, modify the execution policy to allow script execution. Use Set-ExecutionPolicy to change to a less restrictive setting, such as RemoteSigned.
Syntax Errors
Syntax errors typically arise from incorrect command structure, missing parameters or typos. Here is an example:
To fix syntax errors, carefully read the error messages displayed and check the line number indicated to identify where the error occurred. To prevent errors, always double-check your script for common mistakes and consider using a code editor that offers syntax highlighting or IntelliSense features.
Permissions Errors
Permissions errors occur when the script tries to access resources requiring elevated privileges or when file/folder permissions are insufficient. For instance, the error below indicates that access to the path C:\Backup\Backup.txt was denied:
Here are two ways to fix the problem:
- Right-click PowerShell, select Run as Administrator and execute your script again.
- Check the permissions of the file or folder the script is accessing, and grant the necessary permissions using the Get-Acl and Set-Acl cmdlets.
Running PowerShell Scripts in Different Environments
The process for running PowerShell scripts differs depending on whether you are running them:
- In the PowerShell Integrated Scripting Environment (ISE)
- Through File Explorer
- Remotely using commands like Invoke-Command
Running Scripts in the PowerShell ISE
The PowerShell ISE is a user-friendly development environment designed for writing, testing and debugging PowerShell scripts. It provides a multi-pane interface with features like syntax highlighting and built-in debugging tools. To run scripts in the PowerShell ISE, take these steps:
- Open the PowerShell ISE. To locate it, you can either search for PowerShell ISE in the Start menu, or type powershell_ise in the Run dialog (Windows + R). Here is the resulting interface:
- Use the script pane (top window) to write or load scripts. To create a new .ps1 file, press FileèNew. To save your script, click File > Save As.
- To run your full script, click the Run Script button (green triangle) or press F5. To run selected lines, highlight them and press F8.
Running Scripts from File Explorer
Another convenient method for executing PowerShell scripts is directly from File Explorer. This approach is beneficial when you want to execute a script without needing to open a terminal window or for quick access.
- Navigate to the folder containing your PowerShell script.
- Right-click on the .ps1 script file. In the context menu, select Run with PowerShell. This will launch the script in a new PowerShell window and execute it immediately.
Running Scripts Remotely
PowerShell also provides the ability to run scripts on remote machines without the need for physical access. This is especially useful in enterprise environments where tasks need to be executed across multiple servers.
Prerequisite: Enable Remote Execution
Before you can execute a script remotely, you must enable PowerShell Remoting on the target system. Run the following command:
Enable-PSRemoting -Force
Basic Syntax for Invoke-Command
Invoke-Command allows you to execute cmdlets or scripts on remote computers. For example, to run UpdateSystem.ps1 on a remote computer named Server01, use the following cmdlet:
Invoke-Command -ComputerName Server01 -FilePath C:\Scripts\UpdateSystem.ps1
Providing a Block of Script Block to Execute
To execute a script block directly, use this syntax:
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process }
Running Commands on Multiple Computers
To run scripts on multiple computers, you can specify the computer names using a variable, as shown below:
$computers = "PC1", "PC2", "PC3"
Invoke-Command -ComputerName $computers -ScriptBlock { Your PowerShell Commands }
Alternatively, you can pass the computer names as a comma-separated list:
Invoke-Command -ComputerName Server01, Server02 -ScriptBlock { Restart-Service -Name Spooler }
Automating PowerShell Scripts with Task Scheduler
Windows Task Scheduler, a tool built into the Windows operating system, enables users to schedule tasks to run at a specific date and time, on a defined schedule, or when triggered by certain events.
To learn about the benefits of scheduling PowerShell scripts and get detailed instructions, examples, best practices, and troubleshooting tips, please refer to this article: How to Automate PowerShell Scripts with Task Scheduler.
Advanced Techniques
PowerShell offers advanced techniques to enhance script reusability, modularity, and sharing of variables and functions across scripts. Two key concepts are dot sourcing and script modules.
Dot Sourcing
Normally, each script runs in a new session, and any variables or functions declared within it are lost when the script finishes. With dot sourcing, a script is executed in the current scope so that any variables, functions or aliases defined in that script are available in the session that called it. This is particularly useful when you want to share common functions or variables across scripts or within the same session.
The syntax is as follows:
. .\ScriptName.ps1
The first dot followed by a space (. ) indicates to PowerShell that you are dot sourcing the script.
The second part (.\ScriptName.ps1) is the relative path to your script.
Using Script Modules
A module in PowerShell is a package that contains PowerShell functions, cmdlets, variables and more. Modules are designed to be imported and used across multiple scripts. Compared to dot sourcing, modules provide better encapsulation and versioning, which makes it easier organize, maintain and share reusable scripts.
To create a script module, simply save your script with a .psm1 file extension instead of .ps1.
Once you have created a module, you can make its functions available in your PowerShell session using the Import-Module as follows:
Import-Module C:\Scripts\Modules\Geometry.psm1
Best Practices for Running PowerShell Scripts
The following best practices are essential for maintaining security when running PowerShell scripts, as well as for enhancing script usability and accuracy.
Security Best Practices
Use Strong Execution Policy Settings
Use PowerShell’s execution policies to allow only scripts from trusted and verified sources. Set the execution policy to a level appropriate for your environment. For most organizations, RemoteSigned offers a good balance, allowing scripts created locally to run while requiring downloaded scripts to be signed by a trusted publisher.
Digitally Sign Your Scripts
PowerShell checks a script’s digital signature before running it. Digitally signing your scripts with a trusted certificate helps protect against tampering.
Run Scripts with the Least Privileges Required
Whenever possible, run scripts with the least privilege to limit potential damage in case of security vulnerabilities or errors.
Documentation Best Practices
Well-documented scripts are easier to maintain, debug, and understand for both current and future users.
Use Comments
Comments are important for explaining the purpose of the script, parameters and logic. In PowerShell, comments are prefixed with the # symbol.
For quick explanations, use inline comments:
$backupDirectory = "D:\Backup" # Set the backup directory
To provide more detailed explanations or to temporarily disable parts of your code, use block comments (<# … #>):
<#
This script performs a backup of critical data.
It checks for available space and verifies the integrity of the backup.
#>
Check the Help
To help ensure you are using PowerShell functions properly, use Get-Help to review cmdlet syntax and usage. For example, to get help on Get-Process, run the following command:
Get-Help Get-Process
Error Handling Best Practices
Proper error handling is essential for preventing PowerShell scripts from failing unexpectedly and leaving tasks incomplete or systems in an unstable state.
Validate Input
To avoid unexpected errors, ensure that your scripts validate input. This is especially important for user-related data like names or user avatars.
Implement Try-Catch Blocks
The try-catch block is the primary method for handling errors in PowerShell. This allows you to catch and handle exceptions gracefully. Here is an example:
try {
# Attempt to run a command
Copy-Item -Path $source -Destination $destination -Recurse
} catch {
# Handle the error
Write-Host "An error occurred: $_"
# Additional error recovery actions can be performed here
}
Use Finally Blocks
Add a final block when necessary. This block will run regardless of whether an error occurred in the try block, allowing you to clean up resources or execute the finalization code. Below is an example:
try {
# Code that may throw an exception
Remove-Item -Path $filePath -ErrorAction Stop
} catch {
Write-Host "Failed to remove the file: $_"
} finally {
Write-Host "Cleanup actions have been performed."
}
Conclusion
PowerShell is an incredibly powerful tool for automating system administration tasks to ensure accuracy and improve efficiency. By understanding core concepts like execution policies, dot sourcing and script modules, as well as following best practices for security and error handling, you can take full advantage of PowerShell to write robust, reusable and secure scripts that improve your day-to-day operations.
We encourage you to start experimenting with PowerShell by writing and running your own scripts. Begin with simple automation tasks and gradually dive deeper into advanced scripting techniques. The more you practice, the more proficient you will become in automating complex workflows, managing remote systems and handling larger-scale IT operations.
FAQ
How to run a PowerShell script from the command line (CMD)?
You can run a PowerShell script from CMD by using the following command:
powershell -ExecutionPolicy Bypass -File "C:\Scripts\Script.ps1"
Why does nothing happen when I run my PowerShell script, and how can I troubleshoot it?
Make sure the script path is correct. Verify that the script contains valid PowerShell commands without errors. Add Write-Host statements for debugging purposes to see where it might be failing.
How can I run a PowerShell script from within another PowerShell script?
You can invoke another script using dot sourcing, as follows:
. "C:\Scripts\Script.ps1"
How do I pass arguments to a PowerShell script when using Start-Process?
You can pass arguments to Start-Process using the syntax below:
Start-Process "powershell.exe" -ArgumentList "-File ‘C:\Path\To\Your\Script.ps1’ -Argument1 Value1 -Argument2 Value2"
How do I resolve the “execution of scripts is disabled on this system” error in PowerShell?
To resolve this, you need to change the execution policy. Open PowerShell as an administrator and use this cmdlet:
Set-ExecutionPolicy RemoteSigned
What is the difference between RemoteSigned and Unrestricted execution policies in PowerShell?
RemoteSigned allows local scripts to run without a signature but requires a signature for scripts downloaded from the internet. Unrestricted allows all scripts to run but warns about internet-downloaded scripts.
How can I run PowerShell scripts as an administrator?
You can use the Start-Process cmdlet with -Ver RunAs parameter, as shown below:
Start-Process powershell -Verb RunAs -ArgumentList "-File 'C:\Scripts\Script.ps1'"
How do I run a PowerShell script with parameters in the current session?
You can call the script with the parameters as follows:
& "C:\Scripts\Script.ps1" -Param1 Value1 -Param2 Value2
Alternatively, you can use this syntax:
.\Script.ps1 -Param1 Value1 -Param2 Value2