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

Time:04-22

I am working on a new tool to help automate some tedious processes. it involves ExchangeOnlineManagement, Python, and Powershell.

I have input variables that I am feeding into Powershell commands via Formatted string.

An example that works:

Email = input("Please provide your domain email address ")

sp.run(f"Connect-IPPSSession -UserPrincipalName {Email}", shell=True)

This works with no problem.

However, when I run:

Search_Name = input("What is the name of the Content Search? ")

sp.run(f'Get-ComplianceSearchAction {Search_Name}', shell=True)

I get the following:

  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

The original syntax for the command (That works on my machine currently) is

Get-ComplianceSearchAction "@chanroodee.com_purge"

I am assuming that because there are no quotes around the Search_Name var, it is not processing it as an argument. So my goal I guess is to enable quotes to be around every string that passes through the Search_Name input. so that it can be processed as an argument rather than a random string.

CodePudding user response:

Something like: f'Get-ComplianceSearchAction "{Search_Name}"'?

CodePudding user response:

A fully robust solution that guarantees that whatever string value you pass to PowerShell is used verbatim requires:

  • using embedded '...' quoting
  • which in turn requires that any ' characters contained in the value be escaped as '':
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)

A simpler solution is possible if you can assume that your string values never contain ` or $ characters (which would be subject to string interpolation by PowerShell inside "..."), using !r, as suggested by jonrsharpe, which calls the string's __repr__() method in order to automatically return a quoted representation of the value - which uses embedded '...' quoting by default, but switches to embedded "..." quoting if the string itself contains ' (and not also "):

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