我正在学习PowerShell,我所做的任务之一就是过滤一个Csv文件记录。
基于这个链接:https://4sysops.com/archives/create-sort-and-filter-csv-files-in-powershell/,我尝试了类似于:Import-Csv -Path '.\sample.csv' | Select-Object EmailAddress,UniqueName,LastLoginDate | ? EmailAddress -like *gmail.com -Or ? EmailAddress -like *outlook.com | Export-Csv -Path $fileOut -NoTypeInformation
的东西
但是上面的内容给了我标题中提到的错误。基于这个链接:https://www.computerperformance.co.uk/powershell/match/,我在Select行之后使用Where来解决错误,如下所示:Where-Object {$_.EmailAddress -Like "*gmail.com" -Or $_.EmailAddress -Like "*outlook.com"}
为什么第一个示例给出了错误,而没有给出第二个示例?
发布于 2022-07-25 08:15:20
tl;博士
Where-Object
cmdlet;?
只是它的内置别名。-like
操作,所以必须使用脚本块语法简化语法,将您限制为单个操作。规则, 脚本阻止-based语法
示例:
# You're free to add additional expressions inside { ... }
Where-Object { $_.EmailAddress -like '*gmail.com' }
使用单个参数,即https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Script_Blocks ({ ... }
),在该参数中,要测试的条件是基于表示当前输入对象的变量而制定的。
这个语法:
简化的, 语法:
示例:
# Equivalent of the above.
# Note the absence of { ... }, $_, and "..."
Where-Object EmailAddress -like *gmail.com
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Simplified_Syntax是一种可与Where-Object
和ForEach-Object
一起使用的替代语法,ForEach-Object
:
ForEach-Object
调用方法,则仅限于输入对象本身。使用简化的语法,构成条件/方法调用的部分作为单独的参数传递,因此绑定到专为使用此语法而设计的不同参数:
{ ... }
附件(没有使用脚本块)。$_
,因为它的使用是隐含的;例如,在脚本块语法中,EmailAddress
相当于$_.EmailAddress
。- A notable limitation as of PowerShell 7.2.x is that with `Where-Object` you cannot operate on the input object _itself_ - you _must_ specify a property. [GitHub issue #8357](https://github.com/PowerShell/PowerShell/issues/8357) discusses overcoming this limitation in the future, but there hasn't been any activity in a long time.
"..."
或'...'
的*.gmail.com
使用简化的语法,而等效脚本块内的表达式模式解析需要引用,例如'*gmail.com'
。https://stackoverflow.com/questions/73110762
复制