¿Cómo puedo negar una condición en PowerShell?


¿Cómo puedo negar una prueba condicional en PowerShell?

Por ejemplo, si quiero comprobar el directorio C:\Code, Puedo correr:

if (Test-Path C:\Code){
  write "it exists!"
}

Hay una manera de negar esa condición, por ejemplo (no funciona):

if (Not (Test-Path C:\Code)){
  write "it doesn't exist!"
}

Solución alternativa :

if (Test-Path C:\Code){
}
else {
  write "it doesn't exist"
}

Esto funciona bien, pero preferiría algo en línea.

Author: Peter Mortensen, 2011-11-11

2 answers

Casi lo tienes con Not. Debe ser:

if (-Not (Test-Path C:\Code)) {
    write "it doesn't exist!"
} 

También puede utilizar !: if (!(Test-Path C:\Code)){}

Solo por diversión, también puedes usar bitwise exclusive or, aunque no es el método más legible/comprensible.

if ((test-path C:\code) -bxor 1) {write "it doesn't exist!"}
 379
Author: Rynant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-19 23:56:34

Si eres como yo y no te gusta el doble paréntesis, puedes usar una función

function not ($cm, $pm) {
  if (& $cm $pm) {0} else {1}
}

if (not Test-Path C:\Code) {'it does not exist!'}

Ejemplo

 7
Author: Steven Penny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-18 16:46:05