在 python 内的 powershell 中转义 $_

Escaping $_ in powershell inside python

提问人:Norbert Yuhas 提问时间:8/6/2023 更新时间:8/6/2023 访问量:46

问:

你能告诉我为什么美元符号输出不起作用吗? 我使用了这个结构:

commands = (
    f'powershell.exe -noprofile -command "&Get-ADUser -Filter (\\"OfficePhone -like {internal_number}\\") '
    f'-Properties SID | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString '
    f'-AsPlainText \\"{gen_password}\\" -Force -Verbose) -PAssThru | Unlock-ADAccount"'
)

现在我正在尝试像这样在powershell中更改我的查询

Get-ADUser -Filter * -Properties OfficePhone, Mobile, SID | Where-Object {  $_.OfficePhone -eq "888888" -or   $_.Mobile -eq "888888"  } | Select-Object SID

但是当我用 python 用 (') 美元转义编写它时

f'powershell.exe -noprofile -command "&Get-ADUser -Filter * -Properties OfficePhone, Mobile, SID | Where-Object "{`$_.OfficePhone -eq {internal_number} -or `$_.Mobile -eq {internal_number}}" '

发生错误

(`$_.OfficePhone -eq {internal_number} -or `$_.Mobile -eq {internal_number})
     ^
SyntaxError: invalid syntax

我做错了什么?

python-3.x PowerShell 转义 引号

评论


答:

1赞 mklement0 8/6/2023 #1
  • 删除参数周围的嵌入(它只需要一个脚本块,而不是一个字符串;在你真正需要嵌入字符的情况下,像 PowerShell 一样转义它们,这在 f 字符串中意味着"..."Where-Object"\"\\")
  • 无需转义字符。$
  • 为了在 Python f 字符串中嵌入逐字和字符,请分别将它们转义为 和 。{}{{}}

因此:

f'powershell.exe -noprofile -command "Get-ADUser -Filter * -Properties OfficePhone, Mobile, SID | Where-Object {{ $_.OfficePhone -eq {internal_number} -or $_.Mobile -eq {internal_number} }}"'

评论

1赞 mklement0 8/7/2023
很高兴听到它,@NorbertYuhas;感谢您接受。