PowerShell: ¿Cómo puedo suprimir el error si el archivo Alreadys existe para el comando "mkdir"?

StackOverflow https://stackoverflow.com/questions/19853340

  •  29-07-2022
  •  | 
  •  

Pregunta

Considerar:

PS Y:\> mkdir  C:/dog


    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         11/7/2013  10:59 PM            dog


PS Y:\> mkdir  C:/dog
New-Item : Item with specified name C:\dog already exists.
At line:38 char:24
+         $scriptCmd = {& <<<<  $wrappedCmd -Type Directory @PSBoundParameters }
    + CategoryInfo          : ResourceExists: (C:\dog:String) [New-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
¿Fue útil?

Solución

Añade el -Force Parámetro al comando.

Otros consejos

Usar:

mkdir C:\dog -ErrorAction SilentlyContinue

Es una mejor práctica no suprimir los mensajes de error (a menos que tenga una razón válida). Compruebe si el directorio existe en lugar de intentar crear uno. Si lo hace, ¿tal vez necesite eliminar su contenido o elegir otro nombre? Al igual que,

if (-not (test-path "c:\foobar") ) {
    write-host "c:\foobar doesn't exist, creating it"
    md 'c:\foobar'|out-null
} else {
    write-host "c:\foobar exists, no need to create it"
}

Solo quería agregar que al suprimir el error generalmente no es la mejor práctica como usted dice, el comando -Force funciona mucho más rápido que verificar si existe antes.

Donde D: es un disco RAM:

Measure-Command {new-item "D:\NewFolder\NewSubFolder" -ItemType Directory -force}

Primera ejecución (creación del objeto de carpeta): 5 ms

Segunda ejecución (después de la carpeta existe): 1 ms

Measure-Command {if (-not (test-path "D:\NewFolder\NewSubFolder") ) {
write-host "Directory doesnt exist, creating it"
md "D:\NewFolder\NewSubFolde"|out-null} else {
write-host "Directory exists, no need to create it"}}

Primera ejecución (creación del objeto de carpeta): 54 ms

Segunda ejecución (después de la carpeta existe): 15 ms

¡Gracias Peter por limpiar mi publicación! ¡Tu eres el hombre!

PowerShell 7 ( || no funcionó):

(test-path foo) ? $null : (mkdir foo)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top