New-Item changes function return value

偶尔善良 提交于 2019-12-01 11:03:45

New-Item returns the created object, and PowerShell functions return all non-captured output, not just the argument of the return keyword.

In Windows PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the Return keyword.

This means that if the path already exists your function returns just the path string. Otherwise it returns an array with the new DirectoryInfo object and the path string.

Depending on whether you want a string or a DirectoryInfo object returned you can either suppress the output of New-Item:

if (!(Test-Path $path)) {
  New-Item -Path $parentFolder -Name $name -ItemType Directory | Out-Null
}

return $path

or remove the return statement and instead add an else branch where you call Get-Item on the path:

if (!(Test-Path $path)) {
  New-Item -Path $parentFolder -Name $name -ItemType Directory
} else {
  Get-Item $path
}

On a more general note, I'd recommend some modifications to your code:

  • Use the -LiteralPath parameter with Test-Path, so you don't run into problems when the path contains special characters like square brackets.
  • Use Join-Path for constructing a path, as that will automatically take care of path separators.
  • Use advanced parameter definitions, which will allow you to make parameters mandatory, define parameter order, validate input, and lots of other things.
  • Use the PowerShell naming convention with approved verbs for your function names.

Example:

function New-Folder {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$true)]
    [string]$Name,
    [Parameter(Mandatory=$true)]
    [string]$ParentFolder
  )

  $path = Join-Path $ParentFolder $Name

  if (-not (Test-Path -LiteralPath $path)) {
    New-Item -Path $ParentFolder -Name $Name -ItemType Directory
  } else {
    Get-Item -LiteralPath $path
  }
}
J.Russell

In this case I decided to set the variable "junk" to the return value of New-Item:

# CRAZY HACK: Need to set the return to something or else this
#             function will return the New-Item object too.
if(!(Test-Path $path))
{
     $junk = New-Item -path $parentFolder -name $name -itemtype Directory
}
J.Russell

Even better solution: Pipe the output to Out-Null:

if (!(Test-Path $path))
{
    New-Item -path $parentFolder -name $name -itemtype Directory | Out-Null
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!