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 Perform Iteration in Windows Scripts Using CMD and PowerShell

Iteration is a fundamental concept in programming that allows you to repeat a set of instructions until a certain condition is met. This is crucial for automating repetitive tasks, processing data, and managing system configurations. In the Windows environment, iteration can be implemented using batch scripts in CMD (Command Prompt) or PowerShell scripts. This article will guide you through the process of creating and running iterative scripts in both CMD and PowerShell, providing practical examples to illustrate each method.

Examples:

Iteration in CMD (Batch Scripts)

In CMD, you can use the FOR loop to iterate over a set of items or a range of numbers. Here is an example of a batch script that iterates through a list of files in a directory and prints their names:

@echo off
setlocal enabledelayedexpansion

REM Define the directory
set dir=C:\example\path

REM Iterate over each file in the directory
for %%f in (%dir%\*) do (
    echo %%f
)

endlocal

To run this script:

  1. Open Notepad and paste the above code.
  2. Save the file with a .bat extension, for example, list_files.bat.
  3. Open CMD and navigate to the directory where the script is saved.
  4. Run the script by typing list_files.bat and pressing Enter.

Iteration in PowerShell

PowerShell provides more advanced and flexible iteration constructs. Here is an example of a PowerShell script that iterates through a range of numbers and prints each number:

# Define the range
$range = 1..10

# Iterate over each number in the range
foreach ($number in $range) {
    Write-Output $number
}

To run this script:

  1. Open Notepad or any text editor and paste the above code.
  2. Save the file with a .ps1 extension, for example, print_numbers.ps1.
  3. Open PowerShell and navigate to the directory where the script is saved.
  4. Run the script by typing .\print_numbers.ps1 and pressing Enter.

Iterating Over Files in PowerShell

Here is an example of a PowerShell script that iterates over all .txt files in a directory and prints their contents:

# Define the directory
$dir = "C:\example\path"

# Get all .txt files in the directory
$files = Get-ChildItem -Path $dir -Filter *.txt

# Iterate over each file and print its contents
foreach ($file in $files) {
    Write-Output "Contents of $file:"
    Get-Content $file
    Write-Output ""
}

To run this script, follow the same steps as the previous PowerShell example.

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.