是的,我有一个简单的Copy-Item
脚本可以将文件从一个目标文件夹复制到另一个目标文件夹。
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$source,
[Parameter(Mandatory=$true)]
[string]$destination
)
Process {
Copy-Item -Path $source -Destination $destination -Recurse -Force
我正在releasecode.ps1
使用以下命令行运行:
。\ releasecode.ps1-源“ C:\ test \ from”-目标“ C:\ test \ to”
该from
文件夹具有以下结构:
.
├── from
├── stain.txt
├── test1.txt
├── folder
| ├── test2.bmp
正确复制到(在第一个副本上):
.
├── to
├── stain.txt
├── test1.txt
├── folder
| ├── test2.bmpthe
如果我之后直接重新运行它,该from
文件夹将被创建为“ to”中的目录,而不仅仅是覆盖现有结构:
.
├── to
├── stain.txt
├── test1.txt
├── folder
| ├── test2.bmp
├── from
| ├── stain.txt
| ├── test1.txt
| └── folder
| ├── test2.bmp
to
如果文件和文件夹当前存在,如何覆盖现有目录结构。
在Windows Box上运行
$PSVersionTable
:
您已经遇到了Copy-Item
与复制源目录有关的陷阱。
如果目标存在并且是文件夹,则cmdlet会将源复制到目标。
复制项目C:\ src \ a C:\ dst \ b- 递归 C:\ C:\ ├─dst├─dst | └─b| └─b └─src| └─一个 └─a⇒| ├─bar.txt ├─bar.txt| └─baz.txt └─baz.txt└─src └─a ├─bar.txt └─baz.txt
如果目标不存在,则cmdlet将源复制为目标。
复制项目C:\ src \ a C:\ dst \ b- 递归 C:\ C:\ ├─dst├─dst└─src| └─ b └─a| ├─bar.txt├─bar.txt⇒ | └─baz.txt └─baz.txt└─src └─a ├─bar.txt └─baz.txt
在PowerShell中处理此问题的惯用方式是确保首先存在目标文件夹,然后复制源文件夹的内容:
if (-not (Test-Path $destination)) {
New-Item -Type Directory -Path $destination | Out-Null
}
Copy-Item -Path $source\* -Destination $destination -Recurse -Force
或者,您可以使用robocopy
,而不会出现此问题:
robocopy C:\src\a C:\dst\b /s
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句