none
Split command failing

    Question

  • Hello everyone,

    Apologies if this has been asked elsewhere, my searches haven't found anything!

    Basically, I am declaring a directory as a variable.  Then I am listing the contents of that variable with the 'split-path' cmdlet with the -leaf switch to return just the filenames.

    Now, the filenames in question contain a file code, a report date and todays date - for example 12345-19022010-26022010.snp 

    I need to split this filename by the "-" so I can put the 3 elements into an array (12345, 19022010 and 26022010.snp). 

    My command is as follows (I'm using echo to see what is happening):

    $listfiles = dir $dir | split-path -leaf
    echo $listfiles
    $filesplit = $listfiles.split("-")
    echo $filesplit

    but all I get back is:

    Method invocation failed because [System.Object[]] doesn't contain a method named 'split'.
    At h:\script.ps1:31 char:30
    + $filesplit = $listfiles.split <<<< ("-")
        + CategoryInfo          : InvalidOperation: (split:String) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound

    I have tried doing $listfiles.tostring().split("-") but that only returns System.Object[]

    I have used a very similar method on another script that seems to work OK but the syntax of that command doesn't work in this scenario.

    Can anyone see where I'm going wrong?

    Thanks
    Friday, February 26, 2010 11:36 AM

Answers

  • **Not fully tested**, but you'll need to do something like this:

    $splits=@()
    $listfiles = dir $dir | split-path -leaf
    echo $listfiles
    foreach($file in $listfiles){
      $filesplit = $file.split("-")
      $splits+=$filelesplit
    }
    $splits

    Friday, February 26, 2010 12:33 PM

All replies

  • **Not fully tested**, but you'll need to do something like this:

    $splits=@()
    $listfiles = dir $dir | split-path -leaf
    echo $listfiles
    foreach($file in $listfiles){
      $filesplit = $file.split("-")
      $splits+=$filelesplit
    }
    $splits

    Friday, February 26, 2010 12:33 PM
  • **Not fully tested** - but it works a treat!

    Thanks very much for the quick reply.
    Friday, February 26, 2010 12:38 PM
  • I'm not sure I follow you, but a following might give you what you want:

    PS C:\> $filesplit = dir $dir | ? {!$_.psIscontainer} | select @{n="name";e={$_.name -split "-"}}
    PS C:\> $filesplit[0].name
    12345
    19022010
    26022010.snp
    PS C:\> $filesplit[1].name
    67890
    19022010
    26022010.snp

    $filesplit is an array where every member is an array of 3 elements which once were parts of file names.

    Aleksandar Nikolić http://powershellers.blogspot.com http://twitter.com/alexandair
    Friday, February 26, 2010 12:54 PM