删除旧文件和文件夹时发生Powershell错误

我正在尝试删除存档文件夹中的一些旧文件,并且我的脚本可以正常工作,直到到达最后一个删除空文件夹的部分为止(最初使用-whatif进行测试)。我收到以下错误:

Remove-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\ArchiveDelete.ps1:13 char:39
+   $dirs | Foreach-Object { Remove-Item <<<<  $_.fullname -whatif }
    + CategoryInfo          : InvalidData: (:) [Remove-Item],ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,microsoft.PowerShell.Commands.RemoveItemCommand

试图在此处找到合适的答案,但找不到解决方案(我知道我可能正在使用旧版本的Powershell)

#Days older than
$HowOld = -900

#Path to the root folder
$Path = "C:\SharedWorkspace\ArchiveDSAgile"

#Deletion files task
get-childitem $Path -recurse | where {$_.lastwritetime -lt (get-date).adddays($HowOld) -and -not $_.psiscontainer} |% {remove-item $_.fullname -force -whatif}

#Deletion empty folders task
do {
  $dirs = gci $Path -recurse | Where { (gci $_.fullName -Force).count -eq 0 -and $_.PSIsContainer } | select -expandproperty FullName
  $dirs | Foreach-Object { Remove-Item $_ -whatif }
} while ($dirs.count -gt 0)
jiayoushixin 回答:删除旧文件和文件夹时发生Powershell错误

您的循环都不是必需的。

您可以将Where-Object的输出直接输入Remove-Item

$AgeCap = (Get-Date).AddDays(-900)
$Path = "C:\SharedWorkspace\ArchiveDSAgile"

Get-ChildItem $Path -Recurse -File | Where-Object LastWriteTime -lt $AgeCap | Remove-Item -WhatIf

PowerShell 3.0(我相信)和更高版本中提供了-File的{​​{1}}参数。如您在示例代码中所做的那样,PowerShell 2.0的解决方法将对照Get-ChildItem中的$_.PSIsContainer进行检查。

,

最终使其正常工作:

#Days older than
$HowOld = -900

#Path to the root folder
$Path = "C:\SharedWorkspace\ArchiveDSAgile"

#Deletion files task
get-childitem $Path -recurse | where {$_.lastwritetime -lt (get-date).adddays($HowOld) -and -not $_.psiscontainer} |% {remove-item $_.fullname -force -whatif}

#Deletion empty folders task
Get-ChildItem $Path -Recurse | Where-Object {$_.lastwritetime -lt (get-date).adddays($HowOld) -and -not !$_.psiscontainer} | Remove-Item -recurse -WhatIf

感谢您的帮助

本文链接:https://www.f2er.com/3117795.html

大家都在问