如何比较一个文件夹是否存在,如果不存在,就创建她

How to compare if a folder exists and if it does not exist, create her

我有以下问题,我需要创建一个脚本来比较目录是否存在,如果不存在,则创建它。在 linux shell 中,我使用参数 -F 来检查目录是否存在。如何在 PowerShell 中进行测试?

在Linux shell:

DIR=FOLDER

if [ -f $DIR ]
then
    echo "FOLDER EXIST";
else
    echo "FOLDER NOT EXIST";
    mkdir $DIR
fi

如何在 Windows PowerShell 中进行比较?

$DIRE = "C:\DIRETORIO"

if ( -e $DIRE ) {
    echo "Directory Exists"
} else {
    md DIRETORIO
}

您也可以使用带有 force 参数的 New-Item cmdlet,您甚至不必检查目录是否存在:

New-Item -Path C:\tmp\test\abc -ItemType Directory -Force

根据评论,Test-Path 是您应该用来检查文件或目录是否存在的 PowerShell cmdlet:

$DIRE = "C:\DIRETORIO"

if ( Test-Path $DIRE ) {
    echo "Directory Exists"
} else {
    md DIRETORIO
}

The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element.