【发布时间】:2023-03-08 11:44:01
【问题描述】:
我正在尝试开发一个脚本,将 .txt 文件从两个源文件夹复制到一个目标文件夹。
我还想添加 2 个附加条件:
- 如果目标目录中已经存在文件,则跳过它
- 复制的文件不得早于当天
这是我做的,但它没有按预期工作:
$SourceDirItemsMITEMAvail = "\\wipfs02\Data\webshop\test\ecomcloud_import\carhartt\product\*"
$SourceDirCaproBPRIC = "\\wipfs02\Data\webshop\test\hybris_import\carhartt\product\*"
$TargetDirB2B = "\\wipfs02\Data\webshop\test\ecomcloud_import\carhartt\b2b\product\"
$ExcludeSubDir = "archive", "IDISC Test", "save", "archive_B2B", "archive_tmp", "Errors"
# Copy only the specific files
$SpecificTypesEcomCloudImport = "avail*", "items*", "MITEM*"
$SpecificTypesHybrisImport = "BPRIC*", "CAPRO*"
# Get the current date
$CurrentDateFiles = (Get-Date).Date
# Copy items from source directories and transfer them to the B2B Folder
For ($i=0; $i -lt $SourceDirItemsMITEMAvail.Count -and $SourceDirCaproBPRIC.Count; $i++) {
# If the copied files don't already exist into the target directory, then copy them
if (-not(Test-Path -Path $SourceDirItemsMITEMAvail, $SourceDirCaproBPRIC)) {
try {
# The copied files must not be older that the current day
$CopyFilesEcomCloudImportDir = Copy-Item $SourceDirItemsMITEMAvail -Exclude $ExcludeSubDir -Destination $TargetDirB2B -PassThru -Verbose -Include $SpecificTypesEcomCloudImport | Where-Object { $_.LastWriteTime -eq $CurrentDateFiles}
Write-Host ""$CopyFilesEcomCloudImportDir.Count" file(s) have been copied from $SourceDirItemsMITEMAvail to $TargetDirB2B."
# The copied files must not be older that the current day
$CopyFilesHybrisImportDir = Copy-Item $SourceDirCaproBPRIC -Exclude $ExcludeSubDir -Destination $TargetDirB2B -PassThru -Verbose -Include $SpecificTypesHybrisImport | Where-Object { $_.LastWriteTime -eq $CurrentDateFiles}
Write-Host ""$CopyFilesHybrisImportDir.Count" file(s) have been copied from $SourceDirCaproBPRIC to $TargetDirB2B."
}
catch {
"Error: $($_.Exception.Message)"
}
}else {
Write-Host "Cannot copy $CopyFilesEcomCloudImportDir because a file with that name already exists in the destination folder."
Write-Host "Cannot copy $CopyFilesHybrisImportDir because a file with that name already exists in the destination folder."
}
}
要么复制源目录中的所有文件,要么立即进入 else 条件。
如果我删除 if (Test-Path) 条件,它会从源中复制所有文件,甚至是那些早于当前日期的文件。
如果我让 if (Test-Path) 条件,它立即转到 else 语句。
您能帮我解决这个问题吗?谢谢!
【问题讨论】:
-
为什么不用Robocopy 来代替?它有很多选项和功能。
标签: powershell file date directory copy