/
/

How to Automate Repetitive Tasks with PowerShell

by Makenzie Buenning, IT Editorial Expert
reviewed by Stan Hunter, Technical Marketing Engineer
Task Automation with PowerShell

Key Points

PowerShell Automation Guide for IT Pros

🔹 Key PowerShell Concepts

  • Cmdlets: Built-in lightweight commands (e.g., Get-Process)
  • Pipelines: Pass data between cmdlets (|)
  • Scripts: Sequences of commands to automate tasks
  • ISE: Integrated Scripting Environment for writing/debugging scripts

🔹 Common PowerShell Automation Tasks

  • User account management
    • Automate creation, disabling, deletion, and updates in AD
  • File & folder operations
    • Automate copying, moving, deleting, and archiving files
  • CPU & system monitoring
    • Generate usage reports with Get-Counter
  • Security & port scanning
    • Use Test-NetConnection for remote port status
  • Network config
    • Set static IPs and DNS via New-NetIPAddress

🔹 Advanced PowerShell Use Cases

  • Log monitoring & alerting
    • Monitor for keywords (e.g., “ERROR”) → send alerts
  • Log analysis
    • Count errors across logs, output to CSV
  • Third-party API integration
    • Use Invoke-RestMethod to interact with APIs
  • Data manipulation
    • Merge & export datasets using Import-Csv + Export-Csv

Cybersecurity moves fast, and IT professionals constantly seek ways to improve productivity and efficiency. This guide focuses on automation using PowerShell, 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:

# 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" 

Set-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:logsapp.log"
$keywordToMonitor = "ERROR"
$recipientEmail = "admin at domain.com"
$smtpServer = "smtp.domain.com"
$smtpPort = 587

Get-Content -Path $logFilePath -Wait | ForEach-Object {
    if ($_ -match $keywordToMonitor) {
        Send-MailMessage -From "alerts at domain.com" -To $recipientEmail -Subject "Error Alert" -SmtpServer $smtpServer -Port $smtpPort
    }
}

Explanation: This script continuously monitors a log file for an error condition, using the occurrence of a specific keyword (“ERROR”), then sends an email alert when it detects that keyword.

 

Log analysis and reporting

Example code:

# 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"
}

$response = Invoke-RestMethod -Uri $apiUrl -Headers $headers -Method Get

# Process the response data
if ($response.StatusCode -eq 200) {
    $data = $response | ConvertFrom-Json
    Write-Host "Received data from the API:"
    $data | Format-Table
} else {
    Write-Host "Failed to retrieve data from the API. Status code: $($response.StatusCode)"
}

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 left, and regularly updating user attributes.

Solution: PowerShell was used to automate these tasks. Scripted tasks included:

  1. 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.
  2. 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.
  3. 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:

  1. Automated patch deployment: PowerShell scripts were developed to connect to servers and workstations remotely and initiate the Windows Update process. These scripts scheduled updates during maintenance windows to minimize disruption.
  2. Patch status reporting: PowerShell also helped in generating reports on the patch status of each machine. It provided insights into which machines were up to date and which needed attention.
  3. Security compliance: PowerShell scripts were used to enforce security compliance policies, ensuring that all devices were running the required updates and configurations.

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 restrict the execution of scripts to trusted sources. For example, set the execution policy to “RemoteSigned” or “AllSigned” to ensure that only signed scripts or scripts from trusted locations can run.

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 store and retrieve them. PowerShell provides the Get-Credential cmdlet to securely store credentials as PSCredential objects. Avoid hardcoding usernames and passwords.

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 minimizes risks associated with PowerShell scripting, and a secure and compliant IT environment is assured. 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 offers tools for patching, software deployment, and remediation. 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.

FAQs

Use PowerShell 7+ (PowerShell Core) for cross-platform scripts and modern modules. Keep Windows PowerShell 5.1 for legacy Windows-only modules like some AD tooling. Many environments run both side-by-side. Test modules and scripts in the target runtime before rollout.

Use Get-Credential and store as PSCredential, or save encrypted secrets with the SecretManagement module or a vault (e.g., DPAPI-backed, Azure Key Vault). Avoid hardcoding usernames or passwords. Retrieve at runtime and scope privileges to the minimum required.

Yes. Use PowerShell Remoting (Enter-PSSession, Invoke-Command) over WinRM/SSH for fan-out execution. Schedule scripts with Task Scheduler, Azure Automation, or your RMM/CI system. Always restrict remoting endpoints and authenticate with least privilege.

Implement structured error handling with Try/Catch/Finally and fail clearly on non-zero outcomes. Log actions and results using Start-Transcript, event logs, or centralized logging, and export reports (e.g., CSV). Enforce execution policies (AllSigned/RemoteSigned) and sign production scripts to ensure integrity.

You might also like

Ready to simplify the hardest parts of IT?