简体   繁体   English

Powershell,转义正则表达式转义方法中不存在的字符串变量中的特定字符

[英]Powershell, escaping specific character in string variable not present in regex escape method

From this post I learned that I can use [Regex]::Escape() to escape all the commonly escaped characters in string variables.这篇文章中我了解到我可以使用 [Regex]::Escape() 来转义字符串变量中所有常见的转义字符 The problem is that I'm going to use a path that contains & characters and then use that in a URL for a RestAPI call, and that escape method does not escape the & character.问题是我将使用包含 & 字符的路径,然后在 URL 中使用它进行 RestAPI 调用,并且该转义方法不会转义 & 字符。

When the path contains & the API interprets this as an operator in the URL and is not parsed correctly:当路径包含 & 时,API 将此解释为 URL 中的运算符并且未正确解析:

$MyPath = "\\Server\Share\Something & Something Else"
$MyURL= "http://localhost/Address/to/APIResource/"
Invoke-RestMethod -Method Get -Uri ("$MyURL" + "?path=$MyPath") -UseDefaultCredentials

The ?path=$MyPath is the problem, since $MyPath contains & and will therefore not work. ?path=$MyPath 是问题所在,因为 $MyPath 包含 & 并且因此不起作用。 How can I escape the & character inside $MyPath to make it work with the RestAPI?如何转义 $MyPath 中的 & 字符以使其与 RestAPI 一起使用?

I learned that I can use [Regex]::Escape() to escape all the commonly escaped characters in string variables我了解到我可以使用[Regex]::Escape()来转义字符串变量中的所有常见转义字符

And now you'll learn that that isn't true at all :)现在你会知道这根本不是真的:)

[regex]::Escape() only escapes characters that would otherwise risk being interpreted as escape sequences as defined by .NET's regular expression grammar - it's designed for, and only guaranteed to work in, that context. [regex]::Escape()转义那些可能会被解释为.NET 正则表达式语法定义的转义序列的字符 - 它是为该上下文设计的,并且只能保证在该上下文中工作。


For URI parameters, you'll want to use [uri]::EscapeDataString() :对于 URI 参数,您需要使用[uri]::EscapeDataString()

Invoke-RestMethod -Uri ("$MyURL" + [uri]::EscapeDataString("?path=$MyPath")) ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM