Search code examples
powershellreplacesplitpowershell-2.0file-get-contents

Hello, how to get a string between commas


I'm trying to get the number in the middle of a sentences with some comma.

I have a powershell.ps1 file that contain array bellow

$Person = "Tom,Jerry,Buldog,12345,Cartoon"

I'm trying to get the 12345 only.

This is the code I tried

(Get-Content c:\powershel.ps1 | Select-Object -First 1) -replace”.*= " -replace '"' -replace '.*,'

But the result I got is just Cartoon.


Solution

  • You can get it using by split function. The first element starts with '0'.

    $Person = "Tom,Jerry,Buldog,12345,Cartoon"
    $array = $Person.Split(",")
    $array[3]