2012-01-10 131 views

回答

2

此代码应工作假设文本文件名格式不改变,如,它总是需要删除的最后9个字符。此代码假设txt文件位于文件夹C:\文件夹中

$filelist = (get-childitem c:\folder | Where-Object {$_.mode -match "a"} | foreach-object {$_.name}) 
foreach ($file in $filelist) 
    { 
     $len = $file.length 
     $newname = $file.substring(0,$len -13) 
     $newname = $newname + '.txt' 
     Rename-Item C:\folder\$file $newname 
     clear-variable newname, len 
    } 
+0

非常感谢你,你能详细解释一下每个人在做什么吗?我很喜欢这个和学习。 – user1140032 2012-01-17 02:07:53

+0

高兴它为你工作:) 我会尽力在他们给我们在有限的空间来解释。 $ filelist是一个容器,我把所有的txt文件名放入,使用get-childitem。 GCI获取您指定的任何文件夹中的文件的文件信息。我用来限制GCI的Where对象只能找到文件,跳过子文件夹($ _。mode -match“a”)。 foreach-object {$ _。name}获取每个文件的名称并将其添加到$ filelist容器中。 然后在foreach通过在$文件列表容器中的每个文件循环。 $ len获取并保存文件字符长度。 – Emo 2012-01-17 15:20:39

+0

$ newname创建并包含文件名称,并将日期修剪掉(您必须-13而不是-9才能考虑'.txt'扩展名字符)。第二个$ newname行重新添加.txt扩展名,使得$ newname容器完整,因为它现在保存着文件名,并且删除了日期并正确形成了日期。 Rename-Item是内建的powershell cmdlet(如get-childitem),您可以在其中重命名项目。它循环遍历$ filename容器中的每个$文件,更改所有名称。 – Emo 2012-01-17 15:27:16

0

这个答案会微妙地改变取决于命名模式的类型,但在你的情况,你可以用这样的脚本实现这一点:

Get-ChildItem | 
    Where-Object { 
     <# 
     Multiple Assignment in PowerShell. 
     $beforeUnderbar will have your name, 
     $AfterUnderBar will have the data, and 
     $extension will have the extension. 
     All from one little -split 
     If you start throwing random other files in there, it will barf. 
     #> 
     $beforeUnderbar, $afterUnderBar, $extension = ($_.Name -split "[_.]") 
     if ($afterUnderBar -and $afterUnderBar.Length -eq 8 -and $afterUnderBar -as [int]) { 
     "$beforeUnderBar.$extension" 
     } 
    } 

该脚本应该给你你想要什么与您的命名惯例相匹配的文件。

+0

您好,感谢您的回复,但是我收到此错误if(condition)后缺少语句块。 在行:13字符:9 + <<<< “$ $ beforeUnderBar扩展”。 + CategoryInfo:ParserError:(:) [],ParentContainsErrorRecordException + FullyQualifiedErrorId:这里MissingStatementBlock是一个示例出一组文件的, EMPLOYEE_SKILL_20110519.TXT,我想从后面修整9个字符。这意味着新文件将为EMPLOYEE_SKILL.TXT – user1140032 2012-01-14 00:18:10

+0

这将是因为我忘了将它们放入。对不起,我正在输入一个特别的解决方案。我在样本中添加了括号。 – 2012-01-14 01:22:33

+0

谢谢,但它没有做任何事情,也没有错误。 – user1140032 2012-01-14 02:32:17

相关问题