powershell - 如何在备份脚本期间记录复制的项目?
问题描述
我需要制作基本/或更高级的备份脚本,将项目从文件夹 A 复制到文件夹 B,然后记录它所做的事情。
这可以很好地复制文件:
$source = 'path\gamybinis\*'
$dest = 'path\backup'
Get-ChildItem -Path $source -Recurse | Where-Object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5)
}| Copy-Item -Destination $dest -Recurse -Force
Write-Host "Backup started"
Pause
但在此之后我不能用 | 写日志 Out-File,所以我试过这个:
$source = 'path\gamybinis\*'
$dest = 'path\backup'
$logFile = 'path\log.txt'
$items = Get-ChildItem -Path $source -Recurse | Where-Object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5)
}
foreach($item in $items){
Out-File -FilePath $logFile -Append
Copy-Item -Path "$source\$item" -Destination $dest -Recurse -Force
}
Write-Host "Backup started"
Pause
这个完全没有做,我到底做错了什么?
(高级脚本部分是:备份最近修改的文件,然后将文件归档到 .rar/.zip,日志文件必须具有易于阅读的结构,并且日志文件应该包含备份期间用户在设备上工作的信息) - 对于那些想知道的人。
解决方案
如果您不能使用 robocopy,则可以在纯 PowerShell 代码中执行此操作
$source = 'path\gamybinis' # no need for '\*' because you're specifying -Recurse
$dest = 'path\backup'
$logFile = 'path\log.txt'
# test if the destination path exists. If not, create it first
if (!(Test-Path -Path $dest -PathType Container)) {
$null = New-Item -Path $dest -ItemType Directory
}
Write-Host "Backup started"
Get-ChildItem -Path $source -Recurse |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-5) } |
ForEach-Object {
$_ | Copy-Item -Destination $dest -Recurse -Force
Add-Content -Path $logFile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - Copied file '$($_.FullName)'"
}
Write-Host "Backup done"
从您的评论中,我了解到您在使用-Container
开关时遇到了问题。
下面的代码不使用它并在备份文件夹中创建复制文件的文件夹结构,严格使用 Powershell 代码:
$source = 'path\gamybinis' # no need for '\*' because you're specifying -Recurse
$dest = 'path\backup'
$logFile = 'path\log.txt'
Write-Host "Backup started"
Get-ChildItem -Path $source -File -Recurse |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddMinutes(-5) } |
ForEach-Object {
$target = Join-Path -Path $dest -ChildPath $_.DirectoryName.Substring($source.Length)
if (!(Test-Path $target -PathType Container)) {
# create the folder if it does not already exist
$null = New-Item -Path $target -ItemType Directory
}
$_ | Copy-Item -Destination $target -Force
Add-Content -Path $logFile -Value "$((Get-Date).ToString("yyyy-MM-dd HH:mm:ss")) - Copied file '$($_.FullName)'"
}
Write-Host "Backup done"
推荐阅读
- php - wordpress 插入帖子在边缘不起作用
- android - 使用 Volley 请求 XML REST API 的问题
- spring - SpringBoot Rest API 中的 EntityManager 和 SessionHolder 错误
- java - 自定义转换器未调用 spring data mongodb [无法序列化类错误]
- android - OpenGL中垂直平面上的纹理显示不正确
- node.js - npm - 如何在 npm 中设置 max-old-space-size
- azure-devops - 如何将 HTML 从 RSS 剥离到 Yammer 消息
- resharper - 在一段代码中禁用 resharper 换行符?
- javascript - $(element).position().top 返回错误值
- unit-testing - 解决在 H2 数据库中无法理解语句以进行单元测试的 flyway 迁移的最佳实践