0

So i have folder with several files:

$files = @(Get-ChildItem "myPath")

I can see via the debugger that $files contains several items and i want to take the first:

$files[0] = "123_this.is.string"

And i want to split in by '_' and take 123

$splitted = $files[0] -split "_"

So here i can see that $splitted is empty.

Any suggestions why this strange behavior ?

3
  • this works fine for me, please provide a minimal verifiable example Commented Dec 15, 2016 at 11:41
  • 4
    I believe, you should use Name property value to split. Your $file[0] should contain an object with a bunch of properties, and you can't split objects. Try $files[0].Name -Split '_'. Commented Dec 15, 2016 at 11:53
  • $files[0] -split "_" and $files[0].Name -split "_" should give the same result. Commented Dec 15, 2016 at 21:21

2 Answers 2

6

$files[0] isn't a string but a FileSystemInfo Object.

$files[0].getType()

IsPublic IsSerial Name                                     BaseType                                                                                                                           
-------- -------- ----                                     --------                                                                                                                           
True     True     FileInfo                                 System.IO.FileSystemInfo

So to get it work you have to use the split function to the filename of the file which is a string.

$files[0].name.getType()

IsPublic IsSerial Name                                     BaseType                                                                                                                           
-------- -------- ----                                     --------                                                                                                                           
True     True     String                                 System.Object

With this it should work:

$files[0].name.split("_")
Sign up to request clarification or add additional context in comments.

Comments

1

Try:

$files[0].ToString().split("_")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.