Copy-Item | Taking on PowerShell one cmdlet at a time | Weekly Blog

Share this post:

This is a part of an on-going blog series written by Adam Gordon. Each week, Adam will walk you through a PowerShell command, showing you when and how to use each one. This week, Adam covers Copy-Item. 

When to use Copy-Item?

The Copy-Item cmdlet copies an item from one location to another location in the same namespace.

This cmdlet does not cut or delete the items being copied. The particular items that the cmdlet can copy depend on the PowerShell provider that exposes the item. For instance, it can copy files and directories in a file system drive and registry keys and entries in the registry drive.

This cmdlet can copy and rename items in the same command. To rename an item, enter the new name in the value of the -Destination parameter. To rename an item and not copy it, use the Rename-Item cmdlet.

What version of PowerShell am I using for this blog?

Get the PowerShell Version from your machine:

$PSVersionTable

This command shows you the PowerShell version information on your machine.

How to use Copy-Item?

Copy a file to the specified directory: 

Copy-Item “C:\pshell_help\*.csv” -Destination “C:\PShellTest”

This example copies all the .csv files from the pshell_help directory to the C:\PShellTest directory. The original files are not deleted

Copy directory contents to an existing directory:

Copy-Item -Path “C:\Windows\Logs\*” -Destination “C:\PShellTest\CopyItemsTest” -Recurse

This example copies the contents of the C:\Windows\Logs files directory into the existing PShellTest\CopyItemsTest directory. The Logs directory is not copied.

If the Logs directory contains files in subdirectories, those subdirectories are copied with their file trees intact. By default, the -Container parameter is set to True, which preserves the directory structure.

NOTE: If you need to include the Logs directory in the copy, remove the \* from the Path.

Recursively copy the entire contents of a folder to a remote computer:

$Session = New-PSSession -ComputerName “SCCMPRIME” -Credential “ITP\Administrator”

Copy-Item “C:\Folder003\” -Destination “C:\Folder003_Copy\” -ToSession $Session -Recurse

A session is created to the remote computer named SCCMPRIME with the credential of ITP\Administrator and stores the results in the variable named $Session.

The Copy-Item cmdlet copies the entire contents from the C:\Folder003 folder to the C:\Folder003_Copy directory on the remote computer using the session information stored in the $Session variable.

The subfolders are copied with their file trees intact. The operation creates the Folder003_Copy folder if it does not already exist.

 

 

Learn last week’s command: Clear-RecycleBin.

Need PowerShell training? Check out ITProTV’s PowerShell online IT training courses.