Scripting
PowerShell
ForEach-Object
ForEach-Object { $_ }
Takes each item on the pipeline and handles it as $_
`[cmdlet]
% { [cmdlet] $_ }`
Get-Content C:\path\to\file.txt | ForEach-Object { $_.ToUpper() }
Converts all text in a file to uppercase.
Get-Content C:\path\to\file.txt | ForEach-Object { $_.Trim() }
Trims whitespace from the start and end of each line in a file.
Processes each line in a file and outputs to a new file. Customize the do
command for specific modifications:
for /f "tokens=*" %i in (C:\path\to\file.txt) do @echo %i
Where-Object
Where-Object condition (alias where or ?):
Get-Process | Where-Object {$_.name -eq "notepad"}
Loops
Do Loop
Do-While Loop
$counter = 1
do {
Write-Host "Do-While Loop Iteration: $counter"
$counter++
} while ($counter -le 5)
Do-Until Loop
$counter = 1
do {
Write-Host "Do-Until Loop Iteration: $counter"
$counter++
} until ($counter -gt 5)
Do-While Loop with Condition at the End
$counter = 1
do {
Write-Host "Do-While Loop (Condition at the End) Iteration: $counter"
$counter++
} while ($counter -le 5)
Do-Until Loop with Condition at the End
$counter = 1
do {
Write-Host "Do-Until Loop (Condition at the End) Iteration: $counter"
$counter++
} until ($counter -gt 5)
Do-While Loop with Break
$counter = 1
do {
Write-Host "Do-While Loop with Break Iteration: $counter"
$counter++
if ($counter -eq 3) {
Write-Host "Breaking out of the loop"
break
}
} while ($true)
For Loop
Basic For Loop
for ($i = 1; $i -le 5; $i++) {
Write-Host "Iteration $i"
}
For Loop with Array
$fruits = @("Apple", "Banana", "Cherry", "Date")
for ($i = 0; $i -lt $fruits.Length; $i++) {
Write-Host "Fruit: $($fruits[$i])"
}
ForEach Loop (For Each Element in an Array)
$colors = @("Red", "Green", "Blue", "Yellow")
foreach ($color in $colors) {
Write-Host "Color: $color"
}
ForEach Loop (For Each Item in a Directory)
$files = Get-ChildItem -Path C:\YourDirectoryPath
foreach ($file in $files) {
Write-Host "File Name: $($file.Name)"
}
ForEach-Object Loop (Pipeline)
$numbers = 1..5
$numbers | ForEach-Object {
Write-Host "Number: $_"
}
ForEach Loop (Associative Array/HashTable)
$person = @{
"Name" = "John";
"Age" = 30;
"City" = "New York";
}
foreach ($key in $person.Keys) {
Write-Host "$key: $($person[$key])"
}
Foreach Loop
$letterArray = "a","b","c","d"
foreach ($letter in $letterArray)
{
Write-Host $letter
}
Example 1: ForEach Loop (For Each Element in an Array)
$fruits = @("Apple", "Banana", "Cherry", "Date")
ForEach ($fruit in $fruits) {
Write-Host "Fruit: $fruit"
}
Example 2: ForEach Loop (For Each Element in a Range)
$numbers = 1..5
ForEach ($number in $numbers) {
Write-Host "Number: $number"
}
Example 3: ForEach Loop (For Each Item in a Directory)
$files = Get-ChildItem -Path C:\YourDirectoryPath
ForEach ($file in $files) {
Write-Host "File Name: $($file.Name)"
}
Example 4: ForEach Loop (For Each Key-Value Pair in a Hashtable)
$person = @{
"Name" = "John";
"Age" = 30;
"City" = "New York";
}
ForEach ($key in $person.Keys) {
Write-Host "$key: $($person[$key])"
}
Example 5: ForEach-Object Loop (For Each Object in a Pipeline)
$colors = @("Red", "Green", "Blue", "Yellow")
$colors | ForEach-Object {
Write-Host "Color: $_"
}
While Loop
while (){}
Example 1: Basic While Loop
$counter = 1
while ($counter -le 5) {
Write-Host "While Loop Iteration: $counter"
$counter++
}
Example 2: While Loop with User Input
$continue = $true
while ($continue) {
$input = Read-Host "Do you want to continue? (Y/N)"
if ($input -eq "N" -or $input -eq "n") {
$continue = $false
}
}
Example 3: Infinite While Loop with Break
$counter = 1
while ($true) {
Write-Host "Infinite While Loop Iteration: $counter"
$counter++
if ($counter -gt 5) {
Write-Host "Breaking out of the loop"
break
}
}
Conditions
if (<test1>)
{<statement list 1>}
[elseif (<test2>)
{<statement list 2>}]
[else
{<statement list 3>}]
Example 1: While Loop with a Condition
$counter = 1
while ($counter -le 5) {
Write-Host "While Loop Iteration: $counter"
$counter++
}
Example 2: Do-While Loop
$counter = 1
do {
Write-Host "Do-While Loop Iteration: $counter"
$counter++
} while ($counter -le 5)
Example 3: While Loop with User Input
$continue = $true
while ($continue) {
$input = Read-Host "Do you want to continue? (Y/N)"
if ($input -eq "N" -or $input -eq "n") {
$continue = $false
}
}
Example 4: Do-While Loop with User Input
$continue = $true
do {
$input = Read-Host "Do you want to continue? (Y/N)"
if ($input -eq "N" -or $input -eq "n") {
$continue = $false
}
} while ($continue)
Example 5: While Loop with a Break Condition
$counter = 1
while ($true) {
Write-Host "While Loop Iteration: $counter"
$counter++
if ($counter -gt 5) {
Write-Host "Breaking out of the loop"
break
}
}
Generating Ranges
Echo "Hello!" 10 times.
1..10 | % {echo "Hello!"}`
Generate a range of numbers in reverse order from 10 to 1
$range = 10..1
$range
Generate a range of letters from 'A' to 'Z'
$range = 'A'..'Z'
$range
Generate a range of even numbers from 2 to 10 with a step size of 2
$range = 2..10 | Where-Object { $_ % 2 -eq 0 }
$range
Generate a range of numbers based on variables
$start = 5
$end = 15
$range = $start..$end
$range
Properties
Get-Process | Get-Member
Gives the methods and properties of the object/cmdlet.
(cmdlet).property
Command Structure.
(GetProcess).Name
Returns the single property of 'name' of every process.
-ExpandProperty
Extracts values from properties.
Functions
Get-Help about_Functions
Displays the help about functions
Get-Help about_Functions_Advanced
Displays some more in-depth help about functions
Function Do-Stuff { Get-Date; Get-Process; Get-Service }
Creates a function
Do-Stuff
Runs the function
Comments
Creates a comment beside cmdlet:
Get-Process # comment
Multi-line comment:
<# comment
|
|
comment #>
How to find the data type
$PSHome | Get-Member
Displays System.String with its objects and properties.
$A=12
Creates variable A with an integer value of 12.
$A | Get-Member
Displays System.Int32 with its objects and properties.
CMD
Delete all .txt files in the current directory older than 7 days:
forfiles /s /m *.txt /d -7 /c "cmd /c del @file"
Delete files older than 30 days in a specific directory
forfiles /p "C:\path\to\directory" /s /m *.* /d -30 /c "cmd /c del @file"
/s
: Recurse into subdirectories.
/m *.txt
: Include only files with the .txt extension.
/d -7
: Include files that are older than 7 days (negative value signifies "older than").
/c "cmd /c del @file"
: Execute the del @file command for each matching file.
Move all files newer than yesterday from the C:\Temp folder to the D:\Archive folder:
forfiles /s /m * /d +1 /c "cmd /c move @file D:\Archive"
/s
: Recurse into subdirectories.
/m *
: Include all files (regardless of extension).
/d +1
: Include files that are newer than yesterday (positive value signifies "newer than").
/c "cmd /c move @file D:\Archive"
: Execute the move @file D:\Archive command for each matching file.
Copy all .jpg files from the C:\Photos folder to the D:\Backup folder:
forfiles /s /m *.jpg /c "cmd /c copy @file D:\Backup"
Copy all PDF files from one directory to another
forfiles /p "C:\path\to\source" /m *.pdf /c "cmd /c copy @path C:\path\to\destination"
Print the names of all txt files in a directory
forfiles /p "C:\path\to\directory" /m *.txt /c "cmd /c echo @file"
Rename all .docx files in the current directory to start with "Document_":
forfiles /s /m *.docx /c "cmd /c ren @file Document_@file"
Change the extension of all .txt files to .bak in a directory
forfiles /p "C:\path\to\directory" /m *.txt /c "cmd /c ren @file @fname.bak"
Recursively list the paths of all files in a directory and its subdirectories
forfiles /p "C:\path\to\directory" /s /c "cmd /c echo @path"
Log the names and sizes of all .exe files in the current directory and subdirectories:
forfiles /s /m *.exe /c "cmd /c echo @file (@fsize)" >> exe_files.log"
Execute a PowerShell command on each file in a directory
forfiles /p "C:\path\to\directory" /m *.* /c "cmd /c powershell -Command \"Some-PowerShell-Command -Argument @file\""
Print the last modified date of all files in a directory
forfiles /p "C:\path\to\directory" /c "cmd /c echo @file @fdate"
Create a directory for each file in a directory (using the file name as the directory name)
forfiles /p "C:\path\to\directory" /m *.* /c "cmd /c mkdir @fname"
@file
Represents the full path of the current file being processed by the loop or command.
Its value changes as the loop iterates through a set of files.
Use it within commands to perform actions specific to each file, like copying, deleting, or hashing.
@date
Holds the date and time associated with the current file being processed.
The specific format of @date depends on the command being used.
forfiles typically provides access to date components like creation, modification, or access time.
It allows comparing file dates with specific criteria within the loop.
Last updated
Was this helpful?