2

I have already asked about Powershell return values in Powershell, but I can simply no wrap my head around why the following New-FolderFromName is returning an array - I expected one value(a path or a string) in return:

enter image description here

$ProjectName="TestProject"
function New-FolderFromPath($FolderPath){
    if($FolderPath){
        if (!(Test-Path -Path $FolderPath)) {
            Write-Host "creating a new folder $FolderName..." -ForegroundColor Green
            New-Item -Path $FolderPath -ItemType Directory
        }else{
            Write-Host "Folder $FolderName already exist..." -ForegroundColor Red
        }
    }
}

function New-FolderFromName($FolderName){
    if($FolderName){
        $CurrentFolder=Get-Location
        $NewFolder=Join-Path $CurrentFolder -ChildPath $FolderName
        New-FolderFromPath($NewFolder)
        return $NewFolder
    }
}

$ProjectPath=New-FolderFromName($ProjectName)
Write-Host $ProjectPath

Also tried to add the following to New-FolderFromPath as this function seems to be the problem or altering the parameter:

[OutputType([string])]
param(
    [string]$FolderPath
)
Chris G.
  • 23,930
  • 48
  • 177
  • 302

1 Answers1

4

This happens as a Powershell function will return everything on the pipeline instead of what's just specified with return.

Consider

function New-FolderFromName($FolderName){
    if($FolderName){
        $CurrentFolder=Get-Location
        $NewFolder=Join-Path $CurrentFolder -ChildPath $FolderName
        $ret = New-FolderFromPath($NewFolder)
        write-host "`$ret: $ret"
        return $NewFolder
    }
}

#output
PS C:\temp> New-FolderFromName 'foobar'
creating a new folder foobar...
$ret: C:\temp\foobar
C:\temp\foobar

See, the New-FolderFromPath returned a value which originates from New-Item. The easiest way to get rid of extra return values is to pipe New-Item to null like so,

New-Item -Path $FolderPath -ItemType Directory |out-null

See also another a question about the behaviour.

vonPryz
  • 22,996
  • 7
  • 54
  • 65