Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Split a string in Powershell

Tags:

powershell

Suppose there is a string named as (ai-somename-someid) and it is stored in say

$x='ai-somename-someid'

Now I want to extract (somename)from the given string and pass it into another variable by using split(I am using the below script)

$y = $x.split("-")   
$y 

It is giving me the output as

ai  
somename   
someid  

but I would like to have only

somename

  

as the output.


1 Answers

There's a couple of way you can do that : If you only want one item this is the most straight forward way to do it. Simply cut your string and reference the id of the element you want to save.

$x="ai-somename-someid"
$y=$x.split("-")[1]

or you could do this instead if you are interested in keeping the other parts :

$x="ai-somename-someid"
$z,$y,$v=$x.split("-")

In this exemple $z will have ai, $y somename and $v someid.

If you are only interested in keeping some of the resulting string you can do this :

$x="ai-somename-someid"
$z,$y,$null=$x.split("-")

In this exemple $z will have ai, $y somename and everything after that goes to the trash.

like image 67
aperol Avatar answered Sep 07 '25 21:09

aperol