prosource

PowerShell: 변수에서 따옴표 제거 또는 바꾸기

probook 2023. 8. 11. 22:23
반응형

PowerShell: 변수에서 따옴표 제거 또는 바꾸기

Get-EventLog를 사용하여 변수를 설정한 다음 이벤트 ID 설명으로 다른 변수를 설정합니다.그런 다음 노골적으로 사용합니다.이 정보를 그룹에 전자 메일로 보냅니다.

설명에 따옴표가 있습니다.따옴표로 인해 오류와 함께 노골적으로 종료됩니다.

이벤트에서 인용문을 제거할 수 있는 방법이 있습니까?메시지를 보내고 공백이나 다른 것으로 대체하시겠습니까?

변수가 String 개체인 경우 다음을 수행할 수 있습니다.

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

사실 방금 받았어요.인용문과 중복 인용문의 수는 저를 혼란스럽게 했지만, 이것은 효과가 있었고 노골적으로 오류가 없었습니다.

$var -replace '"', ""

이러한 따옴표는 싱글, 더블, 싱글, 콤마, 더블, 더블입니다.

경우에 따라 트림(Char[]) 방법을 사용하는 것이 더 쉬울 수 있습니다.
...선행 및 후행 발생을 모두 제거합니다.

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

$your_variable의 시작과 끝에서만 따옴표를 제거합니다.$your_variable 텍스트 안에 있는 모든 따옴표는 이스케이프 여부와 상관없이 다음과 같이 유지됩니다.

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

사용할 수 있습니다.Trim('"'),Trim("'")하지만 둘 다:Trim("`"'")

트리밍()은 따옴표가 고아지더라도 상관하지 않으므로 문자열의 다른 쪽에 쌍을 이룬 따옴표가 있는지 여부에 관계없이 끝 또는 시작 따옴표를 제거합니다.

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

파워셸의 기본 제공 기능을 사용하는 경우send-mailmessage(2.0 필요)에 대한 종속성을 제거할 수 있습니다.blat.exe이벤트 로그의 설명을 편집하지 않고 이 문제를 올바르게 처리할 수 있습니다.

문제는 단순 바꾸기를 사용하면 이스케이프(두 배)된 경우에도 모든 따옴표 문자가 지워진다는 것입니다.다음은 제가 사용하기 위해 만든 기능입니다.

  • 고아 인용문만 제거하는 것.
  • 그들에게서 도망치는 자.

또한 옵션인 $charToReplace 매개 변수를 사용하여 다른 문자를 관리하기 위해 일반적으로 만들었습니다.

#Replaces single occurrences 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'

위의 답변 중 하나도 저에게 효과가 없었습니다.그래서 저는 다음과 같은 해결책을 만들었습니다.

문자 단일 따옴표 """asci 문자(39)를 공백 ""asci 문자(32)로 검색 및 바꾸기

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

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

언급URL : https://stackoverflow.com/questions/14816571/powershell-remove-or-replace-quote-marks-from-variable

반응형