首页 > 解决方案 > powershell 检查是否存在多个输入

问题描述

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

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

但我得到了 True,即使文件不存在,测试路径的输出也会打印两次,结果不同。

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
}

例如我得到这样的结果

标签: powershellinputfile-exists

解决方案


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

推荐阅读