递归文件复制过程中的PowerShell错误检查
-
25-09-2019 - |
题
我有一个程序,拷贝文件夹和文件递归。 例如:
Copy-Item -path "$folderA" -destination "$folderB" -recurse
有时文件不复制。有没有一种方法,以“一步递归内”或更好的方式来做到这一点,这样我就可以在这个过程中,而不是病房后使某种错误检查。甚至可能做用于重新复制测试的路径和提示?
解决方案
可以。例如,下面的代码片段实际上将复制和检查可能出现的错误的每个文件。你也可以把你的自定义代码在开始检查一些先决条件:
get-childItem $source -filter *.* | foreach-object {
# here you can put your pre-copy tests...
copy-item $_.FullName -destination $target -errorAction SilentlyContinue -errorVariable errors
foreach($error in $errors)
{
if ($error.Exception -ne $null)
{
write-host -foregroundColor Red "Exception: $($error.Exception)"
}
write-host -foregroundColor Red "Error: An error occured during copy operation."
}
}
不隶属于 StackOverflow