PowerShell provides the Copy-Item
in order to copy single or multiple files. The source or destination file can be local to the remote computer. Also, the copied files can be excluded or filtered according to different patterns like file name, file extension, etc.
Copy A File
We start with a simple copy file example. We copy the file name db.txt
to the specified destination. The destination is specified with the -Destination
option.
PS> Copy-Item -Path db.txt -Destination d:\backup\
Alternatively, we can specify the source and destination files without using the options below.
PS> Copy-Item db.txt d:\backup\
The Copy-Item commandlet is an official command but PowerShell also provides Copy the shortcut of the Copy-Item command.
PS> Copy db.txt d:\backup\
Copy All Files In A Folder
In some cases, we may need to copy multiple files which are located in a specific path or directory. The glob operator can be used to copy all files in the specified source directory. In the following example, we copy all files located in the “c:\backup” to the “d:\backup”.
PS> Copy-Item -Path "c:\backup\*" -Destination "d:\backup\"
Exclude In File Copy
Another useful feature for the file copy operation is the ability to exclude some files according to their extension or file name. The -Include
option is used to specify the name or extension pattern. In the following example, we only copy the log files with the *.log
extension.
PS> Copy-Item -Include *.log -Path "c:\backup\*" -Destination "d:\backup\"
Copy To Remote Computer
Another use case for the Copy-Item command is the ability to copy a file to the remote computer. First, the session is created with the remote computer by using the New-PSSession
command.
PS> $Session = New-PSSession -ComputerName "Comp1" -Credential "WindowsTect\ismail.baydan"
Then we use the new session with the -ToSession
option of the Copy-Item command.
PS> Copy-Item -Path "c:\backup\*" -Destination "c:\backup\" -ToSession $Session