powershell - Powershell替换功能-用数字替换行

标签 powershell replace

基本上,我试图找到一种方法来将变量替换为Powershell中的一行。

当前脚本:

$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","")

您可以在这里看到我要做什么...但是我不希望有99行替换代码,对此有什么想法吗?
另外,数字必须在其前面带有:,否则替换将损坏文件,因为它仅包含IP和端口,这是我要从输出中删除的端口。

最佳答案

您可以使用简单的 foreach loop并从99迭代到1:

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

或者,如果您更喜欢一行:

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

演示:

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 > 

关于powershell - Powershell替换功能-用数字替换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24808918/

相关文章:

c# - New-PSSession 和 Runspacepool 说明

powershell - 从 LastLogonTimestamp 中提取日期

javascript - 如何仅替换外部函数中的某些 "this"?

C# Regex - 匹配不以特定单词开头的表达式

PowerShell MAML 帮助生成器

arrays - IF 包含多个字符串 do "this"else "this"

PowerShell - "Delete all files from this folder except one"的最紧凑方式

javascript - 如果字符串不是较大字符串的一部分,则使用 javascript 中的正则表达式替换字符串

regex - 如何使用 Perl 将以下字符串中的逗号替换为 & ?

Javascript 正则表达式替换结束标签和开始标签