[英]How can we separate folders using powershell script with reference of filename
I am newbie to powershell scripting and I did go through lot of articles here and not able to get much help.Can someone help me out on how to put files in specific folders:我是 powershell 脚本的新手,我通过这里的很多文章做了 go 并且无法获得太多帮助。有人可以帮助我了解如何将文件放入特定文件夹:
file name example:文件名示例:
2008_11_chan_3748_NB001052_031_SIGNED.pdf
put it in folders:把它放在文件夹中:
2008/11/NB001052-031/....
if it ends with "draft", eg如果它以“草稿”结尾,例如
2008_11_chan_3748_NB001052_031_Draft.pdf
put it in a separate draft folder as below把它放在一个单独的草稿文件夹中,如下所示
2008/11/NB001052-031/Draft
Any help is really appreciated.非常感谢任何帮助。 Thanks in advance.提前致谢。
Push-Location c:\2009
Get-ChildItem -File -Filter *_*_*_*_*_*.pdf |
Move-Item -Destination {
$tokens = $_.Name -split '_'
$subdirNames = $tokens[0,1,4]
if ($tokens[-1] -like 'Draft.*') { $subdirNames += 'Draft' }
(New-Item -Force -Type Directory ($subdirNames -join '\')).FullName
} -WhatIf
Pop-Location
Note: The -WhatIf
common parameter in the command above previews the move operation, but the target subfolders are created right away in this case.注意:上面命令中的-WhatIf
常用参数预览移动操作,但在这种情况下会立即创建目标子文件夹。 Remove -WhatIf
once you're sure the operation will do what you want.一旦您确定该操作将执行您想要的操作,请删除-WhatIf
。
(Partial) explanation: (部分)解释:
The Get-ChildItem
call gets those files in the current directory whose name matches wildcard pattern *_*_*_*_*_*.pdf
. Get-ChildItem
调用获取当前目录中名称与通配符模式匹配的那些文件*_*_*_*_*_*.pdf
。
Move-Item -Destination
uses a delay-bind script block ( {... }
) to dynamically determine the target path based on the current input object, $_
, which is of type System.IO.FileInfo
Move-Item -Destination
使用延迟绑定脚本块( {... }
) 根据当前输入 object, $_
动态确定目标路径,其类型为System.IO.FileInfo
The code inside the script block uses the -split
operator to split the file name into tokens by _
, extracts the tokens of interest and appends Draft
as appropriate, then creates / returns a subdirectory path based on the \
-joined tokens joined in order to output the target directory path;脚本块内的代码使用-split
运算符将文件名通过_
拆分为标记,提取感兴趣的标记并酌情附加Draft
,然后根据加入的\
-joined 标记创建/返回子目录路径,以便output 目标目录路径; note that -Force
creates the directory on demand and quietly returns an existing directory.请注意, -Force
按需创建目录并悄悄地返回现有目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.