Script does not exit but loops

I am new to PS and trying to run a script within a windows 11 batch file running as administrator. Purpose is to remove all oldest Created.Date files in the current folder and return to CMD. Manually running the script commands in PS works but when running from the batch it does not exit but loops. Please tell what is wrong.

= Batch Code:

SET _SRC=F:\3-Tue\

CD /D %_SRC%

POWERSHELL.EXE -NoProfile -ExecutionPolicy Bypass -File “C:\Users\eric\Dropbox\Batch_Files\MyScript.ps1”

= MyScript.ps1:

$oldestDate = Get-ChildItem . -File | Sort-Object CreationTime | Select-Object -First 1 | ForEach-Object {$.CreationTime.Date}
$filesToDelete = Get-ChildItem -File | Where-Object {$
.CreationTime.Date -eq $oldestDate}
$filesToDelete | Select-Object Name, CreationTime
$filesToDelete | Remove-Item -WhatIf
EXIT

Eric,
Welcome to the forum. :wink:

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

Guide to Posting Code - Redux <---- Click :point_up_2:t4: :wink:

( !! Sometimes the preformatted text button hides behind the settings gear symbol. :wink: )

I’d streamline your PowerShell code a little to avoid reading the directory twice but there’s actually nothing in your PowerShell code indicating that it should loop for some reason.

$CompleteFileList = 
    Get-ChildItem . -File 
$oldestDate =
    ($CompleteFileList |
        Sort-Object -Property CreationTime |
            Select-Object -First 1).CreationTime.Date
$CompleteFileList |
    Where-Object {
            $_.CreationTime.Date -eq $oldestDate
        } | 
            Remove-Item -WhatIf              

It might help when you elaborate a little more how you run your code and especially why you’re running the PowerShell code from inside a batch file. That’s in the vast majority of the cases I know of unnessecary and error prone.

Thanks for the reply. Running inside a batch because I run a daily batch that is hundreds of lines of code which is too much to convert all to PS and this function will be run on a different folder every day.

I replaced my script with yours and it also errors on depth. I think it is either looping or operating on a larger folder or perhaps the entire disk. As a test using your script I changed “-WhatIf” to “-Force” with the same result BUT my script deleted all files in the folder. Therefore my script is looping and does not exit after it runs each command once.

Since the parameter -WhatIf creates an output to the console you should see if the script is looping. And if you don’t see the console you may add logging to your script to be able to troubleshoot it properly. :backhand_index_pointing_up:

If the reason for the loop is not in the PowerShell code it may be in your batch file. :man_shrugging:

What exactly does that mean “errors on depth”?

Since PowerShell is way more advanced than CMD your batch may be way shorter in PowerShell than in batch.

This is the error in red text:
The script failed due to call depth overflow.

  • CategoryInfo : InvalidOperation: (0:Int32) , ParentContainsErrorRecordException
  • FullyQualifiedErrorId : CallDepthOverflow

This is the PS error in red text:

The script failed due to call depth overflow.

  • CategoryInfo : InvalidOperation: (0:Int32) , ParentContainsErrorRecordException
  • FullyQualifiedErrorId : CallDepthOverflow

That looks like a partial error message. Could share the complete error message? And could you please format it as code?

Thanks in advance.

That was all the “red” BUT I have solved the problem caused by a simple oversight. The mistake was a missing # in a comment which I did not originally show you. My habit is to place the file title as a first line comment and the first line should have been # MyScript.psi. Tired eyes kept overlooking the error. Thanks for sticking with me on this.

Just offering a slightly different way of doing the same thing as the code @Olaf submitted. It doesn’t have to sort the list of files under consideration:

$allfiles = Get-Childitem . -File
$mindate = ($allfiles | Measure-Object -Property CreationTime -Min).Minimum.Date
$allfiles | Where-Object {
                $_.CreationTime.Date -eq $mindate
            } | Remove-Item -WhatIf
2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.