5

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BaltoStar
  • 8,165
  • 17
  • 59
  • 91

2 Answers2

7

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

Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
3

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

'7Ui4RT,@T'
David
  • 6,462
  • 2
  • 25
  • 22