Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand variable inside single quotes

How can I expand $pw inside single quotes?

$pw = "$PsHome\powershell.exe"
cmd.exe /c 'schtasks /create /tn cleanup /tr "$pw -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1" /sc minute /mo 1'
like image 357
Pedro Lobito Avatar asked Aug 20 '15 20:08

Pedro Lobito


People also ask

How do you pass variables in single quotes?

If the backslash ( \ ) is used before the single quote then the value of the variable will be printed with single quote.

How do you put a variable in a quote?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

How do you pass variables in single quotes in PowerShell?

'Single Quotes' Single quotation strings are what you will most often use and encounter when creating or troubleshooting PowerShell scripts. Consider the following example: # Assign a variable with a literal value of 'single'. $MyVar1 = 'single' # Put the variable into another literal string value.

Which of the variable is enclosed in single quotes?

In C and C++ the single quote is used to identify the single character, and double quotes are used for string literals. A string literal “x” is a string, it is containing character 'x' and a null terminator '\0'. So “x” is two-character array in this case. In C++ the size of the character literal is char.


1 Answers

You can use formatting and assign it to another variable:

$pw = "$PsHome\powershell.exe";
$command = 'schtasks /create /tn cleanup /tr "{0} -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1" /sc minute /mo 1' -f $pw;
cmd.exe /c $command

Or you can use double quotes and escape the inside quotes with quotes:

$pw = "$PsHome\powershell.exe"
cmd.exe /c "schtasks /create /tn cleanup /tr ""$pw -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1"" /sc minute /mo 1"

Or do the same but use backtick (grave) to escape them:

$pw = "$PsHome\powershell.exe"
cmd.exe /c "schtasks /create /tn cleanup /tr `"$pw -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile %TEMP%\exec.ps1`" /sc minute /mo 1"
like image 50
Bacon Bits Avatar answered Oct 07 '22 01:10

Bacon Bits