5

I've got a project analyzing logfiles. Someone, in their infinite wisdom, is naming the logfiles MM-DD-YYYY-HH-MM.LOG (e.g., 10-31-2012-18-00.LOG for 6:00pm on October 31, 2012).

My first order of business is to create something significantly more reasonable to work with by making copies of the existing logs named YYYYMMDD_HHMM.LOG (e.g., 20121031_1800.LOG for the above example), and must use powershell to accomplish this task.

So here's where I am so far:

$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"
}

and I keep getting an error

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

I know I'm missing something pretty stupid here...I just can't see it. Any other sets of eyes out there that can help me out?

3

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
}

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.