批处理之家's Archiver

victorwoo 发表于 2014-8-17 20:38

PowerShell 技能连载 - 获取指定扩展名的文件

原始链接:[url=http://blog.vichamp.com/powershell/tip/2014/08/15/getting-files-with-specific-extensions-only/]PowerShell 技能连载 - 获取指定扩展名的文件[/url]
发表日期:2014-08-15
[hr]
[i]适用于 PowerShell 所有版本[/i]

当您使用 `Get-ChildItem` 来获取一个文件列表时,您可能会注意到 `-Filter` 参数有时候会导致返回比你预期的更多的文件。

以下是一个例子。这段代码并不只是返回“.ps1”扩展名的文件,而也会返回“.ps1xml”扩展名的文件:[code]
Get-ChildItem -Path C:\windows -Recurse -ErrorAction SilentlyContinue -Filter *.ps1
[/code]要限制只返回您需要的扩展名的文件,请用一个 cmdlet 来过滤结果:[code]
Get-ChildItem -Path C:\windows -Recurse -ErrorAction SilentlyContinue -Filter [i].ps1 [/i]
  Where-Object { $_.Extension -eq '.ps1' }
[/code]这将只返回您指定的扩展名的文件。


本文国际来源:[url=http://powershell.com/cs/blogs/tips/archive/2014/08/15/getting-files-with-specific-extensions-only.aspx]Getting Files with Specific Extensions Only[/url]

Linuxer 发表于 2014-8-20 10:13

[code] Where-Object { $_.Extension -eq '.ps1' }[/code]这里边的$_.Extension是什么意思呢?
版主,自动执行的又把斜体代码带出来了,[code][i].ps1 [/i][/code]感觉这个比bat里的%~nxI要容易理解一些。。

Linuxer 发表于 2014-8-20 10:39

[b]回复 [url=http://www.bathome.net/redirect.php?goto=findpost&pid=152534&ptid=31482]1#[/url] [i]victorwoo[/i] [/b]


    懂了,原来就是代表扩展名的意思,,where就像数据库里的select一样,,,where-object从管道里查询指定内容。。

523066680 发表于 2014-8-20 11:04

[b]回复 [url=http://bbs.bathome.net/redirect.php?goto=findpost&pid=152722&ptid=31482]2#[/url] [i]Linuxer[/i] [/b]


    好用是好用,就是整条语句加起来长了点。要是$_.Ext就简短咯

CrLf 发表于 2014-8-20 18:30

个人认为与其用 where 不如用 -include '*.txt',无论可读性还是执行效率都是更优选择[code]Get-ChildItem -Path C:\windows -Recurse -ErrorAction SilentlyContinue -Include '*.ps1'[/code]

页: [1]

Powered by Discuz! Archiver 7.2  © 2001-2009 Comsenz Inc.