I am getting an error when running a PowerShell script. It is stating
The item at Microsoft.Powershell.Core\FileSystem::\[path to directory] has children and the Recurse parameter was not specified.
In my PowerShell script I do have it specified. Is it in the wrong location?
# 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
}
Best Answer
The problem is here:
While you've specified
-Recurse
and-Force
onGet-ChildItem
, that doesn't affect the laterRemove-Item
invocation. OnGet-ChildItem
,-Force
just includes hidden and system items.Normally, this would suppress the confirmation, and for me it does:
Given that it's apparently still asking you for confirmation, it seems you have a
$ConfirmPreference
other than High. To get around that, you can add-Confirm:$false
to the removal line to say "definitely do not ask for confirmation", or you can add this line further up in your cmdlet: