I gave @C.B. credit for the answer, but there's another way to solve the problem, by forcing the output of Get-ChildItem to an array using the @( ... )
syntax.
$folders1 = @(Get-ChildItem $parentFolderName |
? { $_.PSIsContainer -and $_.Name -ne "Data" } |
sort CreationTime -desc |
select -Skip $numberOfFoldersToKeep)
foreach ($objItem in $folders1) {
Write-Host $webServerLocation\$objItem
Remove-Item -Recurse -Force $parentFolderName\$objItem -WhatIf
}
This returns an array of length zero, so the body of the foreach statement is not executed.
As C.B. noted in the comments above, the problem is that if you pass a null
collection into a foreach statement in PowerShell, the body of the foreach statement is executed once.
This was completely unintuitive to me, coming from a .NET background. Apparently, it's unintuitive to lots of other folks as well, since there's bug reports filed for this behavior on MSDN: https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=281908&SiteID=99
Apparently, this bug has been fixed in PowerShell V3.