[英]How do I filter a string array (or list) in PowerShell using the 'Match' cmdlet?
I am trying to filter CSV files. 我正在尝试过滤CSV文件。 But the following script is giving an error. 但是以下脚本发出错误。 How do I specify that I want to run match on each String object? 如何指定我想在每个String对象上运行匹配?
I tried various combinations, but without result. 我尝试了各种组合,但没有结果。
$FileNames = [System.IO.Directory]::GetFiles("C:\Users\anagre\Desktop")
$FileNames = $FileNames | Where { -match "*.csv"}
Try this: 试试这个:
$FileNames = Get-ChildItem -Path "C:\Users\anagre\Desktop" -Filter *.csv
In your above code you didn't use the $PSItem ($_) in your where
clause, and if you want to use a wildchar you have got to use the -like
operator: 在上面的代码中,你没有在where
子句中使用$ PSItem($ _),如果你想使用wildchar,你必须使用-like
运算符:
$FileNames|where{$_ -like "*.csv"}
or 要么
$FileNames|where{$_ -match ".csv"}
The -match operator is both a comparison operator and an array operator, depending on its input object. -match运算符既是比较运算符又是数组运算符,具体取决于其输入对象。
If it's a scalar, it returns a boolean. 如果它是标量,则返回布尔值。 If it's an array, it returns all the elements of the array that match the pattern 如果它是一个数组,它将返回与该模式匹配的数组的所有元素
@($Filenames) -match '*.csv'
Use the array syntax to ensure that you still get an array if there's only one filename returned by Get-ChildItem
. 如果Get-ChildItem
只返回一个文件名,请使用数组语法确保仍然获得数组。 Otherwise, you'll get back $True
instead of the filename if it matches. 否则,如果匹配,您将返回$True
而不是文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.