Board logo

标题: [转载代码] [PowerShell每日技巧]根据文件夹前缀进行分组(20131206) [打印本页]

作者: DAIC    时间: 2013-12-9 10:27     标题: [PowerShell每日技巧]根据文件夹前缀进行分组(20131206)

Did you know that Group-Object can easily group elements by custom criteria? Here's a line that groups folders by their first three letters:
  1. Get-ChildItem -Path C:\Windows -Directory |
  2.    Group-Object -Property { $_.Name.PadRight(3).Substring(0,3)}
复制代码
And with little additional effort, you can create a hash table that uses these three letters as a key:
  1. $lookup = Get-ChildItem -Path $env:windir -Directory  |
  2.    Group-Object -Property { $_.Name.PadRight(3).Substring(0,3).ToUpper()} -AsHashTable -AsString
  3. $lookup.Keys
复制代码
So now it is really trivial to get all folders that, let's say, start with "SYS":

PS>powershell -f test.ps1


    Directory: C:\Windows


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        11/27/2013   8:36 AM            System32
d----        11/27/2013   8:36 AM            SysWOW64


And why is that useful? Some companies use folder prefixes for business units. With this technique, it's easy to bundle all business unit folders together - you could then sum up their total storage space in a second step and create automatic reporting.

http://powershell.com/cs/blogs/tips/archive/2013/12/06/getting-folders-by-prefix.aspx




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2