PoSH Fun

I was browsing r/Powershell (as you do), and noticed a chap complaining about the test at the end of a course, where he was asked to

Create a directory named "newdir" in every empty directory whose name is longer than 8 characters recursively.

His code went like this:

get-childitem -recurse | where{$_.Mode -like "d*"} | foreach-object         {$array+=$_.FullName;}
for($i=0; $i -lt $size; i++)
if($array[$i].Length -gt 8)
cd $array[$i];
mkdir newdir;
cd $currentdir;
echo "Done"    

I've been pushing to go on a decent Powershell course for a while, but I think I'll need to pick another course, as I'm sure I can do something more PS specific. Let's have a go...

Though I did miss one requirement (only create files in empty directories), I began with this:

$targetdir = C:\Users\James\Work\Powershell\
$dirs = @()

gci $targetdir -Recurse -Directory | %{ 
	if(($_.Name).Length -ge 8){$dirs += $_.fullname}
$dirs | %{ mkdir (Join-Path $dir "newdir")}

Of course, changing that last line to a quick check solves the empty folders issue -

foreach ($dir in $dirs) {
	if (!(gci $dir)) {mkdir (Join-Path $dir "newdir")}

I do realise that I'm cheating a bit - apparently he was only using stuff available in Powershell 2.0 (poor chap), so the -Directory argument for GCI was unavailable.

Please also note, @stuidge, that Powershell is capable of more fun things, but I'm lazy (and I'd written this out for a reddit post last night... then not posted it, then rewritten it briefly for this).