PowerShell: remove or replace quote marks from variable

后端 未结 6 1028
栀梦
栀梦 2021-02-19 02:24

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.

Th

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-19 02:33

    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
    

提交回复
热议问题