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 -CommandNew-Item -Path './test' -ItemType Directory > $null#displays files in current directoryWrite-Host "-------------Files in current directory-------------"Get-ChildItem -Name#copy fileCopy-Item "abc.txt" -Destination "./test/abc.txt"#displays files in test directoryWrite-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
testin the current directory using theNew-Itemcmdlet. 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.txtfrom the current directory to thetestdirectory using theCopy-Itemcmdlet. - In line 14, we display the files in
test. As we can see, the file has been copied.