在Python中的powershell中转义$_

问题描述 投票:0回答:1

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

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 escaping quotes
1个回答
0
投票
  • 删除
    "..."
    参数周围嵌入的
    Where-Object
    (它只需要一个脚本块,而不是字符串;如果您确实需要嵌入
    "
    字符。请将它们转义为
    \"
  • 无需转义
    $
    字符。
  • 为了在 Python f 字符串中嵌入 verbatim
    {
    }
    字符,请将它们分别转义为
    {{
    }}

因此:

f'powershell.exe -noprofile -command "Get-ADUser -Filter * -Properties OfficePhone, Mobile, SID | Where-Object {{ $_.OfficePhone -eq {internal_number} -or $_.Mobile -eq {internal_number} }}"'
© www.soinside.com 2019 - 2024. All rights reserved.