1

I'm trying to create a script that will split on various object. For example I have disks name

vm01-disk1
vm01_disk2

I'm trying to split the disk names so I can rename the disk vm, but retain the disk number, what I've tried is

 $snapshot = Get-AzSnapShot
 $vhdlong = ($snapshot.name).Split("_")[0]
 $vhdrename = $vhdlong.split("-")[1]

But this still leaves vm01_disk2 untouched, if I add $vhdrename = $vhdlong.split("_")[1] it leaves vm01-disk1 untouched.

Hope that makes sense. Thanks in advance for any tips or advice :)

Norrin Rad
  • 881
  • 2
  • 18
  • 42
  • 2
    Seems like you just need to loop through `$snapshot.name`. – Santiago Squarzon Jul 01 '21 at 21:47
  • 1
    If `Get-AzSnapShot` returns more than one object (an array of snapshots) I'd rather use a loop to process whatever you need. ;-) – Olaf Jul 01 '21 at 21:47
  • 2
    The (string) `.Split()` method accepts more character/string separators in an array. Try `.Split([char[]]'-_')`. Check _OverloadDefinitions_ using `''.Split`. – JosefZ Jul 01 '21 at 21:54
  • `'ab_cd-ef' -split '_|-'` – lit Jul 01 '21 at 22:13
  • Thanks All. That's really helpful, I think JosefZ hit the nail on the head and works perfectly If you'd like to mark it as an answer I'll accept it, thanks again all :) – Norrin Rad Jul 01 '21 at 22:14

1 Answers1

2
  • Unless performance is paramount, I suggest routinely using PowerShell's regex-based -split operator, for the reasons discussed in this answer.

    • Splitting by any from a set of characters can be expressed as enclosing these characters in [...] in a regex; in the case at hand: [-_]
  • The .ForEach() array method enables a (fairly) efficient way to operate on each element of a collection of values already in memory.

Therefore, I suggest the following:

(Get-AzSnapShot).Name.ForEach({ ($_ -split '[-_]')[1] })
mklement0
  • 382,024
  • 64
  • 607
  • 775