提问人:Omer Tirmizi 提问时间:11/2/2023 更新时间:11/3/2023 访问量:60
用于备份清理的 Powershell 脚本在 Windows Server 2016 中不起作用
Powershell script for Backup cleanup does not work in windows server 2016
问:
我一直在开发一个 PowerShell 脚本,该脚本会删除备份文件夹并仅保留最新的 3 个备份文件夹。我使用任务计划程序按计划测试运行脚本,并且它可以工作。 但是,当我在装有 Windows Server 2016 的计算机上实现它时,它会运行并提示完成脚本,但不会删除文件夹。我知道脚本已执行,因为我在脚本中附加了电子邮件通知详细信息。我收到提示完成任务的电子邮件,但未进行删除。
我在下面附上了我正在使用的脚本,希望我能在这个问题上得到一些帮助。
# Gets path of Backup folder
$backup_path = 'C:\Backup'
# Getting the subfolders inside the Backup folder
$subfolders = Get-ChildItem -Path $backup_path -Directory -Force
# Checks if the number of folders is more than 3**
if ($subfolders.Count -gt 3) {
# Sort subfolders by Creation Time
$sorted_subfolders = $subfolders | Sort-Object -Property CreationTime
# Getting number of subfolders to delete
$delete_count = $subfolders.Count - 3
# Deletes the subfolders and their contents
$sorted_subfolders[0..($delete_count - 1)] | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
# Write a message to the console when deletion complete
Write-Output "Deleted $($delete_count) subfolders"
# Create a string for email with the folder names
$email_body = "The Backup Management Script Has been Executed Successfully!`n`n" +
"The following folders were deleted from the SQL backup folder:`n" +
($sorted_subfolders[0..($delete_count - 1)].Name -join "`n") + "`n`n" +
"The following folders are left in the SQL backup folder:`n" +
($sorted_subfolders[$delete_count..($subfolders.Count - 1)].Name -join "`n")
}
else {
# Writes email to Admin when Latest 3 Backup folders are left**
$email_body = "No backup Folder Older than 3 Days Have been Found!`n Please Check If the Backup has run as scheduled."
}
# Sends email notification
$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
$SmtpClient.Host = "SMTP server IP"
$mailmessage.from = ("[email protected]")
$mailmessage.To.add("[email protected]")
$mailmessage.Subject = "Backup Cleanup Job"
$mailmessage.Body = $email_body
$smtpclient.Send($mailmessage)
我尝试将执行策略更改为 RemoteSigned,但它仍然没有删除该文件夹。 备份文件夹位于共享文件夹中,因此我将其移出到服务器上的本地文件夹中。该脚本可以检测文件夹并提取文件夹的名称,但似乎无法删除这些文件夹。
答:
所以,上面的帖子是不完整的。我已经在我的 PC 上运行了该脚本,它按应有的方式运行并删除子文件夹,但它在服务器上不起作用 (Windows Server 2016)。按照 Max 的建议,我在脚本中添加了 Write-Warning $error[0]。 错误 说脚本没有经过数字签名。因此,我将执行策略设置为绕过。它不会保存该配置,并说,
“ 警告:Windows PowerShell 已成功更新执行策略,但该设置被在 more sp 中定义的策略覆盖 ecific 范围。由于替代,shell 将保留其当前的有效执行策略 RemoteSigned。键入“Get-Execution Policy -List“查看您的执行策略设置。有关详细信息,请参阅“Get-Help Set-ExecutionPolicy”。"
评论