Powershell Script Not Deleting Child Items

Powershell Script Not Deleting Child Items

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
}
5

1 Answer

The problem is here:

$_ | Remove-Item

While you've specified -Recurse and -Force on Get-ChildItem, that doesn't affect the later Remove-Item invocation. On Get-ChildItem, -Force just includes hidden and system items.

Normally, this would suppress the confirmation, and for me it does:

$_ | Remove-Item -Recurse -Force

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:

$ConfirmPreference = 'High'
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.