Copy-Item and Move-Item in PowerShell - Time & Space Complexity
When copying or moving files with PowerShell, it is helpful to understand how the time needed grows as the number of files increases.
We want to know how the work changes when we handle more files.
Analyze the time complexity of the following code snippet.
$source = 'C:\SourceFolder'
$destination = 'C:\DestinationFolder'
Get-ChildItem -Path $source | ForEach-Object {
Copy-Item -Path $_.FullName -Destination $destination
}
This script copies all files from one folder to another, one by one.
- Primary operation: Looping over each file and copying it.
- How many times: Once for each file in the source folder.
As the number of files grows, the total time grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 copy operations |
| 100 | 100 copy operations |
| 1000 | 1000 copy operations |
Pattern observation: The time grows directly with the number of files.
Time Complexity: O(n)
This means the time to copy files grows in a straight line as you add more files.
[X] Wrong: "Copying many files takes the same time as copying one file."
[OK] Correct: Each file requires its own copy step, so more files mean more time.
Understanding how file operations scale helps you write scripts that handle many files efficiently and predict how long tasks will take.
"What if we used Move-Item instead of Copy-Item? How would the time complexity change?"