'Is there a way to make sure formatted string is always in quotations?
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.
Solution 1:[1]
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)
Note that it is tempting to attempt putting the expression Search_Name.replace("'", "''") directly inside {...} in the -f-string, but that would require \-escaping the ' chars, whereas use of \ isn't supported inside {...}.
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)
Solution 2:[2]
Something like: f'Get-ComplianceSearchAction "{Search_Name}"'?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
