我正在嘗試在 powershell 中執行以下命令,但沒有如何轉義 & 字符,因為這是 url 的一部分
az rest `
--method GET `
--uri ("https://graph.microsoft.com/v1.0/groups?`$count=true&`$filter=startsWith(displayName,'some filter text')&`$select=id,displayName") `
--headers 'Content-Type=application/json'
由于 & 字符用于啟動一個新命令,它會破壞 url 并希望執行其余部分。
有沒有辦法告訴powershell不要這樣做?
uj5u.com熱心網友回復:
奧拉夫的回答提供了一個有效的解決方案;讓我添加一個解釋:
問題的根源是兩種行為的匯合:
呼叫外部程式時,PowerShell僅根據給定引數值是否包含空格來執行每個引數的按需雙引號- 否則,引數將不帶引號傳遞- 無論該值最初是否在PowerShell命令中被參考(例如,,和所有導致未參考的作為命令列上的最后一個令牌傳遞 PowerShell 在幕后重建以最終用于執行)。
cmd /c echo abcmd /c echo 'ab'cmd /c echo "ab"abAzure
azCLI以批處理檔案(az.cmd) 的形式實作,當呼叫批處理檔案時,它會cmd.exe決議給定的引數;令人驚訝 - 并且可以說是不恰當的 - 它決議它們,就好像命令是從cmd.exe會話內部提交的一樣。
因此,如果一個引數從 PowerShell 傳遞到一個批處理檔案,該批處理檔案 (a) 不包含空格,但 (b) 包含cmd.exe元字符,例如&,則呼叫會中斷。
一個簡單的演示,使用cmd /c echo呼叫作為對批處理檔案的呼叫的替代:
# !! Breaks, because PowerShell (justifiably) passes *unquoted* a&b
# !! when it rebuilds the command line to invoke behind the scenes.
PS> cmd /c echo 'a&b'
a
'b' is not recognized as an internal or external command,
operable program or batch file.
有三種解決方法:
- 使用嵌入式
"..."參考:
# OK, but with a CAVEAT:
# Works as of PowerShell 7.2, but arguably *shouldn't*, because
# PowerShell should automatically *escape* the embedded " chars. as ""
PS> cmd /c echo '"a&b"'
"a&b"
- 使用
--%,停止決議令牌-但請參閱此答案的底部以了解其局限性--%及其相關陷阱。
# OK, but with a CAVEAT:
# Requires "..." quoting, but doesn't recognize *PowerShell* variables,
# also doesn't support single-quoting and line continuation.
PS> cmd /c echo --% "a&b"
"a&b"
- 通過呼叫
cmd /c并傳遞包含批處理檔案呼叫及其所有引數的單個字串,(最終)使用cmd.exe's syntax。
# OK (remember, cmd /c echo stands for a call to a batch file, such as az.cmd)
# Inside the single string passed to the outer cmd /c call,
# be sure to use "...", as that is the only quoting cmd.exe understands.
PS> cmd /c 'cmd /c echo "a&b"'
"a&b"
退后一步:
現在,如果您不必擔心所有這些事情,那不是很好嗎?特別是因為你可能不知道或不關心,如果給定的CLI -如az-這樣恰好被實作為一個批處理檔案?
作為外殼,PowerShell中應盡力轉發引數忠實地在幕后,并允許呼叫者集中專門在僅滿足PowerShell的語法規則:
不幸的是,PowerShell 迄今為止(PowerShell 7.2)在這方面通常做得很差,無論
cmd.exe's 的怪癖如何- 請參閱此答案以獲取摘要。關于
cmd.exe's (batch-file call) 的怪癖,PowerShell可以在未來的版本中可以預見地補償它們——但不幸的是,這似乎不會發生;請參閱GitHub 問題 #15143。
uj5u.com熱心網友回復:
我現在無權訪問 Azure 租戶進行測驗,實際上我通常沒有使用 Azure CLI 的經驗,但我希望這可以作業:
az rest `
--method GET `
--uri 'https://graph.microsoft.com/v1.0/groups?$count=true&$filter=startsWith(displayName,some filter text)&$select=id,displayName' `
--headers 'Content-Type=application/json'
或這個:
az rest --method GET --headers "Content-Type=application/json" `
--% --uri "https://graph.microsoft.com/v1.0/groups?$count=true&$filter=startsWith(displayName,some filter text)&$select=id,displayName"
我只是添加了反引號以提高可讀性 - 您可以在實際代碼中洗掉它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420891.html
標籤:
