Как я могу использовать PowerShell для разбора имен файлов и их переименования?

10381
dwwilson66

У меня есть проект, анализирующий лог-файлы. Кто-то, в своей бесконечной мудрости, называет лог-файлы MM-DD-YYYY-HH-MM.LOG (например, 10-31-2012-18-00.LOG на 18:00 31 октября 2012 г.).

Мой первый заказ - создать что-то значительно более разумное для работы, создав копии существующих журналов с именем YYYYMMDD_HHMM.LOG (например, 20121031_1800.LOG для приведенного выше примера), и для выполнения этой задачи необходимо использовать powershell.

Так вот, где я так далеко:

$orgPath = "d:\testOrg\" $newPath = "d:\testNew\" $delim = "-" ;  function copyFile { "$($orgPath) copying Files to $($newPath)"  Get-ChildItem $orgPath | ` foreach {  $nameArray = $_.Split($delim) $newName = Write-Output $nameArray[2]+$nameArray[0]+$nameArray[1]+"_"+$nameArray[3]+$nameArray[4]  $targetFile = $newPath + $_.FullName.SubString($orgPath.Length)  New-Item -ItemType File -Path $targetFile -Force  Copy-Item $_.FullName -destination $targetFile write-host $_.DirectoryName $_.newName  "File Copied" } 

и я продолжаю получать ошибку

+ CategoryInfo : InvalidOperation: (Split:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound 

Я знаю, что здесь упускаю что-то довольно глупое ... Я просто не вижу этого. Какие-нибудь другие виды глаз, которые могут мне помочь?

4

1 ответ на вопрос

3
Ƭᴇcʜιᴇ007

Get-ChildItem returns a list of File System objects, not just file names.

You can use the -Name option to get it to return just file names.

The output type is the type of the objects that the cmdlet emits.

System.Object - The type of object that Get-ChildItem returns is determined by the objects in the provider drive path.

System.String - If you use the Name parameter, Get-ChildItem returns the object names as strings.

Something like this:

$orgPath = "d:\testOrg\" $delim = "-" Get-ChildItem $orgPath -Name | ` foreach { $nameArray = $_.Split($delim) $newName = $nameArray[2]+$nameArray[0]+$nameArray[1]+"_"+$nameArray[3]+$nameArray[4] Write-Output $newName } 

Похожие вопросы