【问题标题】:How do I check if a file is present in a particular location?如何检查文件是否存在于特定位置?
【发布时间】:2016-03-25 22:38:15
【问题描述】:

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

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

【问题讨论】:

  • 您发布的问题和代码没有意义。 $MyInvocation.MyCommand.Path 是脚本的完整路径,显然它确实存在,否则代码一开始就不会运行。它也不是一个集合,这使得foreach 循环毫无意义。

标签: powershell if-statement


【解决方案1】:

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

【讨论】:

  • 如果你想确保它是一个文件而不是一个目录添加:-PathType Leaf
【解决方案2】:

您也可以使用 .NET 方法:

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

A better way to check if a path exists or not in PowerShell

【讨论】:

    【解决方案3】:

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

    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!";
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多