Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Invoke-Expression command parameter contains comma

What should I do when a password contains PowerShell special characters?

Invoke-Expression -Command "net use x: $Path /USER:domain1\user1 7Ui4RT,@T /persistent:no"

This fails on syntax -- because PowerShell interprets 7Ui4RT,@T as an array:

Invoke-Expression -Command "net use x: $Path /USER:domain1\user1 7Ui4RT`,@T /persistent:no"

This fails on syntax -- apparently because PowerShell can't interpret 7Ui4RT``,@T

Invoke-Expression -Command "net use x: $Path /USER:domain1\user1 "7Ui4RT,@T" /persistent:no"

This fails because PowerShell interprets 7Ui4RT,@T as an object, not a string (error = "A positional parameter cannot be found that accepts argument 'System.Object[]'.").

What should I do?

like image 932
BaltoStar Avatar asked Apr 16 '13 23:04

BaltoStar


People also ask

How do you pass parameters to invoke expressions?

The only parameter Invoke-Expression has is Command . There is no native way to pass parameters with Invoke-Expression . However, instead, you can include them in the string you pass to the Command parameter.

How do you use commas in PowerShell?

Commas are array separators in PowerShell. You should either escape them or encase the parameter in double quotes and then write some logic to split your string that contains commas. E.g. Your cmdlet call should be: Get-Weather "Shrewsbury,MA?

What does invoke-expression do in PowerShell?

Description. The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression , a string submitted at the command line is returned (echoed) unchanged. Expressions are evaluated and run in the current scope.

How do I call a PowerShell script with parameters?

You can run scripts with parameters in any context by simply specifying them while running the PowerShell executable like powershell.exe -Parameter 'Foo' -Parameter2 'Bar' . Once you open cmd.exe, you can execute a PowerShell script like below.


2 Answers

Why are you using Invoke-Expression to evaluate your command? If you need to build up a set of arguments dynamically, you can place them in an array:

$command = 'net'
$commandArgs = @('use','x:',$Path,'/USER:domain1\usr1','7Ui4RT,@T','/persistent:no')
& $command $commandArgs

If you know the command ahead of time, you can call it directly: net $commandArgs

like image 172
Emperor XLII Avatar answered Sep 22 '22 00:09

Emperor XLII


Put single quotes around 7Ui4RT,@T, i.e.

'7Ui4RT,@T'
like image 25
David Avatar answered Sep 19 '22 00:09

David