Powershell 脚本不删除子项

Mic*_*yon 3 powershell

运行 PowerShell 脚本时出现错误。它在说明

Microsoft.Powershell.Core\FileSystem::\[path to directory] ​​中的项目有子项,并且未指定 Recurse 参数。

在我的 PowerShell 脚本中,我确实指定了它。是不是在错误的位置?

# Add CmdletBinding to support -Verbose and -WhatIf 
[CmdletBinding(SupportsShouldProcess=$True)]
param
(
# Mandatory parameter including a test that the folder exists       
[Parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_ -PathType 'Container'})] 
[string] 
$Path,

# Optional parameter with a default of 60
[int] 
$Age = 60   
)

# Identify the items, and loop around each one
Get-ChildItem -Path $Path -Recurse -Force | where {$_.lastWriteTime -lt (Get-Date).addDays(-$Age)} | ForEach-Object {

# display what is happening 
Write-Verbose "Deleting $_ [$($_.lastWriteTime)]"

# delete the item (whatif will do a dry run)
$_ | Remove-Item
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*n N 5

问题在这里:

$_ | Remove-Item
Run Code Online (Sandbox Code Playgroud)

虽然您已指定-Recurseand -Forceon Get-ChildItem,但这不会影响以后的Remove-Item调用。On Get-ChildItem-Force只包括隐藏和系统项目。

通常,这会抑制确认,对我来说确实如此:

$_ | Remove-Item -Recurse -Force
Run Code Online (Sandbox Code Playgroud)

鉴于它显然仍在要求您确认,看来您$ConfirmPreference除了 High 之外还有一个。为了解决这个问题,您可以-Confirm:$false在删除行中添加“绝对不要求确认”,或者您可以在 cmdlet 中进一步添加此行:

$ConfirmPreference = 'High'
Run Code Online (Sandbox Code Playgroud)