Powershell根据修剪后的文件名

时间:2015-11-06 13:31:24

标签: powershell file-manipulation

我有一个文件夹,其中文件被删除,我希望从该文件夹中提取文件并根据部分文件名移动到新文件夹。如果缺少新文件夹,则创建它。

我试图将下面的内容放在一起,但它会引发有关已存在路径的错误,并且不会移动文件。

文件名可以是除了文件的最后16个字符之外的任何模式,我删除它们并使用剩余的作为文件夹名称。 我对脚本非常陌生,所以如果我犯了一个愚蠢的错误,那么解释就会受到赞赏。

修改 我玩了不同的操作顺序,在新项目命令中添加了“-Force”,尝试使用“Else”而不是“If(!(”。 我现在正处于自豪地显示新目录然后停止的地步。 我可以将move-item部分添加到每个循环的new中,以便在创建和测试dir之后处理它吗?如果是这样,你如何安排{}部分?

编辑2 我终于让它工作了,下面更新了脚本,movie-item命令在运行文件名中的特殊字符时遇到问题,在我的例子中它是方括号。 -literalpath开关为我修复了这个问题。 谢谢各位的意见。

更新了脚本3.0

#Set source folder
$source = "D:\test\source\"
#Set destination folder (up one level of true destination)
$dest = "D:\test\dest\"
#Define filter Arguments
$filter = "*.txt"
<#
$sourcefile - finds all files that match the filter in the source folder
$trimpath - leaves $file as is, but gets just the file name.
$string - gets file name from $trimpath and converts to a string
$trimmedstring - Takes string from $trimfile and removes the last 16 char off the end of the string
Test for path, if it exists then move on, If not then create directory
Move file to new destination
#>
pushd $source
$sourcefile = Get-ChildItem $source -Filter $filter
foreach ($file in $sourcefile){
$trimpath = $file | split-path -leaf
$string = $trimpath.Substring(0)
$trimmedstring = $string.Substring(0,$string.Length-16)
If(!(Test-Path -path "$dest\$trimmedstring")){New-Item "$dest\$trimmedstring" -Type directory -Force}        
move-Item -literalpath "$file" "$dest\$trimmedstring"
}

2 个答案:

答案 0 :(得分:0)

您可能需要调整正在使用的路径,但以下情况应该有效。

e

答案 1 :(得分:0)

我终于让它工作了,下面更新了脚本,当在文件名中运行特殊字符时,movie-item命令出现问题,在我的例子中它是方括号。 -literalpath开关为我修复了这个问题。感谢每一位人士的意见。

#Set source folder
$source = "D:\test\source\"
#Set destination folder (up one level of true destination)
$dest = "D:\test\dest\"
#Define filter Arguments
$filter = "*.txt"
<#
$sourcefile - finds all files that match the filter in the source folder
$trimpath - leaves $file as is, but gets just the file name.
$string - gets file name from $trimpath and converts to a string
$trimmedstring - Takes string from $trimfile and removes the last 16 char off the end of the string
Test for path, if it exists then move on, If not then create directory
Move file to new destination
#>
pushd $source
$sourcefile = Get-ChildItem $source -Filter $filter
foreach ($file in $sourcefile){
$trimpath = $file | split-path -leaf
$string = $trimpath.Substring(0)
$trimmedstring = $string.Substring(0,$string.Length-16)
If(!(Test-Path -path "$dest\$trimmedstring")){New-Item "$dest\$trimmedstring" -Type directory -Force}        
move-Item -literalpath "$file" "$dest\$trimmedstring"
}