PowerShell командлет Copy-Item используется для копирования файлов между локальными, сетевыми каталогами или между компьютерами по сети через WinRM. Командлет Copy-Item предоставляет большое количество опций, которые можно использовать в разных сценариях копирования файлов и каталогов (по своим возможностям этот командлет почти не уступает утилите robocopy). Например:
- перезапись файлов (override)
- фильтрация по имени/шаблону
- исключение по имени/шаблону
- Verbose режим
- Копирование файлов с/на удаленные компьютеры
Начнем с простых примеров использования Copy-Item и будем переходить к более сложным.
Содержание:
- Копирование файлов и каталогов
- Копирование с заменой и копирование с заменой read-only файлов
- Копирование с фильтрацией по шаблону
- Исключение файлов при копировании
- Копирование файлов на удаленный компьютер по сети
- Ключ PassThru
- Ключ Verbose
- Несколько полезных скриптов с Copy-Item
Копирование файлов и каталогов
Чтобы скопировать один файл 1.txt из каталога C:\SourceFolder\ в F:\DestFolder\, выполните:
Copy-Item -Path "C:\SourceFolder\1.txt" -Destination "F:\DestFolder\1.txt"
Можно использовать сокращенный синтаксис командлета, пропустив указание параметров Path и Destination:
cpi "C:\SourceFolder\1.txt" "F:\DestFolder\1.txt"
Теперь скопируем каталог C:\SourceFolder\folder в F:\DestFolder\folder. В папке folder находится файл 1.txt. Обратите внимание что без ключа –Recurse, папка folder копируется без содержимого:
Copy-Item -Path "C:\SourceFolder\folder" -Destination "F:\DestFolder\folder" -Recurse
С помощью Copy-Item также можно просто объединить файлы из несколько директорий в одну (слияние директории), для этого нужно перечислить директории в ключе –Path:
Copy-Item -Path "C:\SourceFolder\*", "C:\SourceFolder2\*", "C:\SourceFolder3\*" -Destination "F:\DestFolder\"
Копирование с заменой и копирование с заменой read-only файлов
Copy-Item по умолчанию при копировании заменяет файлы в целевом каталоге. Никаких дополнительных параметров указывать не нужно. При копировании каталога, если нужно заменить каталог в целевой папке, нужно использовать ключ –Force, иначе будет ошибка “Элемент folder с указанным именем уже существует — DirectoryExists”.
Для перезаписи файла с атрибутом read-only, нужно использовать ключ -Force. Если его не использовать, вы получите ошибку “отказано в доступе по пути… CopyFileInfoItemUnauthorizedAccessError”.
Чтобы скопировать файл с перезаписью файла с read-only атрибутом используйте параметр Force.
Copy-Item -Path "C:\SourceFolder\1.txt" -Destination "F:\DestFolder\1.txt" -Force
Совет. Чтобы не путаться, ключ –Force можно рассматривать как ключ для копирования с заменой.
Чтобы Copy-Item скопировал файлы из одной папки в другую без замены существующих файлов, можно использовать этот простой скрипт
Copy-Item (Join-Path "C:\SourceFolder\" "*") "F:\DestFolder\" -Exclude (Get-ChildItem "F:\DestFolder\") -Recurse
Этот скрипт скопирует все файлы и папки из C:\SourceFolder в F:\DestFolder без замены файлов уже существующих в F:\DestFolder
Копирование с фильтрацией по шаблону
С помощью Copy-Item можно скопировать файлы/директории выбранные с помощью wildcard символа * или с помощью символа ?. Также поддерживаются некоторые регулярные выражения
- * — обозначает любое количество любых символов
- ? – обозначает 1 любой символ
- [a-z], [0-9] – символы между a-z и цифры между 0 и 9
Для примера возьмём такую структуру файлов:
Выполним копирование командой:
Copy-Item -Path "C:\SourceFolder\fol*" -Destination "F:\DestFolder\"
Результат в F:\DestFolder\
Теперь чистим папку назначения и выполняем:
Copy-Item -Path "C:\SourceFolder\folder[0-3]" -Destination "F:\DestFolder\"
Результат:
Папка без цифры в окончании не скопировалась, потому что folder[0-3] подразумевает что после folder будет как минимум еще 1 символ между 0 и 3
Исключение файлов при копировании
С помощью ключа –Exclude можно исключить файлы при копировании. Например, следующай команда скопирует все файлы кроме файлов с расширением txt.
Copy-Item -Path "C:\SourceFolder\*" -Destination "F:\DestFolder\" -Recurse -Force -Exclude "*.txt"
Аналогичным же образом можно применить ключ –Include, например
Copy-Item -Path "C:\SourceFolder\*" -Destination "F:\DestFolder\" -Recurse -Force -Include "*.txt"
Скопирует только txt файлы. Хотя для простоты гораздо удобнее использовать при копировании вид
-Path "C:\SourceFolder\*.txt"
.
Копирование файлов на удаленный компьютер по сети
Copy-File может копировать не только по SMB протоколу, но и через WinRM (WSMan).
Создайте новую сессию с компьютером testnode1 и выполните копирование в её контексте:
$session = New-PSSession -ComputerName testnode1
Copy-Item -Path "C:\SourceFolder\*" -ToSession $session -Destination "C:\SourceFolder\" -Recurse -Force
Эта команда скопирует файлы с локального компьютера из директории C:\SourceFolder на компьютер testnode1 в C:\SourceFolder\.
Примечание. Доступность WSMan на удаленном компьютере можно проверить с помощью командлета Test-WSMan.
Test-WSMan -ComputerName testnode1
Если WSMan не настроен, вы можете выполнить его быструю конфигурацию. Для этого откройте командную строку с правами администратора и выполните
winrm quickconfig
Также можно копировать и через обычные сетевые SMB шары, для этого просто используйте UNC формат сетевого пути.
Copy-Item -Path "C:\SourceFolder\*" -Destination "\\testnode1\C$\copy_tutorial\"
Можно скопировать файл с удаленного компьютера. Принцип такой же, как и при копировании файлов на удаленный компьютер, за исключением параметра –ToSession, вместо него нужно использовать –FromSession:
$session = New-PSSession -ComputerName testnode1
Copy-Item -FromSession $session -Path "C:\SourceFolder\*" -Destination "F:\DestFolder\" -Recurse -Force
Эта команда скопирует содержимое папки C:\SourceFolder\ с компьютера testnode1 на локальный компьютер в директорию F:\DestFolder
Ключ PassThru
Командлет Copy-Item (как и многие другие командлеты PowerShell) не возвращает результатов в консоль. Параметр PassThru применяется скриптах, или для лог-файлов, когда нужно получить список скопированных файлов и работать с ним дальше. Рассмотрим пример
$items = Copy-Item -Path "C:\SourceFolder\*" –Destination "\\testnode1\C$\copy_tutorial\" -PassThru
Переменная
$items
будет содержать список скопированных файлов, с которым вы можете работать дальше.Это значит что вы можете напрямую работать с этими файлами. Например выполнив команду
Remove-Item $items[0]
, вы удалите директорию folder.
Ключ Verbose
При использовании ключа -Verbose вы получите подробный лог операций копирования. Например, вывод команды
Copy-Item -Path "C:\SourceFolder\*.txt" -Destination "F:\DestFolder\" -Recurse -Force -Verbose
Несколько полезных скриптов с Copy-Item
Скопировать только файлы:
Get-ChildItem "C:\SourceFolder" -File -Recurse | Copy-Item -Destination "F:\DestFolder"
Скопировать структуру папок, без файлов:
$path = Get-ChildItem "C:\SourceFolder" -Recurse | ?{$_.PsIsContainer -eq $true}
$dest = "F:\DestFolder\"
$parent = $path[0].Parent.Name
$path | foreach {
$_.FullName -match "$parent.+"
New-Item -ItemType directory ($dest + $Matches[0])
}
Copy-Item очень простой и удобный в использовании командлет PowerShell для выполнения операций копирования и перемещения файлов. В сочетании с другими инструментами PowerShell, Copy-Item также является мощным инструментом для написания скриптов.
Copying files between folders, drives and machines can be a waste of your time if you do it manually on a regular basis. A bit of PowerShell know-how automates this tedious process and even handles the most complex situations.
Once you understand the parameters associated with the Copy-Item command and how they work together, you can produce comprehensive scripts with more advanced PowerShell commands to copy files and directories.
The examples in this article work on both Windows PowerShell and PowerShell 7.
PowerShell has providers — .NET programs that expose the data in a data store for viewing and manipulation — and a set of generic cmdlets that work across providers.
These include the following cmdlets:
- *-Item
- *-ItemProperty
- *-Content
- *-Path
- *-Location
With a default installation of PowerShell or Windows PowerShell, you can use the Copy-Item cmdlet to copy files, registry keys and variables. This is facilitated by the provider feature that enables interaction with different content types with the same command. Some modules include custom providers, such as the AD module, which enable you to use those generic cmdlets in the AD data they expose. Run the following command to see the PowerShell providers in your PowerShell session.
Get-PsProvider
For example, these are the providers available in the PowerShell 7 session on my Windows 11 machine.
How do you use the Copy-Item command?
The simplest form of Copy-Item involves a source path and a destination path. To use the FileSystem provider, specify the paths by starting with a drive letter and a colon on Windows or a forward slash on Linux.
Using .\ or ./ to represent the current directory infers the current path based on the current working directory, which doesn’t have to be a FileSystem provider path. You can always check your current working directory with the Get-Location command.
The example in the following PowerShell command copies a single file located at the Path parameter to the location specified in the Destination parameter.
Copy-Item -Path C:\source\path\file.txt -Destination D:\dest\path\text.txt
To use a shorter command, PowerShell offers several aliases for its major cmdlets. The following command shows the three aliases — copy, cp and cpi — for the Copy-Item cmdlet.
Get-Alias -Definition Copy-Item
In PowerShell on Linux, the cp alias does not exist since there is an existing Linux command called cp.
How can you use PowerShell commands to copy files?
To show how the various Copy-Item parameters work, create a test file with the following command.
Get-Process | Out-File -FilePath c:\test\p1.txt
Use this command to copy a file with the Destination parameter. You do not specify a file name in the Destination parameter. In this case, it uses the original file name of p1.txt.
Copy-Item -Path C:\test\p1.txt -Destination C:\test2\
The Copy-Item command does not display any message or confirmation when a copy operation is successful, which can be confusing for new users.
To take advantage of both the command’s alias and position parameters, specify the source and destination in order.
Copy C:\test\p1.txt C:\test2\
Alias use in saved scripts isn’t considered best practice and should be avoided for the most part.
To get feedback from Copy-Item, use the PassThru parameter. This feature returns objects for each of the items that were copied. It’s a helpful tool to confirm the command performed properly.
Copy-Item -Path C:\test\p1.txt -Destination C:\test2\ -PassThru
The other option to see the results from the Copy-Item command is to use the Verbose parameter.
Copy-Item -Path C:\test\p1.txt -Destination C:\test2\ -Verbose
The Verbose parameter displays information as the command executes, while the PassThru parameter gives the resulting file object.
By default, PowerShell overwrites the file if a file with the same name exists in the target folder. If the file in the target directory is set to read-only, you get an error.
Copy-Item -Path C:\test\p1.txt -Destination C:\test2\
You need to be a PowerShell Jedi to avoid this error by using the Force parameter.
Copy-Item -Path C:\test\p1.txt -Destination C:\test2\ -Force
PowerShell can rename files as part of the copy process. For example, this code creates nine copies of the p1.txt file called p2.txt through p10.txt.
2..10 | Foreach-Object {
$newname = "p$_.txt"
Copy-Item -Path C:\test\p1.txt -Destination C:\test2\$newname
Verbose
}
In this case, the .. operator creates an array of integers from two to 10. Then, for each of those integers, the code creates a file with the new name.
How to use PowerShell commands to copy multiple files or folders
There are a few techniques to copy multiple files or folders when using PowerShell.
Copy-Item -Path C:\test\*.txt -Destination C:\test2\
Copy-Item -Path C:\test\* -Filter *.txt -Destination C:\test2\
Copy-Item -Path C:\test\* -Include *.txt -Destination C:\test2\
These commands copy all the .txt files from the test folder to the test2 folder, but the Include parameter lets PowerShell be more selective. For example, this command only copies files with a 6 in the file name.
Copy-Item -Path C:\test\* -Include *6*.txt -Destination C:\test2\ -PassThru
Copy-Item has an Exclude parameter to reject certain files from the copy operation. This PowerShell command only copies text files that start with the letter p unless there is a 7 in the name.
Copy-Item -Path C:\test\* -Filter p*.txt -Exclude *7*.txt -Destination C:\test2\ -PassThru
How to use the Path, Filter, Include and Exclude parameters
A combination of the Path, Filter, Include or Exclude parameters refines the copy process even further. However, if you use Include and Exclude in the same call, Exclude is applied after the inclusions.
For example, combine Path, Filter, Include and Exclude. In this example, the Path parameter selects all files in C:\test, the Filter parameter finds all files that start with the letter p, the Include parameter specifies only .txt files from that selection and the Exclude parameter eliminates files with 7 in the name.
Copy-Item -Path C:\test\* -Filter p* -Include *.txt -Exclude *7* -Destination C:\test2\ -PassThru
You can also supply an array of file names. The path is simplified if your working folder is the source folder for the copy.
Copy-Item -Path p1.txt,p3.txt,p5.txt -Destination C:\test2\
The Path parameter also accepts pipeline input. In the following example, PowerShell checks the p*.txt files in the C:\test folder to see if the second character is divisible by two. If so, PowerShell copies the file to the C:\test2 folder.
Get-ChildItem -Path C:\test\p*.txt | Where-Object
{(($_.BaseName).Substring(1,1) % 2 ) -eq 0} |
Copy-Item -Destination C:\test2\
If you end up with a folder or file name that contains wildcard characters — *, [, ], ? — use the LiteralPath parameter instead of the Path parameter. LiteralPath does no interpretation of any wildcard characters and specifies the exact path to an item.
How to test the Filter, Include and Exclude parameters
If you are using a complex combination of Filter, Include and Exclude, it can be hard to predict what files PowerShell will copy. To test a Copy-File command before executing it, append the WhatIf parameter to any Copy-File command. PowerShell outputs a description of the operation rather than executing the action.
Copy-Item -Path C:\test\* -Filter p* -Include *.txt -Exclude *7* -Destination C:\test2\ -PassThru -WhatIf
Another method to report on the files is to use Get-ChildItem, which utilizes the same Path, Filter, Include and Exclude parameters. They function in the same way as with Copy-Item. Take the same parameters, remove Destination and apply them to Get-ChildItem. The command outputs the list of files and folder objects that start with the letter p and have a .txt extension, and it removes any files that have 7 in the file name.
Get-ChildItem -Path C:\test\* -Filter p* -Include *.txt -Exclude *7*
Because the command returns the files in an array, you can then work with the file objects and generate a report on the files that would be copied, among other things.
How to perform a recursive copy
To copy a folder and its entire contents, use the Recurse parameter.
Copy-Item -Path c:\test\ -Destination c:\test2\ -Recurse
A recursive copy works its way through all the subfolders below the C:\test folder. PowerShell then creates a folder named test in the destination folder and copies the contents of C:\test into it.
When copying between machines, you can use Universal Naming Convention paths to bypass the local machine.
Copy-Item -Path \\server1\fs1\test\p1.txt -Destination \\server2\arc\test\
Another option is to use PowerShell commands to copy files over a remoting session. The following command prompts the user for the password to the Administrator account on the remote machine named W16ND01. The session object gets stored in the $s variable, which can be used in ensuing commands to run operations on W16ND01.
$cred = Get-Credential -Credential W16ND01\Administrator
$s = New-PSSession -VMName W16ND01 -Credential $cred
In this case, use PowerShell Direct to connect to the remote machine. You need the Hyper-V module loaded to create the remoting session over VMBus. Next, use the following PowerShell commands to copy files to the remote machine.
Copy-Item -Path c:\test\ -Destination c:\ -Recurse -ToSession $s
You can also copy files from the remote machine.
Copy-Item -Path c:\test\p*.txt -Destination c:\test3\ -FromSession $s
The ToSession and FromSession parameters control the direction of the copy and whether the source and destination are on the local machine or a remote one. Sending data to a remote machine uses ToSession, and recieving files from a remote machine uses FromSession.
Unfortunately, ToSession and FromSession cannot be used in the same command, nor are relative paths supported. To copy something from your user account’s home directory on one server to another while connecting to both servers via PowerShell remoting, get creative while specifying fully qualified paths.
In the code in the following example, the remote file from server1 is copied locally and then copied to server2.
$server1 = New-PSSession -ComputerName server1.domain.com -Credential
$cred
$server2 = New-PSSession -ComputerName server2.domain.com -Credential
$cred
$path = 'C:\Users\user\Downloads\file.zip'
Copy-Item -Path $path -Destination .\file.zip -FromSession $server1
Copy-Item -Path .\file.zip -Destination $path -ToSession $server2
How to track the progress of a copy command
A useful addition to Copy-Item is the introduction of a progress bar in PowerShell 7.4. This feature shows a visual representation of the status of a running command and helps the user estimate how long until the operation completes. This is not supported in Windows PowerShell.
The following PowerShell code copies files from the C:\PowerShell folder and its subfolders to the D:\PowerShell folder.
Copy-Item C:\PowerShell\ D:\PowerShell\ -Recurse
The output shows the overall progress of the copy operation in terms of files copied, the total size of data transferred and the current data transfer rate.
PowerShell also introduced a ProgressAction common parameter that can disable the progress bar if speed is of the essence.
Copy-Item C:\PowerShell\ D:\PowerShell\ -Recurse -ProgressAction SilentlyContinue
How to copy files to multiple machines
There are times when a file, such as a configuration file, needs to be copied to multiple remote servers or clients. This is easy enough to do if the machines have PowerShell remoting enabled.
First, import the list of computer names. In this example, assume that there is a list of names in a text file, but this could come from an AD query or another source.
$remoteTargets = Get-Content .\names.txt
Next, store the credentials in a variable.
$cred = Get-Credential
Next, use a Foreach-Object loop to take advantage of multithreading in PowerShell 7 with the Parallel parameter to create a session object, copy the file — a config.json file — to the device and close the session.
$remoteTargets | Foreach-Object -Parallel {
$session = New-PSSession -ComputerName $_ -Credential $using:cred
Copy-Item -Path .\config.json -Destination
C:\ProgramData\app\config.json -ToSession $session
Remove-PsSession $session
}
Note how the code uses the $using: syntax to pass the $cred variable into the Foreach-Object scriptblock.
How to create backups of a file
Copy-Item is also useful to create backups for items such as configuration files or frequently modified files in a file share. This example places each backup in a dated folder to provide multiple copies.
First, define the date string. The frequency of the backup dictates the format. For example, a daily backup has a date string that only includes the year, month and day or YYYYMMDD format. This is also called the ISO 8601 format for dates and is recommended due to its relative ease to sort.
For a simple daily backup, generate the date string with the following PowerShell code.
$dateStr = Get-Date -Format FileDate
This returns a string of the current date as a four-digit year, two-digit month and two-digit day.
Next, define the file paths, and create the new directory if needed.
$source = "C:\ProgramData\app\config.json"
$dest = "D:\Backups\app\$dateStr"
if (-not (Test-Path $dest -PathType Container)) {
New-Item -ItemType "directory" -Path $dest
}
Lastly, copy the file.
Copy-Item -Path $source -Destination $dest
To get the most out of a backup script, schedule it with the Task Scheduler on Windows or as a cron job on Linux.
Use advanced PowerShell techniques to check for errors and resume a copy
The Copy-Item cmdlet lacks error checking or restart capabilities. For those features, you need to write the code.
The following script tests the source file path, calculates the file hash, checks for the file’s existence and verifies the integrity of the copied file using a hash comparison. The file copy process occurs within a try/catch block used for exception handling. If an error occurs, a «File copy failed» message is output.
function Copy-FileSafer {
[CmdletBinding()]
param (
[string]$path,
[string]$destinationfolder
)
if (-not (Test-Path -Path $path)) {
throw "File not found: $path"
}
$sourcefile = Split-Path -Path $path -Leaf
$destinationfile = Join-Path -Path $destinationfolder -ChildPath
$sourcefile
$b4hash = Get-FileHash -Path $path
try {
Copy-Item -Path $path -Destination $destinationfolder -ErrorAction
Stop
}
catch {
throw "File copy failed"
}
finally {
$afhash = Get-FileHash -Path $destinationfile
if ($afhash.Hash -ne $b4hash.Hash) {
throw "File corrupted during copy"
}
else {
Write-Information -MessageData "File copied successfully" -InformationAction Continue
}
}
}
With additional coding, the script can recursively retry several times. After each copy attempt, the script can calculate the hash of the file and compare it to the original. If they match, all is well. If not, an error is reported.
Anthony Howell is an IT strategist with extensive experience in infrastructure and automation technologies. His expertise includes PowerShell, DevOps, cloud computing, and working in both Windows and Linux environments.
What is PowerShell Copy-Item Cmdlet?
Copy-Item cmdlet in Powershell is primarily used to copy files from source to destinataion. In terms of numbers of files, they could be individual or multiple along with their content. It can also work across different file systems such as local, network shares etc,
Basic Syntax and Parameters
The basic syntax for the PowerShell Copy-Item cmdlet is as follows:
Copy-Item -Path <source> -Destination <destination> [<parameters>]
If you type the cmdlet only, PowerShell will prompt you for the Source, as shown below:
The first mandatory parameter is the source path. This item path parameter specifies the path to the item or items to be copied. The source can be a file or folder path. Multiple paths can be specified using a comma-separated list, and the path can contain wildcards. A best practice would be to supply a destination path string to specify the path to which the items should be copied. If copying a single item, the path can include a new name for the copied item if desired.
Below is a list of other parameters for the Copy-Item PowerShell cmdlet:
- -Recurse: Copies subdirectories and their content recursively, which means that the Copy-Item cmdlet is applied to the top-level folder and all levels of subfolders beneath it.
- -Force parameter: Overwrites existing read-only files and creates destination directories if they do not exist.
- -Container: Preserves container objects during copy operations, which is useful when copying directory structures.
- -Filter: Specifies a filter string to qualify the path parameter, such as specifying a particular file extension
- -Include: Specifies items to copy and supports wildcards. Only items that match both Path and Include parameters are copied
- -Exclude: Specifies items to omit from copying, supports wildcards
- -Credential: Specifies the user account credentials to use for the operation
- -WhatIf: Shows what would happen if the command ran without actually executing it
- -Confirm: Prompts for confirmation before executing the command
- -FromSession: Specifies the PSSession object from which to get a remote file.
- -ToSession: Specifies the PSSession object to which to send a remote file
Common Use Cases
For most examples, we will copy files to multiple locations on the local computer. There are, however, a variety of common use cases for the Copy-Item cmdlet, including:
- Creating backups of important files and folders
- Distributing files or simple applications across multiple machines
- Migrating large amounts of files between servers or storage locations
- Developers can create snapshots of project folders at different stages of development.
- Distribute configuration files across multiple servers
Now let’s compare the Copy-Item cmdlet with other file management cmdlets:
Copy-Item vs. Move-Item:
- Copy-Item creates a duplicate, leaving the original intact
- Move-Item relocates the file/folder, removing it from the original location
Copy-Item vs. Get-ChildItem
- Copy-Item performs the action of copying
- Get-ChildItem lists files and folders and is often used in conjunction with the Copy-Item
Note that the Copy-Item cmdlet is recommended for basic file copying. Those seeking more advanced features for large file transfers or mirroring may consider Microsoft Robocopy.
Copying Files with Copy-Item PowerShell Cmdlet
Basic File Copy Example
In this example, we want to copy a spreadsheet from one folder to another using the PowerShell copy item command.
Copy-Item -Path "C:\Destination One\SpreadsheetOne.xlsx" -Destination "c:\Destination Two"
Here is what it looks like in PowerShell:
Copying Multiple Files
Now, let’s copy more than one file at a time. Note that the file paths use different drives. Remember that if the destination directory doesn’t exist, PowerShell will create it.
Copy-Item -Path "C:\source\file1.txt","C:\Source\file2.txt" -Destination "D:\Destination Two"
Copying Files with Renaming
You can copy a file to a new folder and rename it in the process using the below command:
Copy-Item -Path "C:\Source\file1.txt" -Destination "C:\Destination Two\NewName1.txt"
Here is what it looks like in PowerShell:
Copying Folders with PowerShell
The copying ability of PowerShell isn’t just limited to files – you can also copy a folder using the Copy-Item cmdlet to new locations. Below, we show you how to use the PowerShell copy folder and contents command.
Basic Folder Copy Example
Use the PowerShell copy folder command below to copy a folder to a different location. This PowerShell copy command will copy all files in the “source” folder and place them in the destination folder.
Copy-Item -Path "C:\source\folder" -Destination "D:\destination"
Copying Folders with Subfolders
What if the source folder had multiple subdirectories within it? Using the basic command above, anything within the subfolders would have been ignored. If you want to copy everything in the source folder, including the contents of subdirectories, you need to enact a PowerShell copy folder and subfolders command using the Recurse parameter.
Copy-Item -Path "C:\source\folder" -Destination "D:\destination" -Recurse
Copying and Merging Multiple Folders
Let’s say you want to copy the files of two source folders and merge them into a single destination folder. That is easily accomplished using the PowerShell copy contents of folder to another folder command. Here, two source paths are separated by a comma. They are copied and then merged into the destination folder.
Copy-Item -Path "C:\source1\*","C:\source2\*" -Destination "D:\destination"
Advanced File and Folder Copy Techniques
Using Wildcards in File Paths
Wildcards allow you to copy multiple files or folders that match a specific pattern without listing each item individually. They are ideal for dealing with large numbers of files or folders, as using wildcards can significantly reduce the amount of code you need. In the example below, the wildcard is used for any .txt file:
Copy-Item -Path "C:\source\*.txt" -Destination "C:\Destination Two"
Here’s what it looks like in PowerShell:
Filtering Files with Include and Exclude Parameters
There will be times when you want to exclude specific files within a folder for copying. You may want to exclude or only include certain file types or file versions or not include specific files that contain sensitive information. As such, you’ll likely want to exclude temporary or unnecessary files during a backup or migration process.
In the example below, we are copying and specifying that all log files should be considered for copying; however, any log file that also has a .tmp extension will be excluded.
Copy-Item -Path "C:\source\*" -Destination "D:\destination" -Include "*.log" -Exclude "*.tmp"
Using the Force Parameter to Overwrite Files
By default, Copy-Item will overwrite existing files at the destination without prompting. Sometimes, you might encounter a situation where the destination folder contains a read-only file with the same name as the file you’re trying to copy. By default, Copy-Item will not overwrite this read-only file. However, you can override this behavior and force the overwrite using the -Force parameter. Here’s an example of how to use it:
Copy-Item -Path "C:\source\file.txt" -Destination "D:\destination" -Force
Copying Files and Folders to Remote Computers via Copy-Item
Although there are situations where you might need to copy files and folders to different drive locations on a local computer, the true strength of the Copy-Item cmdlet lies in its ability to facilitate the transfer of files and folders between remote computers.
Setting Up a Remote Session with New-PSSession
Let’s say you want to copy some files to a remote computer using PowerShell. While you may have local admin rights, your current account may not have the proper rights to the destination computer. You will also have to know the computername of the remote machine. In this case, you must establish a remote session with the new computer using an alternative credential. You can enact PowerShell copy file to folder using the $session command below.
$session = New-PSSession -ComputerName "RemotePC" -Credential "User"
Copying Files to a Remote Computer
You can now copy files to the remote computer using the established session.
Copy-Item -Path "C:\source\file.txt" -Destination "C:\remote\destination" -ToSession $session
Copying Files from a Remote Computer
Of course, you may want to copy files from a remote computer to your local computer. To do this, use the following command.
Copy-Item -Path "C:\remote\source\file.txt" -Destination "C:\local\destination" -FromSession $session
Recursively Copying Remote Folders
In the previous examples involving remote computers, subfolders, and their contents were not included in the copy operation. To include the entire contents of the source item path, including all subfolders and files, add the -Recurse parameter to the Copy-Item command, just as we did with local copy operations.
Copy-Item -Path "C:\remote\source\folder" -Destination "C:\local\destination" -FromSession $session -Recurse
Error Handling and Verification
Using WhatIf and Confirm Parameters
The WhatIf parameter allows you to verify the outcome of a command without making any changes. For instance, as shown below, you might want to confirm that the source and destination paths are correct before executing the copy operation.
You can also check for overwrite behavior, which shows which files will be overwritten at the destination, helping you avoid unintended data loss. WhatIf helps you understand exactly which items will be copied. The command parameter is shown below.
Copy-Item -Path "C:\Source\File1.txt" -Destination "C:\Destination Two" -WhatIf
By default, most PowerShell cmdlets make changes to the system without confirmation from the user. There may be instances where you want the user to confirm an action if it is executed. The best example would be if you used PowerShell to remove a file. In the example below, you use the confirm command to prompt the user for confirmation.
Remove-Item -Path C:\file.txt -Confirm
The command will be executed in PowerShell, as shown below:
You can add the -Confirm parameter to any Copy-Item command.
Verifying the Copy Process
When using PowerShell to back up critical files, you may want to verify that the copy process occurred. You can create a simple PowerShell script, such as the one below, to confirm file copying by comparing file counts, sizes, and timestamps.
# Define source and destination paths
$source = "C:\SourceFolder"
$destination = "C:\DestinationFolder"
# Copy the files from source to destination
Copy-Item -Path $source\* -Destination $destination -Recurse
# Confirm the files were copied by checking if they exist in the destination folder
$sourceFiles = Get-ChildItem -Path $source
$allCopied = $true
foreach ($file in $sourceFiles) {
$destinationFile = Join-Path $destination $file.Name
if (Test-Path $destinationFile) {
Write-Host "File '$($file.Name)' was copied successfully."
} else {
Write-Host "File '$($file.Name)' failed to copy."
$allCopied = $false
}
}
if ($allCopied) {
Write-Host "All files copied successfully."
} else {
Write-Host "Some files failed to copy."
}
Handling Errors and Retries
You may want to utilize error handling for large file copying to ensure that your scripts operate correctly and can recover from unexpected failures. In PowerShell, the primary way to handle errors is through try-catch blocks. The script below utilizes the try-catch to handle errors when copying files
# Define source and destination paths
$source = "C:\SourceFolder"
$destination = "C:\DestinationFolder"
# Function to copy files with error handling
function Copy-Files {
try {
# Copy files and set error action to stop failure
Copy-Item -Path $source\* -Destination $destination -Recurse -ErrorAction Stop
Write-Host "Files copied successfully."
}
catch {
# Log the error message
Write-Error "An error occurred while copying files: $($_.Exception.Message)"
# Perform additional actions, like retrying or logging
}
finally {
Write-Host "Copy operation complete."
}
}
# Execute the function
Copy-Files
Practical Examples and Use Cases of Copy-Item Cmdlet
Detailed Examples of Common Tasks
- Copying Files from a Failing Hard Drive: A hard drive shows signs of failure, and critical files need to be copied to a safe location before the drive fails.
- Backup Automation for Daily File Changes: For disaster recovery, a company might need to back up all files in a critical directory to a backup server.
- Migration from an On-Prem Server to Cloud Storage: A company might want to migrate its local server’s documents from local drives to a cloud storage provider such as Azure or AWS.
- Deploying Configuration Files to Multiple Servers: A system administrator wants to deploy updated configuration files from
C:\ConfigUpdatesto a list of remote servers.
Real-World Scenarios and Solutions
A complex file structure can present some challenging instances when using the Copy-Item cmdlet. For example, long file paths can be a problem for older Windows versions that don’t support file paths greater than 260 characters. In those instances, you may want to use UNC paths rather than local file paths.
There may be instances when you need to use the -LiteralPath parameter in the Copy-Item cmdlet. This might be necessary when the path contains special characters (like [, ], or *) that PowerShell might otherwise interpret as wildcard characters or escape sequences.
Permission issues are also a common problem. You can use the -Force parameter to override some restrictions or run PowerShell as an administrator.
Sample Scripts for Automation
It is in your interest to automate as many manual tasks as possible to streamline them and avoid human error. Below is an example of a PowerShell script that is used to back up a folder to a backup directory.
# Define source and destination directories
$sourcePath = "C:\SourceDirectory"
$backupPath = "D:\BackupDirectory"
# Get current timestamp to append to the backup folder
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
# Create a new folder for the current backup with timestamp
$backupDestination = "$backupPath\Backup_$timestamp"
New-Item -ItemType Directory -Path $backupDestination
# Copy all files and directories from the source to the backup folder
try {
Copy-Item -Path $sourcePath -Destination $backupDestination -Recurse -Force
Write-Output "Backup completed successfully on $(Get-Date)"
} catch {
Write-Output "An error occurred during the backup: $_"
}
# Optional: Clean up old backups (e.g., delete backups older than 30 days)
$daysToKeep = 30
$oldBackups = Get-ChildItem -Path $backupPath -Directory | Where-Object { $_.CreationTime -lt (Get-Date).AddDays(-$daysToKeep) }
foreach ($backup in $oldBackups) {
try {
Remove-Item -Path $backup.FullName -Recurse -Force
Write-Output "Old backup removed: $($backup.FullName)"
} catch {
Write-Output "An error occurred while deleting old backups: $_"
}
}
Tips and Best Practices
Best Practices for Using Copy-Item
While the Copy-Item cmdlet is straightforward, here are a few best practices that might help you in more complex circumstances.
- Run PowerShell as Administrator
- Use the -Recurse parameter to copy entire directory structures.
- Utilize the -Force parameter judiciously to avoid unintended overwrites
- When copying large directories, consider alternatives such as Robocopy or other tools better suited for large jobs.
- Consider using -WhatIf for testing your commands to see what might happen without making actual changes.
Common Pitfalls and How to Avoid Them
In addition to best practices, you should also keep these common pitfalls in mind when using PowerShell scripting:
- Avoid using incorrect or relative paths that don’t resolve as expected by using full paths
- It is easy to forget about underlying subdirectories, so use the -Recurse parameter to ensure that all files contained in the parent directory are copied.
- Insufficient permission will prevent you from completing copy operations, especially when remote machines are involved. Ensure proper permissions and use elevated privileges when necessary.
- When complex copy operations are not completed correctly, use try-catch blocks and implement proper error logging.
Performance Considerations and Optimizations
Copying substantial data sets can consume much processing power on your computer. Parallel processing is a computing technique that involves breaking down a task into smaller parts and executing them simultaneously across multiple processors or cores. Parallel processing can significantly improve performance when applied to file operations like those performed by the Copy-Item cmdlet. Instead of copying files one at a time sequentially, parallel processing allows multiple files to be copied concurrently, utilizing the total capacity of modern multi-core processors. This approach can dramatically reduce the time required for large copy operations, as it takes advantage of available system resources more efficiently. While the Copy-Item cmdlet doesn’t natively support parallel processing, PowerShell provides mechanisms like ForEach-Object -Parallel that can be used with Copy-Item to achieve parallel file copying. This can potentially provide substantial performance gains in scenarios involving numerous files or complex directory hierarchies. A basic example is shown below:
<$sourcePath = "C:\SourceFolder"
$destPath = "D:\DestinationFolder"
Get-ChildItem $sourcePath | ForEach-Object -Parallel {
Copy-Item $_.FullName -Destination $using:destPath -Force
} -ThrottleLimit 8
Conclusion
The Copy-Item cmdlet command is a versatile tool in PowerShell for managing file and directory operations. It has a variety of parameters to cover multiple situations, such as the ability to specify a copy item path and implement error handling. Whether you’re using PowerShell script to copy files from source to destination or to copy files locally or across remote systems, the Copy-Item cmdlet can perform essential copy functions efficiently. Consider implementing parallel processing to enhance performance for large and complex datasets or explore specialized tools designed for handling extensive data transfers. Mastering the Copy-Item cmdlet ensures accurate file transfers, making it an essential component of any PowerShell user’s toolkit, while understanding its limitations allows for informed decisions on when to employ alternative methods.
Kevin Horvatin is a Lead Software Architect at Netwrix and responsible for Netwrix Privilege Secure. A software developer for over 20 years, he has worked with PowerShell and C# since they were introduced.
To copy and rename a file in PowerShell, you can use the `Copy-Item` cmdlet followed by the original file path and the new file path with the desired name.
Copy-Item -Path "C:\path\to\original\file.txt" -Destination "C:\path\to\new\file_renamed.txt"
Understanding PowerShell Basics
What is PowerShell?
PowerShell is a powerful scripting and automation framework developed by Microsoft. It is designed to help users automate tasks and manage systems more efficiently through command-line interface (CLI) and scripting. With its extensive range of cmdlets, PowerShell allows users to perform complex operations easily, making it an essential tool for system administrators and IT professionals.
Why Use PowerShell for File Management?
Using PowerShell for file management offers several advantages over traditional graphical user interfaces (GUIs):
- Automation: PowerShell scripts can automate repetitive tasks, saving time and minimizing errors.
- Flexibility: Users can manipulate files, folders, and system settings in a flexible manner using complex commands tailored to their needs.
- Batch Processing: Users can process multiple files and directories in a single command without needing to click through menus.
PowerShell Concatenate Files: A Simple Guide
The Copy-Item Cmdlet in PowerShell
What is the Copy-Item Cmdlet?
The `Copy-Item` cmdlet is used in PowerShell to copy files and directories from one location to another. This command is essential when you need to duplicate files without altering the original.
Syntax:
Copy-Item -Path <string> -Destination <string> [-Recurse] [-Force]
Basic Usage of Copy-Item
To copy a single file, you can use the following command:
Copy-Item -Path "C:\Source\file.txt" -Destination "C:\Destination\file.txt"
In this example:
- -Path specifies the location of the file you want to copy.
- -Destination indicates where you want the new copy to be created.
By using the `-Recurse` parameter, you can copy entire directories and their contents.
PowerShell -Command Example: Quick Guide for Beginners
Renaming Files in PowerShell
Introduction to the Rename-Item Cmdlet
The `Rename-Item` cmdlet allows users to change the name of an existing item, such as a file or a folder. This command works seamlessly within PowerShell, empowering users to rename files without opening them or using a graphical interface.
Syntax:
Rename-Item -Path <string> -NewName <string>
Basic Usage of Rename-Item
Here’s how to rename a single file:
Rename-Item -Path "C:\Destination\file.txt" -NewName "newfile.txt"
This command effectively updates the name of `file.txt` to `newfile.txt`.
Mastering PowerShell: Rename File Extension in Seconds
Combining Copy and Rename Operations
Step-by-step Approach
It’s possible to optimize your workflow by combining the `Copy-Item` and `Rename-Item` commands in a sequence. This is especially useful when you want to immediately rename a file after copying it.
Example of Copying and Renaming in One Go
Here’s how to perform both actions in two simple commands:
Copy-Item -Path "C:\Source\originalFile.txt" -Destination "C:\Destination\originalFile.txt"
Rename-Item -Path "C:\Destination\originalFile.txt" -NewName "renamedFile.txt"
In this example:
- The first command creates a copy of `originalFile.txt` in the `C:\Destination` directory.
- The second command renames the copied file to `renamedFile.txt`. This structure is easy to follow and ensures clarity in your script.
Mastering PowerShell Noprofile for Swift Command Execution
Handling Errors and Troubleshooting
Common Errors When Copying and Renaming
When working with file operations, it’s essential to be aware of potential errors. Common issues include:
- File Not Found: If the specified source file does not exist, PowerShell will throw an error.
- Permission Issues: You may encounter problems if you do not have the necessary permissions to access or modify the files.
- Path Format Problems: Always ensure that the file path is correctly formatted and that paths do not contain illegal characters.
Tips for Successful Execution
To improve reliability, consider performing error checks before executing commands. For example, you can use the `Test-Path` cmdlet to verify that the source file exists:
if (Test-Path "C:\Source\file.txt") {
Copy-Item -Path "C:\Source\file.txt" -Destination "C:\Destination\file.txt"
} else {
Write-Host "Source file does not exist."
}
For more robust error management, implement `try-catch` blocks:
try {
Copy-Item -Path "C:\Source\file.txt" -Destination "C:\Destination\file.txt"
} catch {
Write-Host "An error occurred: $_"
}
PowerShell Rename Folder: A Quick How-To Guide
PowerShell Scripting for File Management
Creating a Script to Copy and Rename Files
Creating a script to automate the file copying and renaming process enhances efficiency, especially for tasks performed repeatedly. Here’s a simple example:
$sourcePath = "C:\Source\originalFile.txt"
$destinationPath = "C:\Destination\renamedFile.txt"
Copy-Item -Path $sourcePath -Destination $destinationPath
Rename-Item -Path $destinationPath -NewName "newFile.txt"
This script defines the source path and destination path variables, then executes the copy and rename operations.
Automating File Management Tasks
To further enhance your productivity, consider scheduling your PowerShell scripts to run at specified intervals using Task Scheduler. This way, you can automate file management tasks without manual intervention, thus maintaining workflow efficiency.
PowerShell Copy-Item: Create Folder Made Easy
Conclusion
Mastering the PowerShell copy and rename file operations empowers users to manage their files effectively. By understanding cmdlets like `Copy-Item` and `Rename-Item`, you can navigate through your data with confidence and ease. Whether you are an IT professional or a casual user, leveraging PowerShell for file tasks can save you time and effort.
Powershell Open Excel File: A Quick Guide
Additional Resources
To further enhance your understanding and skills in PowerShell, consider exploring Microsoft’s official PowerShell documentation and taking advantage of online tutorials related to file management and scripting techniques.
Mastering the PowerShell Profiler for Efficient Scripting
Call to Action
Engage with us for in-depth PowerShell training and resources that will help you elevate your skills and streamline your IT tasks effectively!
Windows PowerShell предоставляет пользователям четыре способа работы с файлами. В данной статье речь пойдет о командах, которые были созданы специально для файлов. Команды, которые вы можете использовать для работы с файлами:Get-ChildItem Get-Item Copy-Item Move-Item New-Item Remove-Item Rename-Item
Windows PowerShell предоставляет пользователям четыре способа работы с файлами.
- Применение составных команд. Существует ряд команд, созданных специально для работы с файлами. При помощи этих команд вы можете управлять файлами и путями к файлам так, как если бы работали с содержанием файлов.
- Применение команд DOS. PowerShell полностью совместим с командами DOS. Таким образом, то, что вы можете сделать при использовании DOS, вы можете сделать и при помощи PowerShell. PowerShell признает даже команду xcopy.
- Использование инструментария управления Windows Management Instrumentation (WMI). WMI предлагает иной механизм для управления файлами (например, изменение файловых свойств, поиск или переименование файла). Лучше всего запускать команды WMI в удаленном режиме.
- Применение методов Microsoft. NET Framework. Пространство имен. NET System.IO доступно через командную строку PowerShell. Эта строка включает в себя классы System.IO.File и System.IO.FileInfo.
В данной статье я расскажу о командах, которые были созданы специально для файлов. Вот те команды, которые вы можете использовать для работы с файлами:
Get-ChildItem Get-Item Copy-Item Move-Item New-Item Remove-Item Rename-Item
Использование Get-ChildItem
Команда Get-ChildItem возвращает элементы, обнаруженные в одном или нескольких указанных местах. Местоположение может быть контейнером файловой системы, таким как каталог, или местом, показанным другим провайдером, таким как подраздел реестра или хранилище сертификатов. Вы можете задействовать параметр Recurse данной команды, чтобы добраться до элементов во всех подпапках.
Если использовать эту команду без параметров, она возвращает все дочерние элементы (такие как подпапки и файлы) в текущем местоположении. Например, если текущее местоположение – корневой каталог H, то запуская команду Get-ChildItem, вы получите результаты, похожие на те, что показаны на экране 1.
|
| Экран 1. Результаты работы Get-ChildItem |
Используя параметры, вы можете получить информацию, которая вам нужна. Например, следующая команда возвращает все файлы. log в корневом каталоге C, включая подкаталоги:
Get-ChildItem C:\* -Include *.log -Recurse -Force
Как мы видим, эта команда использует параметры -Include, -Recurse и –Force. Параметр –Include служит для возвращения заданных элементов. Он поддерживает использование групповых символов и является идеальным для указания расширения имени файла. Параметр –Recurse дает PowerShell указание возвращать подпапки наряду с файлами. Параметр –Force добавляет скрытые и системные файлы к выходным данным.
После запуска этой команды вы, вероятно, получите обширный список сообщений об ошибках доступа. В зависимости от настроек и политик безопасности системы, доступ к некоторым каталогам (например, Recycle Bin, Start Menu, пользовательские папки) ограничен и их нельзя прочитать. Вы можете скрыть эти сообщения об ошибках, указав параметр -ErrorAction SilentlyContinue.
Следующая команда дает те же результаты, что и предыдущая, потому что параметр –Path понимает групповые символы:
Get-ChildItem -Path C:\*.log -Recurse -Force
Для некоторых параметров команд PowerShell имя параметра вы можете опустить, если знаете, что параметр находится в той позиции, которая нужна PowerShell. Так происходит при использовании параметра –Path команды Get-ChildItem. Таким образом, следующая команда выдаст тот же результат, что и предыдущая команда:
Get-ChildItem C:\*.log -Recurse -Force
Параметр –Path может принимать множественные аргументы, разделенные запятыми. Например, предположим, что вы хотите возвратить. log-файлы из двух мест: корневого каталога С и корневого каталога Н, последний является текущим (то есть местоположением по умолчанию). Для выполнения этого действия нужно указать значение C:\* для получения всех файлов журналов из корневого каталога С и значение * для получения всех файлов журналов из корневого каталога Н (поскольку корневая папка Н является местоположением по умолчанию, вам не нужно указывать H:\.). Необходимо разделить два аргумента запятой, например так:
Get-ChildItem C:\*, * -Include *.log -Force
В результатах примера на экране 2 обратите внимание на атрибут «h» в колонке Mode корневого каталога Н. Этот атрибут показывает, что файл ntuser.dat.LOG является скрытым. Это обнаруживается при помощи параметра –Force.
|
| Экран 2. Вывод скрытых файлов |
Хотя в примерах это и не показано, вы можете обратиться к Get-ChildItem при помощи дополнительных имен, псевдонимов. Вот три встроенных псевдонима: dir (как в DOS команда dir), gci и ls (как команда ls в UNIX).
Использование команды Get-Item
Команда Get-Item возвращает заданные элементы из назначенных местоположений. Как и ChildItem, Get-Item может применяться для навигации по различным типам хранилищ данных. В отличие от Get-ChildItem, Get-Item не имеет местоположения по умолчанию, поэтому вы должны всегда предоставлять, как минимум, одно местоположение с помощью параметра –Path. Хотя сам параметр и нужен, указывать имя параметра не требуется. Например, вот простая команда, которая использует «точку» для возвращения информации о текущем каталоге (в данном случае корневая папка Н):
Get-Item.
Результаты показаны на экране 3. Команда Get-Item позволяет задействовать групповой символ * для возвращения всего содержимого элемента (то есть всех дочерних элементов). Например, следующая команда возвращает весь контент текущего каталога (в данном случае корневого каталога Н). Точка и символ звездочки могут быть использованы как компоненты в пути файла, но вы должны еще указать косую черту как разделитель папок:
Get-Item. \*
|
| Экран 3. Использование Get-Item для вывода информации о текущей папке |
Результаты вы можете увидеть на экране 4. Важно понимать, что команды PowerShell, включая Get-Item, возвращают объекты. Команда Get-Item возвращает объекты System.IO.DirectoryInfo, которые содержат несколько методов и свойств, которые вы можете использовать. Чтобы увидеть эти методы и свойства, можно передать результаты команды Get-Item в команду Get-Member. Если вы хотите увидеть эти свойства, можете запустить такую команду:
Get-Item. | Get-Member -MemberType Property
|
| Экран 4. Использование Get-Item для вывода всего содержимого текущей папки |
Как показано на экране 5, свойство LastAccessTime возвращает дату и время, когда к указанному каталогу был в последний раз осуществлен доступ.
|
| Экран 5. Изучение свойств объекта System.IO.DirectoryInfo |
Например, если вы хотите выяснить, когда к текущему каталогу был осуществлен доступ в последний раз, вы запускаете команду:
(Get-Item. ).LastAccessTime
Заметим, что в этой команде вызов Get-Item. заключен в круглые скобки и что между закрывающей круглой скобкой и LastAccessTime стоит точка. Круглые скобки вокруг вызова «Get-Item. » нужны для того, чтобы возвращенные объекты сохранялись в памяти и вы могли бы выполнять с ними дополнительные операции. В этом случае операцией является поиск возвращаемого значения свойства LastAccessTime объекта. В PowerShell вы используете символ точки для получения доступа к ряду свойств объекта и методов. Вот почему следует вставить точку между закрывающейся скобкой и LastAccessTime.
Существует коллекция специальных свойств, которая называется NoteProperty. Вы можете применять ее для того, чтобы сузить выводимые результаты для определенного типа объекта. Вы можете использовать Get-Member с параметром -MemberType NoteProperty, чтобы узнать о специальных свойствах этой коллекции:
Get-Item. | Get-Member -MemberType NoteProperty
Если вы запустите эту команду, то обнаружите, что коллекция возвращает шесть свойств: PSChildName, PSDrive, PSIsContainer, PSParentPath, PSPath и PSProvider. Свойство PSIsContainer коллекции NoteProperty показывает, является ли объект контейнером (папкой). Свойство возвращает True, когда объект является папкой, и False, когда он является файлом. Вы можете использовать это свойство для ограничения вывода Get-Item папками:
Get-Item C:\* | Where-Object { $_.PSIsContainer }
Давайте обсудим эту команду подробнее. Ее результаты показаны на экране 6. Вы передаете по конвейеру весь контент корневого каталога С команде Where-Object, которая позволяет отфильтровать объекты. В этом случае вы используете PSIsContainer из NoteProperty для фильтрации выходных данных, и, таким образом, возвращаются только каталоги. Автоматическая переменная $_ представляет каждый файловый объект, как только он передается команде по конвейеру.
|
| Экран 6. Ограничение вывода команды Get-Item только папками |
Как и в случае с Get-ChildItem, вы можете обращаться к Get-Item по дополнительному имени. У Get-Item есть одно встроенное дополнительное имя: gi.
Использование Copy-Item
Команда Copy-Item является реализацией в PowerShell команды copy bp DOS и команды cp из UNIX. Но помимо этого, Copy-Item сконструирован для работы с данными, выдаваемыми любым провайдером. Первыми двумя параметрами команды являются -Path (вы используете его для указания элемента, который хотите скопировать) и –Destination (вы применяете его для указания места, в которое хотите скопировать этот элемент). Они позиционные, поэтому имена параметров можно опустить. Например, следующая команда копирует файл test.txt из папки C:\Scripts в папку C:\Backups\Scripts:
Copy-Item C:\Scripts\test.txt C:\Backups\Scripts
Параметр –Path принимает групповые символы, поэтому вы можете копировать несколько файлов сразу. Например, следующая команда копирует все файлы в папке C:\Scripts в папку C:\Backups\Scripts:
Copy-Item C:\Scripts\* C:\Backups\Scripts
Чтобы получить более детальное управление операцией копирования, вы можете задействовать параметры -Recurse, -Filter и –Force. Так, следующая команда копирует все файлы. txt, содержащиеся в C:\Scripts в C:\Temp\Text:
Copy-Item -Path C:\Scripts -Filter *.txt -Recurse ` -Destination C:\Temp\Text
Обратите внимание, что «обратная кавычка» в конце первой строки является символом продолжения строки в PowerShell.
Немного освоившись, вы можете вставить свойство FullName в параметр –Path для копирования тщательно отобранного списка файловых объектов, используя либо Get-Item, либо команду Get-ChildItem:
Get-ChildItem C:\* -include *.txt |
Where-Object { $_.PSIsContainer -eq $false -and `
$_.LastAccessTime -gt ($(Get-Date).AddMonths(-1))} |
ForEach-Object { Copy-Item $_.FullName C:\Temp}
На самом деле это предложение является комбинацией трех отдельных команд. Первая команда (то есть команда в первой строке) возвращает все файлы. txt в корневом каталоге С. Вторая команда (команда во второй и третьей строках) вычленяет список текстовых файлов таким образом, что содержит только те файловые объекты, чье свойство LastAccessTime больше, чем месяц назад. Третья команда (команда в последней строке) вставляет каждое файловое имя в свойство –Path, располагающееся в Copy-Item, используя команду ForEach-Object. Слишком сложно для вас? Тогда можете принять входные данные по конвейеру. Только убедитесь, что вы указали имя параметра –Destination так, чтобы Copy-Item знала, что делать с этими входными данными, так как данный параметр находится не в ожидаемой позиции:
Get-ChildItem C:\* -Include *.log | Copy-Item -Destination C:\Temp
Хотя в наших примерах это и не показано, вы можете обратиться к Copy-Item через дополнительные имена. Существует три псевдонима: copy, cp, cpi.
Использование Move-Item
Move-Item очень похожа на Copy-Item. Фактически, если вы заменяете Copy-Item на Move-Item в любой из команд, представленных в предыдущем разделе, команды будут вести себя во многом так же, за исключением того, что исходные файлы будут удалены в исходную папку.
Однако есть одно важное различие. Если вы запустите одну и ту же команду Copy-Item дважды, то обнаружите, что PowerShell переписывает существующий файл в папку назначения без какого-либо предупреждения.
Move-Item более осторожна в этом смысле и вместо удаления выдает ошибку. Например, если вы запускаете команду
Get-ChildItem C:\* -Include *.txt |
Where-Object `
{ $_.LastAccessTime -gt ($(Get-Date).AddMonths(-1))} |
ForEach-Object { Move-Item $_.FullName C:\Temp}
то получите ошибку Cannot create a file («нельзя создать файл»), так как файл уже существует. Использование параметра –Force приводит к тому, что Move-Item переписывает существующий файл.
Помимо параметра –Force, вы можете задействовать параметры Recurse и –Filter в команде Move-Item, чтобы настраивать ее. Например, следующая команда перемещает текстовые файлы в папке C:\Scripts и ее подпапках в папку C:\Temp\Text. В данном случае вам нужно указать имя параметра –Destination, поскольку вы не используете этот параметр в той позиции, где его ожидает PowerShell:
Move-Item C:\Scripts -Filter *.txt -Recurse ` -Destination C:\Temp\Text
Как и Copy-Item, Move-Item имеет три псевдонима: move, mv и mi.
Использование New-Item
New-Item играет двойную роль — создателя каталога и файла (кроме того, она может создавать разделы и параметры реестра). Когда вы хотите создать файл, вам нужно указать параметры –Path и –ItemType. Как было показано выше, параметр –Path является позиционным, таким образом, не требуется имя параметра –Path, когда вы задаете путь и имя (то есть путь к файлу) сразу же после имени команды. Также следует указать параметр –ItemType при помощи флажка»file«. Вот пример:
New-Item 'C:\Documents and Settings\Nate\file.txt' ` -ItemType»file«
Параметр –Path может принимать массив строк так, что вы можете создавать несколько файлов за раз. Вам просто нужно разделить пути при помощи запятых. Вдобавок, необходимо вставить сначала параметр -ItemType»file«, который означает, что вам нужно указать имя параметра –Path, поскольку он теперь не первый параметр после имени команды:
New-Item -ItemType»file«-Path»C:\Temp\test.txt«, ` »C:\Documents and Settings\Nate\file.txt«, ` »C:\Test\Logs\test.log«
Если файл с точно таким же именем пути файла уже существует, вы получите ошибку. Однако вы можете указать параметр –Force так, что New-Item перепишет существующий файл.
Что на самом деле примечательно, так это то, что New-Item позволяет вставлять текст в файл посредством параметра –Value:
New-Item 'C:\Documents and Settings\Nate\file.txt' ` -ItemType»file«-Force ` -Value»Here is some text for my new file.«
Не забудьте указать параметр –Force, если файл уже существует. Иначе система выдаст ошибку.
Параметр –Value может принимать ввод данных по конвейеру, что является отличным способом перенаправлять вывод данных других команд в файл. Вам нужно просто конвертировать выходные объекты в строку, используя Out-String (если вы этого не сделаете, New-Item создаст новый файл для каждого объекта). Например, следующая команда возвращает информацию обо всех файлах из корневого каталога С, конвертирует информацию о файлах в строку, а затем пишет эту информацию в файл H:\C Listing.txt:
Get-ChildItem C:\* | Out-String | New-Item -Path»H:\C Listing.txt«-ItemType»file«-Force
New-Item имеет только одно встроенное дополнительное имя: ni.
Использование Remove-Item
Remove-Item навсегда удаляет ресурс с указанного диска, то есть она не перемещает его в корзину. Таким образом, если вы используете Remove-Item для удаления файла, то нет иного способа вернуть его, кроме как через программу восстановления файлов.
Вы указываете, какой файл должна удалять Remove-Item при помощи параметра –Path. Он позиционный, поэтому вам не нужно указывать имя параметра –Path, если оно идет сразу же за именем команды. Например, вот команда для удаления файла test.txt, который был ранее скопирован в папку C:\Backups\Scripts:
Remove-Item»C:\Backups\Scripts\test.txt«
Давайте рассмотрим другой пример. Следующая команда удаляет все файлы. txt (что указано в параметре –Include) в папке C:\Scripts, кроме тех файлов, которые имеют слово test где-либо в файловом имени (что указано в параметре –Exclude):
Remove-Item C:\Scripts\* -Include *.txt -Exclude *test*
Будучи, по сути, опасным инструментом, Remove-Item предоставляется с парой элементов защиты. Прежде всего, если вы пытаетесь удалить все из папки, которая содержит непустые подпапки, вы получите запрос на подтверждение Confirm. Например, предположим, что C:\Scripts содержит непустые подпапки и вы запускаете такую команду:
Remove-Item C:\Scripts\*
Нужно подтвердить, что вы хотите удалить непустые подпапки, как показано на экране 7.
|
| Экран 7. Запрос на подтверждение удаления при использовании Remove-Item |
Если вы хотите запустить сценарий, который использует Remove-Itemм для удаления всего содержимого папок, включая содержимое подпапок, вам нужен способ запускать Remove-Item без участия пользователя. Этот способ – включение флажка –Recurse.
Второй элемент защиты – это параметр –WhatIf. Если вы включаете его в команду Remove-Item, то PowerShell покажет, какие элементы будут удалены, вместо того, чтобы просто удалить их. В силу деструктивной природы операций удаления, имеет смысл выполнять пробное применение команды Remove-Item с параметром –WhatIf, как здесь:
Remove-Item c:\* -Recurse -WhatIf
Результаты примера показаны на экране 8. Заметьте, что результаты могут включать в строку сообщение об ошибке Cannot remove the item at ‘C:\Users’ because it is in use. Такая ситуация возникает, если текущая рабочая папка является подпапкой каталога, которую вы пытаетесь удалить (в примере – подпапка корневого каталога С).
|
| Экран 8. Применение Remove-Item с параметром -WhatIf Parameter |
Что касается дополнительных имен, то Remove-Item стоит особняком. У него шесть псевдонимов: del, erase, rd, ri, rm и rmdir.
Использование Rename-Item
Команда Rename-Item используется, когда вы хотите переименовать ресурс внутри пространства имен, предоставленного провайдером PowerShell. Первый параметр Rename-Item – это –Path, а второй параметр -NewName. Параметр –NewName, как и следовало ожидать, задает новое имя ресурса. Если Rename-Item обнаруживает не только имя, но и путь, он выдаст ошибку. Например, если вы хотите сменить имя файла C Listing.txt из корневого каталога Н на имя c_listing.txt, вам потребуется запустить такую команду:
Rename-Item -Path»H:\C Listing.txt«-NewName c_listing.txt
Поскольку -Path и -NewName являются позиционными параметрами, вы можете пропускать имена параметров до тех пор, пока они находятся в ожидаемых позициях:
Rename-Item»H:\C Listing.txt" c_listing.txt
У Rename-Item есть одно ограничение – параметр –NewName ожидает одной строки без групповых символов. Однако вы можете обойти это требование, перечисляя элементы в каталоге. Вам нужно просто направить по конвейеру выходные данные команде Get-ChildItem в параметр –Path и указать параметр –NewName.
Например, следующая команда перечисляет все файлы в текущем каталоге и переименовывает каждый файл, заменяя все пробелы в файловых именах на подчеркивания:
Get-ChildItem * |
Where-Object {! $_.PSIsContainer } |
Rename-Item -NewName { $_.name -replace ' ','_' }
Давайте посмотрим, как работает эта команда. Выходные данные Get-ChildItem попадают в Where-Object, которая фильтрует выходные данные так, что возвращаются только файлы. Это достигается путем использования PSIsContainer из NoteProperty с логическим оператором -not (!) (в качестве альтернативы вы могли бы взять $_.PSIsContainer -eq $false, как это было сделано в предыдущем примере). Отфильтрованные выходные данные (файловые объекты) попадают в Rename-Item. Значение параметра –NewName в Rename-Item является блоком сценария. Этот блок будет выполнен перед командой Rename-Item. В блоке сценария автоматическая переменная $_ представляет каждый файловый объект, так как он попадает в команду через контейнер. Оператор сравнения –replace заменяет пробелы в каждом имени файла (‘ ‘) на символ подчеркивания (‘_’). Заметьте, что вы можете использовать выражение ‘\s’ для указания пробела, поскольку первый параметр принимает регулярные выражения. Даже скрытые файлы могут быть переименованы благодаря параметру –Force.
Rename-Item имеет два псевдонима: ren и rni.
Великолепная семерка
В данном руководстве я познакомил вас со способами взаимодействия PowerShell с файлами. В частности, мы изучили встроенные команды PowerShell, предназначенные для работы с файлами. Это Get-ChildItem, Get-Item, Copy-Item, Move-Item, New-Item, Remove-Item и Rename-Item.
