我写了一个Powershell脚本,它遵循以下步骤。
这个_DeletedFiles文件夹的意思是,即使有人删除了一个文件,我们也希望将它保存在某个地方至少60天。
现在这个脚本有点复杂,包括写入日志文件,测试路径,以及首先运行if语句等。
除了我想将服务器上删除的文件从BackUp复制到新文件夹的步骤外,所有似乎都有效。
此步骤与此类似:
$testfolder = Test-Path "$UsbDisk\$backupFolder"
# If a Backup folder already exist then Compare files and see if any changes have been made
if ( $testfolder -eq $true ) { #IF_2
# Copy deleted files to BackUp Folder
MyLog "Check for Deleted Files on E:\" 0
$source = "E:\"
$sourcelist = Get-ChildItem $source -Recurse
$destination = "$UsbDisk\$backupFolder\Data_01\_DeletedFiles"
foreach ($file in $sourcelist){
$result = test-path -path "E:\*" -include $file
if ($result -like "False"){
Copy-Item $file -Destination "$destination"
}
}
# Start Synchronizing E:\
MyLog "Start Synchronizing E:\" 0
Robocopy "E:\" "$UsbDisk\$backupFolder\Data_01" /mir /r:2 /w:3 /M /XD VM_*
MyLog "E:\ is up to Date" 0
# Copy deleted files to BackUp Folder
MyLog "Check for Deleted Files on F:\" 0
$source = "F:\"
$sourcelist = Get-ChildItem $source -Recurse
$destination = "$UsbDisk\$backupFolder\Data_02\_DeletedFiles"
foreach ($file in $sourcelist){
$result = test-path -path "F:\*" -include $file
if ($result -like "False"){
Copy-Item $file -Destination "$destination"
# Then Delete it from the BackUp
}
}
# Start Synchronizing F:\
MyLog "Start Synchronizing F:\" 0
Robocopy "F:\" "$UsbDisk\$backupFolder\Data_02" /mir /r:2 /w:3 /M /XD VM_*
MyLog "F:\ is up to Date" 0
}
我得到的错误无法复制文件,因为它们在目的地不存在;但是,它会尝试复制首先不应复制的文件。
我想知道是否有人有想法解决这个问题更优雅,或者如何修复我的代码片段。
答案 0 :(得分:1)
我认为问题可能出在test-path命令中。我会将include $file
替换为include $file.Name
。 include
参数需要一个字符串,而不是一个对象。
为了代码可维护性,我还会将($result -like "False")
替换为(-not $result
)。这是因为$result
将包含布尔值($true
或$false
),而不是字符串。