如何检查文件是否存在于特定位置



我只是想帮助编写if语句,我很难在网上找到信息来做我想做的事情。基本上,我需要我的if语句来查看$file是否位于指定的位置(如果可能的话,可以是多个位置)。到目前为止,我有这个:

foreach ($file in $MyInvocation.MyCommand.Path) {
  if ($file) {  #I need this to search a specific directory or directories
  }
}

如果您想查看是否存在某种东西,请尝试使用test-path命令。这将返回一个true/false值,您可以将其插入后续的if语句中,并分别执行您想要的操作。

$fileTest = test-path [file path here]
if($fileTest -eq $true){
    #what happens when the file exists
}
else{
    #what happens when the file does not exist
}

您也可以使用.NET方法:

if(![System.IO.File]::Exists($file)){
  # File exists
}

检查PowerShell 中是否存在路径的更好方法

如果您只想知道文件是否存在于其中一个位置,请使用:

if( ( (test-path 'c:testpath1test.txt','c:testpath2test.txt') -eq $true).Count)
{
"File found!";
}

如果您想知道文件的位置,请分别为每个路径执行测试路径。

if( ( (test-path 'c:testpath1test.txt') -eq $true).Count)
{
"File found at testpath1!";
}
if( ( (test-path 'c:testpath2test.txt') -eq $true).Count)
{
"File found at testpath2!";
}

最新更新