How to Automate Repetitive Tasks with PowerShell

Task Automation with PowerShell

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 developed by Microsoft. It is a scripting language and an interactive command-line shell designed to simplify system management tasks.

PowerShell is used extensively in various IT domains, including system administration, network configuration, and cyber security. Its benefits include automation, simplified scripting, and the ability to manage both Windows and non-Windows systems.

While PowerShell shares some similarities with other scripting languages like Python and Bash, it’s specifically designed for Windows environments. It offers seamless integration with Windows 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. Examples of these constructs can be found in the sections that follow.

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 checked user activity and performed 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 demonstrate how PowerShell can be a powerful tool for automating routine and time-consuming tasks in real-world IT environments, leading to improved efficiency, accuracy, and security. Real-world scenarios may involve more complex automation scripts and considerations. The actual implementation can vary based on specific requirements and organizational needs.

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.

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

Follow the principle of least privilege when running PowerShell scripts. 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

In the ever-evolving landscape of cyber security and IT management, a well-executed PowerShell automation strategy is not just a tool; it’s a game-changer. This strategy empowers IT professionals to optimize business operations, achieve scalability, fortify their cyber security posture, and retain the flexibility needed to thrive in the digital age.

By following the guidance provided, IT professionals can confidently embark on their PowerShell automation journey. The power of PowerShell lies in its versatility in automating a wide range of tasks, from the simple to the complex, making it an indispensable tool for those seeking optimal performance and efficiency.

When you’re ready to take your automation strategy to the next level, consider NinjaOne’s IT automation tools to enable automated patching, software installations or remediation actions based on reaching condition thresholds, according to your defined schedule, or ad hoc. Embed automated responses into your device and group policies always retaining the ability to override or change policies as needed.

Next Steps

Patching is the single most critical aspect of a device hardening strategy. According to Ponemon, almost 60% of breaches could be avoided through effective patching. NinjaOne makes it fast and easy to patch all your Windows, Mac, and Linux devices whether remote or on-site.

Learn more about NinjaOne Patch Management, schedule a live tour, or start your free trial of the NinjaOne platform.

You might also like

Ready to become an IT Ninja?

Learn how NinjaOne can help you simplify IT operations.

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

Start your 14-day trial of the #1 rated patch management software

No credit card required, full access to all features

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).