Answered by:
Formatting a variable

Question
-
Hi,
I'm trying to change the format of a variable in my script. I'd like to change a variable from this
$Name = "Thistext-11.11.11-moretext"
I want to change the text to something like this in a new variable
"11_11_11differenttext"
I've got most of it working
$New = $VMName -replace "Thistext-","" -replace "-moretext",""
result is "11.11.11"
If I try to replace the "." the result is "_______"
$New = $VMName -replace "Thistext-","" -replace "-moretext","" -replace ".","_"
TIA
- Edited by David Maximoff Wednesday, May 20, 2020 10:34 PM
Wednesday, May 20, 2020 10:20 PM
Answers
-
Thanks JRV
I got it working with the following. For some reason it doesn't work as a single line but this is fine.
$ISOname = "text-11.2.111-moretext"
$New = $ISOname -replace "text-","" -replace "-moretext","" -replace "\.","\_" -replace "\\",""
$VMName = "Newtext_"+$VMName+"_morenew"So the output is
Newtext_11_2_111_morenew
- Marked as answer by David Maximoff Thursday, May 21, 2020 12:59 AM
- Edited by David Maximoff Thursday, May 21, 2020 1:00 AM
Thursday, May 21, 2020 12:57 AM
All replies
-
Two methods can be used.
'Thistext-11.11.11-moretext' -replace 'Thistext-' ('Thistext-11.11.11-moretext' -split '-')[1..2] -join ''
But, if you want the numbers then we would do this:
'Thistext-11.11.11-moretext' -replace '.*-(\d+\.\d+\.\d+).*','$1'
To replace the dots we would do this:
'Thistext-11.11.11-moretext' -replace '.*-(\d+\.\d+\.\d+).*','$1' -replace '\.'
\_(ツ)_/
- Edited by jrv Wednesday, May 20, 2020 10:40 PM
- Proposed as answer by Vector BCO Thursday, May 21, 2020 5:49 AM
Wednesday, May 20, 2020 10:35 PM -
Thanks JRV
I got it working with the following. For some reason it doesn't work as a single line but this is fine.
$ISOname = "text-11.2.111-moretext"
$New = $ISOname -replace "text-","" -replace "-moretext","" -replace "\.","\_" -replace "\\",""
$VMName = "Newtext_"+$VMName+"_morenew"So the output is
Newtext_11_2_111_morenew
- Marked as answer by David Maximoff Thursday, May 21, 2020 12:59 AM
- Edited by David Maximoff Thursday, May 21, 2020 1:00 AM
Thursday, May 21, 2020 12:57 AM -
I'm not sure why you couldn't get it to work.
$ISOname = "text-11.2.111-moretext" $VMName = $ISOname -replace '^.+(\d+)\.(\d+)\.(\d+).*$','Newtext_$1_$2_$3_morenew'
--- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)
Thursday, May 21, 2020 2:03 AM