Key Points
- PowerShell works as a scripting language and interactive shell for tasks like user creation, file operations, and network configuration.
- Use simple scripts forcomplex automation: Chain cmdlets for advanced workflows like continuous log monitoring with email alerts on “ERROR” events, automated CSV error reporting, authenticated REST API calls, and merging multiple data sources by ID.
- Examples of PowerShell use cases:A government agency automated its Active Directory lifecycle, while a healthcare provider automated patch scheduling and compliance reporting.
- Build security into every script: Least-privilege access and signed scripts reduces automation security risks and ensure compliance with regulatory frameworks.
Cybersecurity moves fast, and IT professionals constantly seek ways to improve productivity and efficiency. This guide focuses on PowerShell automation, one of today’s most powerful and popular scripting languages. It will provide an understanding of the fundamentals, tool capabilities, and best practices for automating repetitive tasks using PowerShell.
What is PowerShell?
PowerShell is a task automation and configuration management framework from Microsoft. It functions as both a scripting language and an interactive command-line shell for system management.
PowerShell is used extensively in various IT domains, including system administration, network configuration, and cybersecurity. Its benefits include automation, simplified scripting, and the ability to manage both Windows and non-Windows systems.
Although similar to scripting languages like Python and Bash, PowerShell is built for Windows and integrates directly with its features and applications.
Foundations of using PowerShell
To master PowerShell, it is important to grasp fundamental concepts like cmdlets (pronounced “command-lets”), which are lightweight commands used in PowerShell, and pipelines, which allow data to pass between cmdlets.
A PowerShell script is a series of commands and instructions written in the PowerShell scripting language. It allows the automation of complex tasks by executing multiple commands in sequence.
Effective use of PowerShell requires familiarity with the PowerShell Integrated Scripting Environment (ISE) and a basic understanding of scripting constructs, such as variables, loops, and conditional statements. The following sections provide examples of these constructs.
Simple PowerShell scripts for automation
PowerShell scripts are a powerful tool for automation. They can streamline repetitive tasks, reduce human error, and save valuable time and resources.
Common PowerShell tasks and their scripts
PowerShell can be used to automate a wide range of tasks. Some examples of simpler automation tasks follow, with PowerShell code provided for each and an explanation of the functions being executed by that code.
User provisioning and management
Example code:
New-ADUser -Name "James Roberts" -SamAccountName "jamesroberts" -UserPrincipalName "jamesroberts@ at domain.com" -AccountPassword (ConvertTo-SecureString "ChangeMe123" -AsPlainText -Force) # Create a new user New-ADUser -Name "James Roberts" -SamAccountName "jamesroberts" -UserPrincipalName "jamesroberts @at domain.com" -AccountPassword (ConvertTo-SecureString "ChangeMe123" -AsPlainText -Force) # Create a new user New-ADUser -Name "James Roberts" -SamAccountName "jamesroberts" -UserPrincipalName "jamesroberts@ at domain.com" -AccountPassword (ConvertTo-SecureString "ChangeMe123" -AsPlainText -Force)
Explanation: This script creates a new user in Active Directory with the name “James Roberts”, assigns a SAM (Security Account Manager) account name, sets the user’s principal name, and specifies the account password.
File and folder operations
Example code:
# Copy files from one folder to another $sourceFolder = "C:\source" $destinationFolder = "D:\destination" Copy-Item -Path "$sourceFolder\*" -Destination $destinationFolder -Recurse
Explanation: This script copies all files from the source folder to the destination folder, including subdirectories (recursively).
System CPU monitoring and reporting
Example code:
# Get CPU usage
$cpuUsage = Get-Counter -Counter "\Processor(_Total)% Processor Time"
$cpuUsage.CounterSamples | ForEach-Object {
Write-Host "Processor: $($_.InstanceName), Usage: $($_.CookedValue)%"
}Explanation: This script retrieves CPU usage information for all processors and displays the usage percentage for each.
You may also be interested in our article on How to Lower CPU Usage.
Find more monitoring-related PowerShell scripts in the NinjaOne Script Hub.
Security-related tasks
Example code:
# Check open ports on a remote host
$hostname = "example.com"
$ports = 80, 443, 22
$ports | ForEach-Object {
$port = $_
$result = Test-NetConnection -ComputerName $hostname -Port $port
if ($result.TcpTestSucceeded) {
Write-Host "Port $port is open"
} else {
Write-Host "Port $port is closed"
}
}
Explanation: This script tests the availability of specific ports on a remote host and reports whether each port is open or closed.
Find more security-related scripts in NinjaOne Script Hub.
Network configuration
Example code:
# Configure a network adapter with a static IP address $interfaceName = "Ethernet" $ipAddress = "192.168.1.100" $subnetMask = "255.255.255.0" $gateway = "192.168.1.1" $dnsServers = "8.8.8.8", "8.8.4.4" New-NetIPAddress -InterfaceAlias $interfaceName -IPAddress $ipAddress -PrefixLength 24 -DefaultGateway $gateway Set-DnsClientServerAddress -InterfaceAlias $interfaceName -ServerAddresses $dnsServers
Explanation: This script configures a network adapter with a static IP address, subnet mask, default gateway, and DNS server addresses.
PowerShell automation of complex tasks
As PowerShell proficiency grows, the automation of more complex tasks and scenarios becomes achievable. Some more complex PowerShell examples follow, with explanations of the functions being executed:
Continuous log monitoring and alerting
Example code:
# Monitor a log file and send an email alert on a specific event $logFilePath = "C:\logs\app.log" $keywordToMonitor = "ERROR" $recipientEmail = "[email protected]" $smtpServer = "smtp.domain.com" $smtpPort = 587 Get-Content -Path $logFilePath -Wait | ForEach-Object { if ($_ -match $keywordToMonitor) { Send-MailMessage -From "[email protected]" -To $recipientEmail -Subject "Error Alert" -SmtpServer $smtpServer -Port $smtpPort } }
Explanation: This script continuously monitors a log file for an error condition by looking for a specific keyword (“ERROR”), and sends an email alert when it detects that keyword.
Log analysis and reporting
Example code:
$results | Export-Csv -Path "log_analysis.csv" -NoTypeInformation
# Analyze log files and generate a report $logFiles = Get-ChildItem -Path "C:\logs" -Filter "*.log" -File $results = @() foreach ($logFile in $logFiles) { $logContent = Get-Content -Path $logFile.FullName $errorCount = ($logContent | Select-String -Pattern "ERROR").Count $results += [PSCustomObject]@{ LogFileName = $logFile.Name ErrorCount = $errorCount } } $results | Export-Csv -Path "log_analysis.csv" -NoTypeInformation
# Analyze log files and generate a report
$logFiles = Get-ChildItem -Path "C:\logs" -Filter "*.log" -File
$results = @()
foreach ($logFile in $logFiles) {
$logContent = Get-Content -Path $logFile.FullName
$errorCount = ($logContent | Select-String -Pattern "ERROR").Count
$results += [PSCustomObject]@{
LogFileName = $logFile.Name
ErrorCount = $errorCount
}
}
$results | Export-Csv -Path "log_analysis.csv" -NoTypeInformation
Explanation: This script scans a directory for log files, analyzes each log file to count the occurrences of the “ERROR” keyword, and generates a CSV report with the log file names and error counts.
You might also be interested in our article on Linux Log Management: Advanced Techniques and Best Practices.
Integration with third-party APIs
Example code:
# Interact with a REST API to retrieve data
$apiUrl = "https://api.example.com/data"
$headers = @{
"Authorization" = "Bearer YourAuthToken"
}
try {
$data = Invoke-RestMethod -Uri $apiUrl -Headers $headers -Method Get
Write-Host "Received data from the API:"
$data | Format-Table
}
catch {
Write-Host "Failed to retrieve data from the API: $($_.Exception.Message)"
}
Explanation: This script interacts with a REST API by sending an authenticated GET request, processes the API response, and displays the received data.
Complex data manipulation
Example Code:
# Transform and aggregate data from multiple sources
$data1 = Import-Csv -Path "source1.csv"
$data2 = Import-Csv -Path "source2.csv"
# Merge data from different sources
$mergedData = $data1 | ForEach-Object {
$item1 = $_
$matchingItem = $data2 | Where-Object { $_.ID -eq $item1.ID }
if ($matchingItem) {
$_ | Select-Object *, @{Name="AdditionalProperty";Expression={$matchingItem.Property}}
} else {
$_
}
}
# Export the merged data
$mergedData | Export-Csv -Path "merged_data.csv" -NoTypeInformation
Explanation: This script imports data from two CSV files, merges them based on a common ID, and exports the merged data to a new CSV file.
Case studies of real-world automation tasks solved with PowerShell
To provide practical insights into the power of PowerShell, we’ll look at two real-world scenarios where PowerShell automation has been applied to solve complex tasks.
Case study #1: Active Directory user account management
Problem: A large Government organization with thousands of employees needed an efficient way to manage user accounts in Active Directory. Management included creating new accounts, disabling or deleting accounts for employees who are no longer with the business, and regularly updating user attributes.
Solution: PowerShell was used to automate these tasks. Scripted tasks included:
- Creating new user accounts: A PowerShell script was created to read user information from a CSV file and automatically create new user accounts in Active Directory with appropriate attributes like username, password, and group memberships.
- Disabling or deleting inactive user accounts: Another script was developed to identify and disable or delete user accounts for employees who were no longer with the company based on the last login date. This script regularly checks user activity and performs the necessary actions.
- User attribute updates: PowerShell scripts were scheduled to run at specific intervals to update user attributes such as job titles, department, and contact information based on data from the HR system.
Learn more about how NinjaOne can help you easily manage Active Directory users.
Case study #2: Patch management
Problem: A system administrator working with a healthcare provider needed to ensure that all servers and workstations in the organization were regularly updated with the latest security patches to protect against vulnerabilities.
Solution: PowerShell automation was implemented to streamline patch management:
- Automated patch deployment: PowerShell scripts were developed to connect to servers and workstations remotely and initiate the Windows Update process. These scripts schedule updates during maintenance windows to minimize disruption.
- Patch status reporting: PowerShell also helped generate reports on each machine’s patch status. It provided insights into which machines were up to date and which needed attention.
- Security compliance: PowerShell scripts were used to apply and verify required security updates and configurations, helping devices meet defined security policies.”
These examples show how PowerShell automates routine IT tasks and improves efficiency, accuracy, and security. Real implementations may require more complex scripts and must adapt to organizational requirements.
Learn how NinjaOne can automate patch management for any endpoint.
PowerShell scripting best practices
Proficient PowerShell script writers create consistent and coherent syntax, including using meaningful variable names, adding comments for clarity, and organizing scripts logically. Adopt the following best practices for secure task automation with PowerShell:
Use PowerShell execution policies
Set PowerShell execution policies to help control script execution. For example, RemoteSigned requires scripts downloaded from the Internet to be signed by a trusted publisher, while AllSigned requires all scripts and configuration files to be signed by a trusted publisher. Execution policies help reduce the risk of unintentionally running untrusted scripts but should not be treated as a security boundary.
Take a look at the video guide on Understanding PowerShell Execution Policies.
Use digital signatures
Digitally signing PowerShell scripts with a code-signing certificate adds an extra layer of security. It ensures that the script has not been tampered with since it was signed. PowerShell can verify the digital signature to confirm its authenticity when executing scripts.
Follow the principle of least privilege
When running PowerShell scripts, follow the principle of least privilege. Ensure that the user or service account executing the script has the minimum necessary permissions to complete the task. Avoid using highly privileged accounts whenever possible.
Store credentials securely
When dealing with credentials in scripts, use secure methods to handle and retrieve them. PowerShell’s Get-Credential cmdlet can securely prompt for credentials and return them as a PSCredential object. Avoid hardcoding usernames and passwords, and use an appropriate secure credential or secrets store when persistent storage is required.
Use input validation
Sanitize and validate input data to prevent code injection attacks, such as SQL injection or script injection. Avoid using user input directly in script execution without proper validation.
Implement error handling
Robust error handling in scripts allows them to handle unexpected situations gracefully. Avoid displaying sensitive information in error messages that attackers could exploit.
Use secure protocols
When connecting to remote systems or web services, use secure protocols such as HTTPS or SSH. Avoid sending sensitive information over unencrypted connections.
Regularly update and patch
Keep PowerShell and any modules or dependencies up to date with the latest security patches and updates. Outdated software can be vulnerable to known exploits.
Log and audit
Implement logging and auditing mechanisms to track script execution and detect suspicious activities. PowerShell’s Start-Transcript cmdlet can be useful for this purpose.
Perform regular code reviews
Conduct regular code reviews of PowerShell scripts to identify potential security vulnerabilities. Consider using code analysis tools to automate this process.
Follow industry recommendations
Stay informed about industry-specific security recommendations and compliance requirements (e.g., PCI DSS, HIPAA, GDPR) that apply to your organization. Ensure that any scripts developed align with these standards.
Following these security practices helps reduce risks associated with PowerShell scripting and contributes to a more secure and compliant IT environment. Security is an ongoing process; regularly reviewing and updating scripts is essential to staying protected against evolving threats.
Automation strategy drives efficiency
A well-planned PowerShell automation strategy allows IT teams to optimize operations, scale efficiently, strengthen security, and maintain flexibility. PowerShell’s versatility supports automation of both simple and complex tasks, making it a critical tool for performance and efficiency.
IT professionals can apply the provided guidance to begin building their automation strategy with confidence.
To extend automation capabilities, NinjaOne IT automation offers tools that allow IT teams to automate tasks and workflows at scale. It also centralizes patching, software deployment, and remediation into a single dashboard. Tasks can run on schedules, in response to defined conditions, or on demand. Automated responses can also be embedded into device and group policies, with the option to override or adjust them when necessary.

