【问题标题】:Replace in Powershell在 Powershell 中替换
【发布时间】:2016-09-01 09:56:00
【问题描述】:

我正在尝试打印出 Microsoft 更新热修复 URL 并更改它们

    $link=Get-MSHotfix|Where-Object {$_.Installedon -gt ((Get-Date).Adddays(-20000))}|Select-Object -Property KBArticle 


foreach($line in $link){

        [String]$line = $line -replace 'http://support.microsoft.com/?kbid=','https://support.microsoft.com/en-us/kb/'


    [String]$line
}

我有问题,因为它像这样打印出来并且没有替换:

@{KBArticle=http://support.microsoft.com/?kbid=3045992}
@{KBArticle=http://support.microsoft.com/?kbid=3045999}
@{KBArticle=http://support.microsoft.com/?kbid=3046017}
@{KBArticle=http://support.microsoft.com/?kbid=3046359}
@{KBArticle=http://support.microsoft.com/?kbid=3046737}

如果我只打印它而不使用 -replace,它看起来没问题。

我正在尝试获取知识库文章的完整 URL

我正在尝试创建一个脚本,如果可能的话,将打印出所有带有链接和名称的热修复程序

谢谢

【问题讨论】:

  • 你有什么问题?
  • -replace 参数是一个正则表达式。要么将? 转义为\?,要么使用明文方法$line.replace('foo', 'bar')
  • 嗨,如果我使用replace('foo', 'bar'),我会收到错误:Method invocation failed because [Selected.System.Management.Automation.PSCustomObject] does not contain a method named 'Replace'.
  • 使用Select-Object -ExpandProperty 而不是Select-Object -Property

标签: windows powershell hotfix


【解决方案1】:

是的,你必须构建正则表达式, RegEx101

$link=Get-MSHotfix|Where-Object {$_.Installedon -gt ((Get-Date).Adddays(-20000))}|Select-Object -Property KBArticle 

foreach($line in $link){

        [String]$line = $line -replace "http:\/\/support\.microsoft\.com\/\?kbid=",'https://support.microsoft.com/en-us/kb/'


    [String]$line
}

或者你使用子字符串:

$link=Get-MSHotfix|Where-Object {$_.Installedon -gt ((Get-Date).Adddays(-20000))}|Select-Object -Property KBArticle 


foreach($line in $link){

        [String]$line = 'https://support.microsoft.com/en-us/kb/' + $line.substring(35)


    [String]$line
}

删除前 35 个字符的字符串并将其添加到您的网址。

编辑:

非常有趣,另一种替换也有效...

$link=Get-MSHotfix|Where-Object {$_.Installedon -gt ((Get-Date).Adddays(-20000))}|Select-Object -Property KBArticle 

foreach($line in $link){

    [String]$line = $line.replace("http://support.microsoft.com/?kbid=",'https://support.microsoft.com/en-us/kb/')


[String]$line
}

我有点迷茫……

如果你使用 -replace,你必须使用正则表达式,如果你调用函数 .replace(),你需要给出一个字符串。

【讨论】:

  • 您好,这有效,只是现在我得到了这样的@{KBArticle=https://support.microsoft.com/en-us/kb/3160005} 如何从输出中删除@{KBArticle and }?谢谢
  • 这工作$link=Get-MSHotfix|Where-Object {$_.Installedon -gt ((Get-Date).Adddays(-20000))}|Select-Object -ExpandProperty KBArticle foreach($line in $link){ $line = $line -replace "http:\/\/support\.microsoft\.com\/\?kbid=",'https://support.microsoft.com/en-us/kb/' $line }
  • with $line.KBArticle --> 输出是具有属性 KBArticle 的对象 --> 您必须访问该属性而不是 [String]$line --> 使用 [String]$line.KBArticle
猜你喜欢
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2018-10-11
  • 1970-01-01
相关资源
最近更新 更多