【问题标题】:powershell check for existence of multiple inputspowershell 检查是否存在多个输入
【发布时间】:2020-12-14 01:32:36
【问题描述】:

我需要检查输入的文件是否存在。

  1. 我拆分多个输入,例如 BWMDL.VML BWMDL.STA 等,并写出文件夹中已有的文件
  2. 我检查来自输入的文件是否存在于文件夹中。

但我得到了 True,即使文件不存在,test-path 的输出也会打印两次,结果不同。

Set-Variable -Name Files -Value (Read-Host "instert file name") 
Set-Variable -Name FromPath -Value ("C:\Users\Desktop\AP\AP\parser\*.VML" , "C:\Users\Desktop\AP\AP\parser\*.STA")
Set-Variable -Name NameOfFiles (Get-ChildItem -Path $FromPath "-Include *.VML, *.STA" -Name)

Write-Host "FILES IN FOLDER:"
$NameOfFiles

Write-host "---------------------"
Write-host "FILES FROM INPUT: "
Splitted
Write-host "---------------------"

Write-host "FILE EXISTS: "
ForEach ($i in Splitted) {
    FileToCheck
}

function Splitted {
    $Files -Split " "
}

function FileToCheck {
    Test-Path $FromPath -Filter $Files -PathType Leaf
}

例如我是这样的result

【问题讨论】:

    标签: powershell input file-exists


    【解决方案1】:

    你把事情复杂化了。
    一旦你得到一个数组中所有扩展名为 .VML 或 .STA 的文件的名称,你就不必再使用Test-Path,因为你知道数组$NameOfFiles中的文件确实存在,否则Get-ChildItem不会已经列出来了。

    这意味着您可以摆脱您定义的帮助函数,顺便说一句,这些函数应该已经写在您的代码之上,所以调用它们之前。

    试试

    $Files    = (Read-Host "instert file name(s) separated by space characters" ) -split '\s+'
    $FromPath = 'C:\Users\Desktop\AP\AP\parser'
    
    # if you need to recurse through possible subfolders
    $NameOfFiles = (Get-ChildItem -Path $FromPath -Include '*.VML', '*.STA' -File -Recurse).Name
    
    # without recursion (so if files are directly in the FromPath):
    # $NameOfFiles = (Get-ChildItem -Path $FromPath -File | Where-Object {$_.Extension -match '\.(VML|STA)'}).Name
    
    Write-Host "FILES IN FOLDER:"
    $NameOfFiles
    
    Write-host "---------------------"
    Write-host "FILES FROM INPUT: "
    $Files
    Write-host "---------------------"
    
    Write-host "FILE EXISTS: "
    foreach ($file in $Files) { ($NameOfFiles -contains $file) }
    

    输出应该是这样的

    instert file name(s) separated by space characters: BWMDL.VML BWMDL.STA
    FILES IN FOLDER:
    BWMDL.STA
    BWMDL.VML
    ---------------------
    FILES FROM INPUT: 
    BWMDL.VML
    BWMDL.STA
    ---------------------
    FILE EXISTS: 
    True
    True
    

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 2016-10-30
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多