由于某种原因,我的if语句在ForEach语句中没有正常运行。我认为这样做的唯一原因是,如果ForEach语句在$ {Source}声明之后停止,那将是奇怪的。
function new-Backup {
ForEach ($Source in $Sources){
${FileName} = Split-Path ${Source} -Leaf
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Backup Script Running..."
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Creating archive: ${FileName}-${TimeStamp}.zip"
WinRAR a -ep ${Destination}\${FileName}-${TimeStamp}.zip $Source
If(Test-Path -Path ${Destination}\${Filename}-${Timestamp}){
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Successfully created archive: ${FileName}-${TimeStamp}.zip"
Else{
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Failed to create archive: ${FileName}-${TimeStamp}.zip"
}
}
}
答案 0 :(得分:0)
我忘了包含Test-Path命令的文件扩展名,因此总是返回false。我也忘记了if语句的结束括号,它不允许if语句运行。更正的代码已发布在下方。
function new-Backup {
ForEach ($Source in $Sources){
${FileName} = Split-Path ${Source} -Leaf
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Backup Script Running..."
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Creating archive: ${FileName}-${TimeStamp}.zip"
WinRAR a -ep ${Destination}\${FileName}-${TimeStamp}.zip $Source
If(Test-Path -Path ${Destination}\${Filename}-${Timestamp}.zip){
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Successfully created archive: ${FileName}-${TimeStamp}.zip"
}Elseif(-Not(Test-Path -Path ${Destination}\${Filename}-${Timestamp}.zip)){
Add-Content ${Log}\${Timestamp}.log "[Information] $(Get-Timestamp): Failed to create archive: ${FileName}-${TimeStamp}.zip"
}
}