Powershell Join-Path showing 2 dirs in result instead of 1 – accidental script/function output

As T-Me correctly inferred before you posted the CreateDatedFolder source, the problem is that the function inadvertently outputs 2 objects, and Join-Path accepts an array of parent paths to each join with the child path.

Specifically, it is the New-Item call that accidentally creates an additional output object, just before your return $datedDir call.

New-Item outputs a [System.IO.DirectoryInfo] instance representing the newly created directory and, due to PowerShell’s implicit output behavior, that instance becomes part of what the function outputs tooany command or expression inside a script / function that returns a value that isn’t captured or redirected becomes part of the output.

To prevent that, suppress the output:

$null = New-Item -ItemType Directory -Path $datedDir -force

Other ways to suppress output are discussed in this answer, which also discusses the design rationale for PowerShell’s implicit output behavior.

Note that you never need return in PowerShell in order to output a result – but you may need it for flow control, to exit a function prematurely:

return $datedDir 

is syntactic sugar for:

$datedDir # Implicitly output the value of $datedDir.
          # While you could also use `Write-Output $datedDir`,
          # that is rarely needed and actually slows things down.
return    # return from the function - flow control only

For more information about PowerShell’s implicit output behavior, see this answer.

Leave a Comment