PowerShell: remove or replace quote marks from variable

倾然丶 夕夏残阳落幕 提交于 2020-06-25 07:36:05

问题


I'm using Get-EventLog to set a variable, and then setting another variable with the event ID description. I then use blat.exe to email this information to a group.

The description contains quotation marks. The quotation marks are causing blat to exit with error.

Is there a way to remove the quotes from the event.Message and replace them with a space or something?


回答1:


If the variable is a String object then you can do the following:

$Variable.Replace("`"","")



回答2:


I actually just got it. The number of quotes and double quotes was confusing me, but this has worked and blat did not error.

$var -replace '"', ""

Those quotes are: single, double, single, comma, double, double.




回答3:


Depending on a case, it might be simpler to use Trim(Char[]) method:
...Removes all leading and trailing occurrences...

e.g. $your_variable.Trim('"')  

It will remove quotes only from start and end of $your_variable. It will keep any quotes, escaped or not, which are inside the text of $your_variable as they were:

PS C:\> $v.Trim('"') # where $v is: "hu""hu"hu'hu"
hu""hu"hu'hu

You can use Trim('"'), Trim("'"), but also both: Trim("`"'")

Note that Trim() does not care if a quote is orphaned, meaning that it will remove ending or starting quote regardless of it having or not a paired quote on the other side of the string.

PS C:\Users\Papo> $hu = "A: He asked `"whos this sofa?`" B: She replied: `"Chris'`""
PS C:\Users\Papo> $hu
A: He asked "whos this sofa?" B: She replied: "Chris'"
PS C:\Users\Papo> $hu.trim('"')
A: He asked "whos this sofa?" B: She replied: "Chris'
PS C:\Users\Papo> # and even worse:
PS C:\Users\Papo> $hu.trim("'`"")
A: He asked "whos this sofa?" B: She replied: "Chris



回答4:


If you use Powershell's built-in send-mailmessage (2.0 required), you can eliminate your dependency on blat.exe and properly handle this issue without editing the description from the event log.




回答5:


The problem is that a simple replace cleans out every quote character, even if escaped (doubled). Here are the functions I created for my use :

  • one which removes only orphan quotes.
  • one which escapes them

I also made them generic to manage other characters, with the optionnal $charToReplace parameter

#Replaces single occurences of characters in a string.
#Default is to replace single quotes
Function RemoveNonEscapedChar {
    param(
        [Parameter(Mandatory = $true)][String] $param,
        [Parameter(Mandatory = $false)][String] $charToReplace
    )

    if ($charToReplace -eq '') {
        $charToReplace = "'"
    }
    $cleanedString = ""
    $index = 0
    $length = $param.length
    for ($index = 0; $index -lt $length; $index++) {
        $char = $param[$index]
        if ($char -eq $charToReplace) {
            if ($index +1 -lt $length -and $param[$index + 1] -eq $charToReplace) {
                $cleanedString += "$charToReplace$charToReplace"
                ++$index ## /!\ Manual increment of our loop counter to skip next char /!\
            }
            continue
        }
        $cleanedString += $char
    }
    return $cleanedString
}
#A few test cases : 
RemoveNonEscapedChar("'st''r'''i''ng'")                               #Echoes st''r''i''ng
RemoveNonEscapedChar("""st""""r""""""i""""ng""") -charToReplace '"'   #Echoes st""r""i""ng
RemoveNonEscapedChar("'st''r'''i''ng'") -charToReplace 'r'            #Echoes 'st'''''i''ng'


#Escapes single occurences of characters in a string.  Double occurences are not escaped.  e.g.  ''' will become '''', NOT ''''''.
#Default is to replace single quotes
Function EscapeChar {
    param(
        [Parameter(Mandatory = $true)][String] $param,
        [Parameter(Mandatory = $false)][String] $charToEscape
    )

    if ($charToEscape -eq '') {
        $charToEscape = "'"
    }
    $cleanedString = ""
    $index = 0
    $length = $param.length
    for ($index = 0; $index -lt $length; $index++) {
        $char = $param[$index]
        if ($char -eq $charToEscape) {
            if ($index +1 -lt $length -and $param[$index + 1] -eq $charToEscape) {
                ++$index ## /!\ Manual increment of our loop counter to skip next char /!\
            }
            $cleanedString += "$charToEscape$charToEscape"
            continue
        }
        $cleanedString += $char
    }
    return $cleanedString
}
#A few test cases : 
EscapeChar("'st''r'''i''ng'")                              #Echoes ''st''r''''i''ng''
EscapeChar("""st""""r""""""i""""ng""") -charToEscape '"'   #Echoes ""st""r""""i""ng""
EscapeChar("'st''r'''i''ng'") -charToEscape 'r'            #Echoes 'st''rr'''i''ng'



回答6:


None of the above answers worked for me. So I created the following solution...

Search and Replace the character single Quote "'" ascii Character (39) with a space " " ascii Character (32)

$strOldText = [char] 39
$strNewText = [char] 32

$Variable. = $Variable..Replace($strOldText, $strNewText).Trim()


来源:https://stackoverflow.com/questions/14816571/powershell-remove-or-replace-quote-marks-from-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!