gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:07:41 26 4
gpt4 key购买 nike

我在Powershell中已经有关于Powershell返回值的asked了,但是我简直无法绕开为什么以下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
)

最佳答案

之所以发生这种情况,是因为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有关行为。

关于powershell - 将变量传递给函数将创建一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com