I have a problem passing arguments to a powershell script from a command window. This only happens on one of my windows 10 laptops. Did I miss some configuration of powershell to handle arguments correctly?
I have set my powershell execution policy to unrestricted
PS C:\Windows> get-executionpolicy Unrestricted
My test.ps1 file is
[Byte[]] $On = 0xA0,0x01,0x01,0xA2
$port = new-Object System.IO.Ports.SerialPort $args[0],9600,None,8,one
$port.Open()
$port.Write($On, 0, $On.count)
$port.Close()
In powershell (run as administrator)
PS C:\Windows> C:\Users\me\test.ps1 "COM4"
result: success
From a CMD window (run as administrator)
C:\WINDOWS\system32>powershell -File C:\Users\me\test.ps1 "COM4"
result:
Exception calling "Open" with "0" argument(s): Access to the port 'COM4' is denied."
At C:\Users\me\test.ps1:3 char:1
+ $port.Open()
`~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : UnauthorizedAccessException
.
.
If I change the $args[0] in the ps1 file replacing it with COM4 I.E.
$port = new-Object System.IO.Ports.SerialPort COM4,9600,None,8,one
and run
C:\WINDOWS\system32>powershell -File C:\Users\me\test.ps1
result: success
So somehow the argument string is not being parsed correctly. If I put in this debug code in the original ps1 file:
echo "input arg >" $args[0] "<"
then the output is:
input arg >
COM4
<
I.E. there are carriage returns on either side of the args[0] string.
Oddly - this problem only happens on one of my laptops - the other (also windows 10) handles this ps1 script with the "COM4" arguments just fine. Somehow there's a difference between the argument handling on the two machines. The debug output (above) on the laptop that runs the script properly is identical - I.E. with the carriage returns either side of the COM4 text.
.Trim()to your aguments:$args[0].Trim()"COM4"orCOM4as an argument makes no difference - the script (normally) sees verbatim, unquotedCOM4. The issue isn't one of quoting (note that the diagnostic output has no quotes), but one of extraneous surrounding newlines. Conceivably, there could be hidden control characters in the argument string (though I wouldn't know which specific ones would cause this symptom).