【问题标题】:Passing down a variable to function creates an array将变量传递给函数会创建一个数组
【发布时间】:2019-08-14 17:01:57
【问题描述】:

我已经asked 了解 Powershell 在 Powershell 中的返回值,但我无法理解为什么以下 New-FolderFromName 返回一个数组 - 我期望一个值(路径或字符串)作为回报:

$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
)

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这是因为 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 了解有关行为。

    【讨论】:

      猜你喜欢
      • 2013-09-02
      • 2020-07-28
      • 2014-04-02
      • 1970-01-01
      • 2017-09-12
      • 2015-07-02
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多