Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用mkdir命令时出现Powershell问题_Powershell - Fatal编程技术网

使用mkdir命令时出现Powershell问题

使用mkdir命令时出现Powershell问题,powershell,Powershell,我在powershell中遇到了一个奇怪的问题。使用powershell变量调用mkdir命令时,powershell似乎会附加到变量,尽管这仅在函数调用内部发生 我有以下示例代码 function TestStuff($test) { Write-Host "Called with parameter: $test" $newPath = Join-Path "C:\testy\" $test mkdir $newPath # It's ok here

我在powershell中遇到了一个奇怪的问题。使用powershell变量调用mkdir命令时,powershell似乎会附加到变量,尽管这仅在函数调用内部发生

我有以下示例代码

function TestStuff($test) {
    Write-Host "Called with parameter: $test"
    $newPath = Join-Path "C:\testy\" $test
    mkdir $newPath
    # It's ok here
    Write-Host "New path is: $newPath"
    return $newPath;
}

$myNewPath = TestStuff "testVar"
# It's been doubled up here
Write-Host "Returned from function it is: $myNewPath"
这将产生以下输出

Called with parameter: testVar
New path is: C:\testy\testVar
Returned from function it is: C:\testy\testVar C:\testy\testVar
这个问题隐藏在powershell脚本中,很难发现。有人能解释这种行为吗。最终的解决方案被重新编写,因此它不是一个函数调用。另一种选择是将
mkdir
的输出通过管道传输到null,如下所示:
mkdir$myPath>null
,尽管这会在文件系统上生成一个名为null的文件,但似乎不会影响
$myPath
变量

我在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             


要修复函数,请使用
Out Null
抑制
mkdir
的输出,或将其分配给
$Null

mkdir $newPath |Out-Null
# or
$null = mkdir $newPath
# or 
[void]( mkdir $newPath )
。。。或者直接从
mkdir
传递结果:

功能测试工具{
参数($test)
写入主机“使用参数$test调用”
$newPath=连接路径“C:\testy”$test
#无输出抑制,输出值将返回给调用方
mkdir$newPath
#让我们确保最后一次调用实际成功
如果($?){
写入主机“新路径为:$newPath”
}
}

MKDIR是PS command New Item的别名-大多数这种性质的命令都会生成一个输出whcih(如果您不这样做);我不想你需要压制。您不必指定返回的项目-因此,将“RETURN$newPath”更改为RETURN并单独保留MKDIR命令也可以。@politicalist-或者您可以删除整个
RETURN
行?也就是说,我更喜欢
out null
解决方案,并明确说明返回的内容。是的,实际上,您很少需要返回,我主要会创建一个自定义对象或选择在最简单的情况下要返回的属性