我正在開發一種新工具來幫助自動化一些繁瑣的程序。它涉及 ExchangeOnlineManagement、Python 和 Powershell。
我有輸入變數,我通過格式化字串輸入 Powershell 命令。
一個有效的例子:
Email = input("Please provide your domain email address ")
sp.run(f"Connect-IPPSSession -UserPrincipalName {Email}", shell=True)
這沒有問題。
但是,當我運行時:
Search_Name = input("What is the name of the Content Search? ")
sp.run(f'Get-ComplianceSearchAction {Search_Name}', shell=True)
我得到以下資訊:
Get-ComplianceSearchAction @chanroodee.com_purge
~~~~~~~~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@chanroodee' can be used only as an argument to a command.
To reference variables in an expression use '$chanroodee'.
CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
FullyQualifiedErrorId : SplattingNotPermitted
該命令的原始語法(目前適用于我的機器)是
Get-ComplianceSearchAction "@chanroodee.com_purge"
我假設因為 Search_Name 變數周圍沒有引號,所以它沒有將其作為引數處理。所以我想我的目標是讓引號圍繞通過 Search_Name 輸入的每個字串。以便它可以作為引數而不是隨機字串處理。
uj5u.com熱心網友回復:
一個完全強大的解決方案,保證您傳遞給 PowerShell 的任何字串值都被逐字使用,需要:
- 使用嵌入式
'...'參考 - 這反過來又要求
'將值中包含的任何字符轉義為'':
Search_Name = input("What is the name of the Content Search? ")
Search_Name_Escaped = Search_Name.replace("'", "''")
sp.run(f'Get-ComplianceSearchAction \'{Search_Name_Escaped}\'', shell=True)
請注意,嘗試將運算式Search_Name.replace("'", "''")直接放在{...}-f-string 中是很誘人的,但這需要\-escaping'字符,而\inside 不支持使用{...}。
如果您可以假設您的字串值從不包含或字符(這將受到 PowerShell inside 的字串插值),則可以使用更簡單的解決方案,如jonrsharpe建議的那樣,它呼叫字串的方法以自動回傳帶引號的表示的值 -默認情況下使用嵌入參考,但如果字串本身包含(而不是)則切換到嵌入參考:`$"..."!r__repr__()'...'"..."'"
Search_Name = input("What is the name of the Content Search? ")
sp.run(f'Get-ComplianceSearchAction {Search_Name!r}', shell=True)
uj5u.com熱心網友回復:
像這樣的東西:f'Get-ComplianceSearchAction "{Search_Name}"'?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/462218.html
上一篇:在file1中查找一個單詞并復制下一個單詞并在file2中替換它的腳本
下一篇:使用Pester模擬功能不起作用
