简体   繁体   English

如何使用“匹配”cmdlet在PowerShell中过滤字符串数组(或列表)?

[英]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.

相关问题 如何找到 PowerShell cmdlet 的模块? - How do I find the module for a PowerShell cmdlet? 如何导入新的PowerShell cmdlet? - How do I import a new PowerShell cmdlet? 如何在Powershell中的字符串中插入cmdlet - How to insert a cmdlet into a string in powershell 如何使用散列表散列在PowerShell中将逗号分隔的值列表作为参数传递给CmdLet? - How can I pass a comma seperated list of values within PowerShell as a parameter to a CmdLet using splatting with hash tables? 如何在没有Remove-PrinterDriver cmdlet的情况下使用Powershell删除打印机驱动程序 - How do I delete a printer driver using Powershell without the Remove-PrinterDriver cmdlet 如何使用PowerShell将cmdlet的输出与列表进行比较? - How can I use PowerShell to compare the output of a cmdlet with a list? Powershell中如何使用Select-String cmdlet获取文件的路径 - How to get the path of the file using the Select-String cmdlet in Powershell 如何隐藏PowerShell cmdlet(Move-VM)结果? - How do I suppress PowerShell cmdlet (Move-VM) results? 如何确定是否指定了PowerShell Cmdlet参数值? - How do I determine if a PowerShell Cmdlet parameter value was specified? 我如何在 powershell 的 foreach 循环中嵌套另一个 cmdlet - How do i nest another cmdlet in foreach loop in powershell
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM