Я столкнулся со странной проблемой с powershell
Нет, вы пришли, чтобы узнать истинную природу PowerShell.
В PowerShell любой вывод излюбое выражение значения «всплывает» перед вызывающей стороной, включая вывод из вызова mkdir
:
PS C:\> $myNewPath = TestStuff "testVar"
PS C:\> $myNewPath.Count
2
PS C:\> $myNewPath[0].GetType() # the output from `mkdir` is a DirectoryInfo object
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DirectoryInfo System.IO.FileSystemInfo
PS C:\> $myNewPath[1].GetType() # this is the string you `return`d:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
Чтобы исправить вашу функцию, либо подавите вывод из mkdir
с помощью Out-Null
или присваивая его $null
:
mkdir $newPath |Out-Null
# or
$null = mkdir $newPath
# or
[void]( mkdir $newPath )
... или просто передавая результаты непосредственно из mkdir
:
function Test-Stuff {
param($test)
Write-Host "Called with parameter: $test"
$newPath = Join-Path "C:\testy" $test
# No output suppression, output value will be returned to the caller
mkdir $newPath
# Let's ensure that the last call actually succeeded
if($?){
Write-Host "New path is: $newPath"
}
}