powershell - powershell 检查是否存在多个输入
问题描述
我需要检查输入中的文件是否存在。
- 我拆分多个输入,例如 BWMDL.VML BWMDL.STA 等,并写出已经在文件夹中的文件
- 我检查来自输入的文件是否存在于文件夹中。
但我得到了 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
}
例如我得到这样的结果
解决方案
你把这个复杂化了。
一旦你得到一个数组中所有扩展名为 .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
推荐阅读
- mysql - LEFT OUTER JOIN 检查不存在的关系 id
- asp.net-core-mvc - 如何在 ASP.NET Core MVC 中绑定 Part 视图和局部视图中的所有子模型
- c# - Android(Xamarin):BottomNavigationView 没有出现在正确的位置
- python - 我做了 FFT(快速傅里叶变换),但我无法理解......(python)
- svelte - 苗条的过渡:如何淡入,然后淡出?
- web-services - 有关如何从 Google Cloud Platform 调用外部网络服务的任何信息?
- angularjs - 从 $http 承诺以编程方式关闭模式对话框
- java - 如何使用每个循环Java返回值
- python - Django .exclude() 返回空查询集
- docker - Redmine - 发送邮件的docker版本问题