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.
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.
( !! Sometimes the preformatted text button hides behind the settings gear symbol. )
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.
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.
If the reason for the loop is not in the PowerShell code it may be in your batch file.
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.
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: