[英]Split-Path + Join-Path functionality
I have a problem concerning the Split-Path
and Join-Path
cmdlets of MS PowerShell. 我遇到有关MS PowerShell的
Split-Path
和Join-Path
cmdlet的问题。 I want to copy an entire directory from the folder (including all folder and files therein) C:\\Testfolder
to the folder C:\\TestfolderToReceive
. 我想将文件夹(包括其中的所有文件夹和文件)的整个目录复制到
C:\\Testfolder
到文件夹C:\\TestfolderToReceive
。
For this task I use the following coding: 对于此任务,我使用以下代码:
$sourcelist = Get-ChildItem $source -Recurse | % {
$childpath = split-path "$_*" -leaf -resolve
$totalpath = join-path -path C:\TestfolderToReceive -childpath $childpath
Copy-Item -Path $_.FullName -Destination $totalpath
}
The problem arises with files which aren't directly in C:\\Testfolder
, but in subfolders of it (EXAMPLE: C:\\Testfolder\\TestSubfolder1\\Testsub1txt1.txt
). 问题不是由文件直接出现在
C:\\Testfolder
,而是在其子文件夹中(例如: C:\\Testfolder\\TestSubfolder1\\Testsub1txt1.txt
)。 All these files which are not directly in C:\\Testfolder
return "null" via the $childpath
variable. 所有不直接在
C:\\Testfolder
文件都通过$childpath
变量返回“ null”。
For example for the file C:\\Testfolder\\TestSubfolder1\\Testsub1txt1.txt
I would like it to return TestSubfolder1\\Testsub1txt1.txt
so that a new path called C:\\TestfolderToReceive
will be created by the Join-Path
functionality. 例如,对于文件
C:\\Testfolder\\TestSubfolder1\\Testsub1txt1.txt
我希望它返回TestSubfolder1\\Testsub1txt1.txt
以便通过Join-Path
功能创建一个名为C:\\TestfolderToReceive
的新路径。
Could someone explain me what I am doing wrong and explain me the correct way for tackling such a problem? 有人可以向我解释我做错了什么,并向我解释解决此类问题的正确方法吗?
I think you're overthinking this. 我认为您对此太想了。
Copy-Item
can do this for you on its own: Copy-Item
可以自己为您完成此操作:
Copy-Item C:\Testfolder\* C:\TestfolderToReceive\ -Recurse
The \\*
part is crucial here, otherwise Copy-Item
will recreate TestFolder
inside C:\\TestfolderToReceive
\\*
部分在这里至关重要,否则, Copy-Item
将在C:\\TestfolderToReceive
内部重新创建TestFolder
In this scenario, you could use Join-Path
to position the *
correctly: 在这种情况下,您可以使用
Join-Path
正确定位*
:
$SourceDir = 'C:\Testfolder'
$DestinationDir = 'C:\TestfolderToReceive'
$SourceItems = Join-Path -Path $SourceDir -ChildPath '*'
Copy-Item -Path $SourceItems -Destination $DestinationDir -Recurse
If you want a list of files copied, you can use the -PassThru
parameter with Copy-Item
: 如果要复制文件列表,可以将
-PassThru
参数与Copy-Item
:
$NewFiles = Copy-Item -Path $SourceItems -Destination $DestinationDir -Recurse -PassThru
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.