Powershell Gotchas: Get-ChildItem on an directory people/programs are actually using.
We've all gone to a directory and gotten a list of the items there... dir, windows explorer, ls (for the linux folks out there) and so on. Pretty normal thing to do really....
Even in code, in most languages, it's a very simple process in which you use your preferred languages syntax to get back a list of the files or other directories it finds at a given path. Most of these allow for some sort of search pattern or filter to restrict it in various ways, and recursion options to look inside of other directories found there. Universally these sort of just "work". Programmers all over know that these are very basic IO operations that all sort of function the exact same way and as such don't even really think heavily about the process of doing so or what's happening behind the scenes when they do.
Until Windows PowerShell. What was going through their minds when they developed this function!?
Here's the issue...
When any progromatic call gets back a collections of objects (file objects or directory objects) from one of these calls, it first gets a list and then makes an object for each item on the list (in most cases, I'm sure exceptions to this exist). PowerShell is no different. PowerShell however IS different in what it does when, in that brief (or longer across a network share) moment between where it gets a list of 2000 items and then tries to create the object for any given item (say, item 1999 out of the 2000), one of those items goes away. Deleted in some way. PowerShell suddenly thinks it should be there, but can't find it!!!! Panic!!! Emergency!!!!
Most systems have things built in for this... it simply removes that missing item from the list of what was expected, and goes on with life. Returning a now smaller list of items. After all, the returned values represent what was there, and obviously this thing is now now there. But not PowerShell... it errors. It loses it's ever loving mind and errors.
Of course there's a solution to this... a very simple, hidden, unreasonable that it's not default, you're going to have to spend 4 hours chasing this bug before you find it.... solution.
-ErrorAction SilentlyContinue
Just toss that on the end of the Get-ChildItem call, and all is well. Unless of course there is some real error that you DO want to know about... a risk that you'll have to take, because there is no in-between unfortunately.
Hopefully this rant saves you, at some point in the future where this somewhat rare instance surfaces in your code, from losing as much hair and sleep as it caused me... and hopefully one day the developers who implemented this is such a bonehead way make an update that sets this as the default value in this one, sort of common or expected, instance while allowing you to detect other files system errors (such as access denied/etc).
Happy Coding!