2012-01-10 133 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

相關問題