简体   繁体   English

在Powershell中删除目录对象及其内容

[英]delete directory object and its content in powershell

I have this script which tries to delete all the folders that are older than 7 days. 我有此脚本试图删除所有早于7天的文件夹。 All folders are located under a specific directory called "BackupPath" 所有文件夹都位于名为“ BackupPath”的特定目录下。

This is the script: 这是脚本:

 $date=Get-Date -UFormat "%d-%m-%y"
 $BackupPathday="C:\"+$env:computername+"GPOBackup\$date"
 $BackupPath="C:\"+$env:computername+"GPOBackup"

 if ((Test-Path $BackupPathday) -eq 0) {
 New-Item -ItemType Directory -Force -Path $BackupPathday
 }
 else {
 Write-Host "Today´s backup already exists"
 }

 $Folders=Get-ChildItem $BackupPath

 foreach ($i in $Folders) {
  $Days=((Get-Date) - $i.CreationTime).Days
  #PSISContainer is true means that $i is a folder, ohterwise is a file
  if ($Days -ge 7 -and $i.PsISContainer -eq $True) {       
   $i.Delete() 
  }
 }

When I run it, I get this error message: 运行它时,出现以下错误消息:

Exception calling "Delete" with "0" argument(s): "The directory is not empty. " At C:\\Users\\x\\Desktop\\power.ps1:18 char:14 + $i.Delete <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException Exception calling "Delete" with "0" argument(s): "The directory is not empty. " At C:\\Users\\x\\Desktop\\power.ps1:18 char:14 + $i.Delete <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException 异常调用参数为“ 0”的“删除”:“目录不为空。”在C:\\ Users \\ x \\ Desktop \\ power.ps1:18 char:14 + $ i.Delete <<<<( )+ CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException异常,使用“ 0”参数调用“ Delete”:“目录不为空。”位于C:\\ Users \\ x \\ Desktop \\ power .ps1:18 char:14 + $ i.Delete <<<<()+ CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException

Is there any way of force deleting these folders and its content? 有什么办法可以强制删除这些文件夹及其内容? I don´t know if there is an existing method to do this as I´m new with PowerShell. 我不知道是否有现有方法可以执行此操作,因为我是PowerShell的新手。

Thanks 谢谢

The -Directory switch gets just the folders then Where-object filters those folders based on the date criteria and finally remove-item removes them.(Remove Whatif to apply the command) -Directory开关仅获取文件夹,然后Where-object根据日期条件过滤这些文件夹,最后remove-item将其删除。(删除Whatif以应用该命令)

Get-ChildItem -Path $BackupPath -Directory | 
   Where-Object { ((get-date) - $_.CreationTime).days -ge 7} | 
         Remove-Item -Recurse -WhatIf

Also When testing for a non-existing directory use 另请在测试不存在的目录时使用

if( -not (Test-path c:\temp) ) {"Do something"}else { "nothing"}

means if the expression evaluates to false then "Do something" else "nothing" 表示如果表达式的计算结果为false,则“执行某些操作”,否则为“无”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM