Escaping $_ in powershell inside python

67 Views Asked by At

Can you please tell me why the dollar sign output does not work? I used this construction:

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"'
)

Now I am trying to change my query in powershell like this

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

But when I write it in python with (`) dollar escape

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

an error occurs

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

What am I doing wrong?

1

There are 1 best solutions below

0
mklement0 On BEST ANSWER
  • Remove the embedded "..." around the Where-Object argument (it expects just a script block, not a string; in cases where you truly need embedded " chars., escape them as \" for PowerShell, which in an f-string means \\")
  • No need to escape $ characters.
  • In order to embed verbatim { and } characters in a Python f-string, escape them as {{ and }}, respectively.

Therefore:

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