Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Use the SUM Function in Windows Environment via PowerShell

The SUM function is commonly associated with spreadsheet software like Microsoft Excel, where it is used to add up a range of numbers. However, in the Windows environment, particularly for systems engineers and administrators, the need to sum numbers can arise in various scripting and automation tasks. While Windows Command Prompt (CMD) does not have a direct SUM function, PowerShell provides robust capabilities to perform such operations. This article will guide you on how to use PowerShell to sum numbers, which can be particularly useful for automating administrative tasks, processing data, and generating reports.


Examples:


1. Summing a List of Numbers:
Suppose you have a list of numbers and you want to calculate their sum using PowerShell.


   # Define an array of numbers
$numbers = @(10, 20, 30, 40, 50)

# Calculate the sum
$sum = 0
foreach ($number in $numbers) {
$sum += $number
}

# Output the result
Write-Output "The sum of the numbers is: $sum"

This script initializes an array of numbers, iterates through each number, and adds it to the $sum variable. Finally, it outputs the total sum.


2. Summing Numbers from a Text File:
If you have a text file with numbers listed line by line and you want to calculate their sum, you can use the following PowerShell script:


   # Path to the text file
$filePath = "C:\path\to\numbers.txt"

# Read the file and convert each line to an integer
$numbers = Get-Content $filePath | ForEach-Object { [int]$_ }

# Calculate the sum
$sum = $numbers | Measure-Object -Sum | Select-Object -ExpandProperty Sum

# Output the result
Write-Output "The sum of the numbers in the file is: $sum"

This script reads the content of the specified text file, converts each line to an integer, and then uses the Measure-Object cmdlet to calculate the sum.


3. Summing Numbers from User Input:
You can also prompt the user to input numbers and then calculate their sum.


   # Prompt the user to enter numbers separated by commas
$input = Read-Host "Enter numbers separated by commas"

# Split the input string into an array and convert each element to an integer
$numbers = $input -split "," | ForEach-Object { [int]$_ }

# Calculate the sum
$sum = $numbers | Measure-Object -Sum | Select-Object -ExpandProperty Sum

# Output the result
Write-Output "The sum of the entered numbers is: $sum"

This script prompts the user to enter numbers separated by commas, splits the input string into an array, converts each element to an integer, and then calculates the sum.


To share Download PDF