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?
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