Pergunta

I am building a script which uses the test-path cmdlet, if the path exist I want to have a different path to be deleted.

This works out well, but even though I would love to understand how the variable $null works.

Here is a snippet :

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

It now removes the content of the folder "$destzip*" if i have the "$sourcezip"

But I before knowing how it works i was searching for something like :

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

without sucess, that's why i am curious how this $null variable works.

Foi útil?

Solução

Sending the result of an opertation to $null simply causes it to be discarded.

All of these are functionally the same:

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

You use this when an expression will produce output to the Output stream that you don't want, to keep if from polluting the pipeline. I'm not sure why it's being used in your example, since Remove-Item doesn't produce any output.

Outras dicas

$null have nothing to do with the if statement:

this fail:

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

but this not:

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

Close, the operator goes inside the thingy's

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

if (  $a -eq $True  )

{
 $null = remove-item "$destzip\*" -recurse -force
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top