将变量传递给函数将创建一个数组

时间:2019-08-14 08:46:26

标签: powershell

我已经asked关于Powershell中的Powershell返回值,但是我无法绕过为什么下面的New-FolderFromName返回数组的原因-我期望一个值(路径或字符串) )作为回报:

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

也尝试将以下内容添加到New-FolderFromPath中,因为此函数似乎是问题所在或更改了参数:

[OutputType([string])]
param(
    [string]$FolderPath
)

1 个答案:

答案 0 :(得分:4)

发生这种情况是因为Powershell函数将返回管道上的所有内容,而不是return刚刚指定的内容。

考虑

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

请参见,New-FolderFromPath返回了一个源自New-Item的值。摆脱额外返回值的最简单方法是像这样将New-Item传递给null,

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

另请参阅another a question有关该行为。