1

Basicly I am trying to find a way to put a variable for replacing a line in powershell.

The current script:

$switches = get-outlookinbox | where subject -eq "Hello"
    $e = $switches.body
    $e = $e.replace("Hello:","")
    $e = $e.replace(" Number","")
    $e = $e.replace(":1","")
    $e = $e.replace(":2","")
    $e = $e.replace(":3","")
    $e = $e.replace(":4","")
    $e = $e.replace(":99","")

You can see what I am going for here... But I don't want 99 lines of replace code, any thoughts on this? Also, the numbers MUST have : infront of it, otherwise the replace will corrupt the file since it contains only IP's and ports, it's the ports I want to remove from the output.

3 Answers 3

2

You can use a simple foreach loop and iterate from 99 to 1:

foreach ($n in 99..1)
{
    $e = $e.Replace(":$n", " ")
}

Or, if you prefer one line:

foreach ($n in 99..1) { $e = $e.Replace(":$n", " ") }

Demo:

PS > $mystr = "a:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20b"  
PS > foreach ($n in 20..1) { $mystr = $mystr.replace(":$n", "") }
PS > $mystr
ab 
PS > 
Sign up to request clarification or add additional context in comments.

2 Comments

Conveniently your demo only goes up to 9... if it went into double digits it would be very obvious that this does not work
@Cole9350 - Ah, my mistake. I should be iterating in reverse. Thanks for pointing that out.
2

Regular expressions : regex101.com

$e = $e -replace ':\d+',""

No loops necessary

Comments

2

Might as well get 'em all while you're at it:

$e -replace 'Hello:| Number|:\d{1,2}' 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.