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

Powershell 如何检查文件是否存在于特定位置?,powershell,if-statement,Powershell,If Statement,我只想帮助我写我的如果声明,我很难在网上找到信息来做我想做的事情。基本上,我需要if语句来查看$file是否位于指定位置(如果可能,可以是多个位置)。到目前为止,我有: foreach ($file in $MyInvocation.MyCommand.Path) { if ($file) { #I need this to search a specific directory or directories } } 如果要查看是否存在某些内容,请尝试使用测试路径命令。这将返回一个真

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

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

如果要查看是否存在某些内容,请尝试使用
测试路径
命令。这将返回一个真/假值,您可以将该值插入后续的
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
}

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

if( ( (test-path 'c:\testpath1\test.txt','c:\testpath2\test.txt') -eq $true).Count)
{
"File found!";
}
如果您想知道文件的位置,请分别为每个路径执行测试路径

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

你发布的问题和代码没有意义
$MyInvocation.MyCommand.Path
是脚本的完整路径,它显然是存在的,否则代码就不会首先运行。它也不是一个集合,这使得
foreach
循环毫无意义。如果要确保它是一个文件而不是目录,请添加:
-PathType-Leaf