How to Copy File in PowerShell: Simple Commands and Examples
To copy a file in PowerShell, use the
Copy-Item cmdlet followed by the source file path and the destination path. For example, Copy-Item -Path 'source.txt' -Destination 'backup.txt' copies the file to a new location or name.Syntax
The basic syntax to copy a file in PowerShell uses the Copy-Item cmdlet. You specify the source file with -Path and the destination with -Destination. You can also add -Force to overwrite existing files and -Recurse to copy folders with their contents.
powershell
Copy-Item -Path <source> -Destination <destination> [-Force] [-Recurse]
Example
This example copies a file named example.txt from the current folder to a new file named example_backup.txt in the same folder.
powershell
Copy-Item -Path 'example.txt' -Destination 'example_backup.txt' # Verify the copy by listing the new file Get-Item 'example_backup.txt'
Output
Directory: C:\Users\User\Documents
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2024-06-01 10:00 1234 example_backup.txt
Common Pitfalls
One common mistake is forgetting to use quotes around file paths that contain spaces. Another is not using -Force when you want to overwrite an existing file, which causes an error. Also, Copy-Item does not copy hidden or system files unless specified.
powershell
## Wrong: Missing quotes for path with spaces Copy-Item -Path C:\"My Documents"\file.txt -Destination C:\Backup\file.txt ## Right: Use quotes Copy-Item -Path 'C:\My Documents\file.txt' -Destination 'C:\Backup\file.txt' -Force
Quick Reference
| Parameter | Description |
|---|---|
| -Path | Specifies the source file or folder to copy. |
| -Destination | Specifies where to copy the file or folder. |
| -Force | Overwrites existing files without asking. |
| -Recurse | Copies all items in a folder and its subfolders. |
Key Takeaways
Use Copy-Item with -Path and -Destination to copy files in PowerShell.
Always quote file paths that contain spaces to avoid errors.
Use -Force to overwrite files without confirmation.
Use -Recurse to copy folders and their contents.
Verify the copy by checking the destination file after running the command.