简体   繁体   English

powershell 检查是否存在多个输入

[英]powershell check for existence of multiple inputs

I need to check if files from input exists.我需要检查输入中的文件是否存在。

  1. I split multiple inputs for example BWMDL.VML BWMDL.STA etc and write out files that are already in folder我拆分多个输入,例如 BWMDL.VML BWMDL.STA 等并写出文件夹中已有的文件
  2. I check if files from input are present in folder or not.我检查来自输入的文件是否存在于文件夹中。

But I'm getting True, even if the file doesnt exists, also the output from test-path is printed twice, with different result.但是我得到了 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
}

For example I'm getting like this result例如我得到这样的结果

You are over complicating this.你把这复杂化了。
Once you get the names of all files with extension .VML or .STA in an array, you do not have to use Test-Path anymore, since you know the files in array $NameOfFiles actually do exist, otherwise Get-ChildItem would not have listed them.一旦您获得数组中所有扩展名为 .VML 或 .STA 的文件的名称,您就不必再使用Test-Path ,因为您知道数组$NameOfFiles的文件确实存在,否则Get-ChildItem不会有列出他们。

This means you can get rid of the helper functions you have defined, which BTW should have been written on top of your code, so before calling on them.这意味着你可以摆脱你定义的辅助函数,顺便说一句,这些函数应该写在你的代码之上,所以调用它们之前

Try尝试

$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) }

Output should look like输出应该看起来像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM