有没有办法确保格式化字符串始终在引号中?

Is there a way to make sure formatted string is always in quotations?

我正在开发一种新工具来帮助自动化一些繁琐的流程。 它涉及 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 var 周围没有引号,所以它没有将其作为参数处理。所以我想我的目标是让引号出现在通过 Search_Name 输入的每个字符串周围。这样它就可以作为参数而不是随机字符串进行处理。

类似于:f'Get-ComplianceSearchAction "{Search_Name}"'?

完全稳健解决方案,保证使用您传递给 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 中的 {...} 中很诱人,但这需要 \ - 转义 ' 字符,而在 {...}.

中不支持使用 \

更简单解决方案是可能的如果您可以假设您的字符串值从不包含`$ 个字符 (这将受到 PowerShell 在 "..." 内的字符串插值), 使用 !r,如jonrsharpe,它调用字符串的 __repr__() 方法以自动 return 值的 引用 表示 - 使用嵌入式 '...'默认引用,但如果字符串本身包含 '(而不是 "),则切换到嵌入 "..." 引用:

Search_Name = input("What is the name of the Content Search? ")
sp.run(f'Get-ComplianceSearchAction {Search_Name!r}', shell=True)