Search code examples
windowspowershellhotfix

Replace in Powershell


I am trying to print out Microsoft update hot fix URLs and change them

    $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
}

I have problem because it prints it out like this and it is not replacing:

@{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}

If I just print it without -replace it looks ok.

I am trying to get full URL of KB Article

I am trying to create a script with will print out all hot fixes with links and names from title if possible

Thanks


Solution

  • Yep you have to build the regular expression, 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
    }
    

    or you use substring:

    $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
    }
    

    cut the strings by first 35 characters and add it to your url.

    EDIT:

    very interesting, what also works is the other kind of replace...

    $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
    }
    

    I'm a bit confused...

    if you use -replace you have to take a regex if you call the function .replace() you need to give a string.