What is the Copy-Item cmdlet in PowerShell?

Overview

The Copy-Item cmdlet is used to copy files or folders from one location to another.

Syntax

Copy-Item -Path "source file or folder" -Destination "destination path"

Parameters

  • Path: This is the source file path.
  • Destination: This is the destination file path.

Return value

It does not return anything.

Let's take a look at an example of this:

Example

example.ps1
abc.txt
#!/usr/bin/pwsh -Command
New-Item -Path './test' -ItemType Directory > $null
#displays files in current directory
Write-Host "-------------Files in current directory-------------"
Get-ChildItem -Name
#copy file
Copy-Item "abc.txt" -Destination "./test/abc.txt"
#displays files in test directory
Write-Host "-------------Files in test directory after copy-------------"
Get-ChildItem "./test" -Name

Explanation

In the above code snippet:

  • In line 2, we create a new folder with the name test in the current directory using the New-Item cmdlet. We will copy the file to this folder.
  • In line 7, we display the files and folders in the current directory.
  • In line 10, we copy the file abc.txt from the current directory to the test directory using the Copy-Item cmdlet.
  • In line 14, we display the files in test. As we can see, the file has been copied.