0

我正在构建一个使用 test-path cmdlet 的脚本,如果该路径存在,我想删除一个不同的路径。

这很有效,但即使我很想了解变量 $null 是如何工作的。

这是一个片段:

if (Test-Path -path "$sourcezip")
{
 $null = remove-item "$destzip\*" -recurse -force
}

如果我有“$sourcezip”,它现在会删除文件夹“$destzip*”的内容

但在知道它是如何工作的之前,我一直在寻找类似的东西:

if (Test-Path -path "$sourcezip") -eq $true

没有成功,这就是为什么我很好奇这个 $null 变量是如何工作的。

4

3 回答 3

2

将操作结果发送到 $null 只会导致它被丢弃。

所有这些在功能上都是相同的:

$null = remove-item "$destzip\*" -recurse -force
remove-item "$destzip\*" -recurse -force > $null
remove-item "$destzip\*" -recurse -force | out-null

当表达式将向输出流产生您不想要的输出时,您可以使用它,以防止污染管道。我不确定为什么在您的示例中使用它,因为 Remove-Item 不会产生任何输出。

于 2014-01-29T11:41:05.323 回答
2

$null与声明无关if

这个失败:

if (Test-Path -path "$sourcezip") -eq $true

但这不是:

if ((Test-Path -path "$sourcezip") -eq $true)
{
  remove-item "$destzip\*" -recurse -force
}
于 2014-01-29T13:31:37.010 回答
1

关闭,操作员进入事物内部

$a = Test-Path -path "$sourcezip"

if (  $a -eq $True  )

{
 $null = remove-item "$destzip\*" -recurse -force
}
于 2014-01-29T11:10:58.383 回答