powershell 检查是否存在多个输入

powershell check for existence of multiple inputs

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

  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

你把这个复杂化了。
一旦你得到数组中所有扩展名为 .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