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?
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.
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?
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.
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.
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
Put single quotes around 7Ui4RT,@T
, i.e.
'7Ui4RT,@T'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With