Powershell脚本不删除子项


2

我在运行PowerShell脚本时遇到错误。这是陈述

Microsoft.Powershell.Core \ FileSystem :: \ [目录路径]中的项目具有子项,并且未指定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
}

1
没有测试自己验证,我想知道你是否能看到你是否错过了一个结束的大括号?看着 ss64.com/ps/foreach-object.html
Pimp Juice IT

道歉。脚本中有一个。我最初没有在我的帖子中粘贴它。
Michael Munyon

Remove-item有-recurse和-force。你试过吗? msdn.microsoft.com/en-us/powershell/reference/3.0/...
Tim Haintz

谢谢蒂姆。我加了 -recurse -force 到了 Remove-Item 但运行后,我仍然收到确认提示,询问是否要删除子项。
Michael Munyon

你有没有尝试过 -Confirm:$false 代替?
FastEthernet

Answers:


3

问题出在这里:

$_ | Remove-Item

虽然你已经指定了 -Recurse-ForceGet-ChildItem,这不会影响后者 Remove-Item 调用。上 Get-ChildItem-Force 只包括隐藏和系统项目。

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

$_ | Remove-Item -Recurse -Force

鉴于它显然仍然要求你确认,似乎你有一个 $ConfirmPreference 除了高。要解决这个问题,您可以添加 -Confirm:$false 到删除行说“绝对不要求确认”,或者你可以在你的cmdlet中进一步添加这一行:

$ConfirmPreference = 'High'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.