Search code examples
powershellcommand-line-arguments

Powershell string array argument not working as intended when -File is used


I'm using a Powershell script that I found here: https://github.com/Simbiat/SnoozeGuard

The works by passing a string array and intended, when run in the usual way:

> C:\fullPathToSnoozeGuard.ps1 -requiresSystem 'arg1', 'arg2', 'arg3'
Searching for "arg1"...
Searching for "arg2"...
Searching for "arg3"...
No processes found
Feeling sleepy

But when run in using -File, it seems to not take the arguments as an array:

> C:\fullPathToPowershell.exe -File C:\fullPathToSnoozeGuard.ps1 -requiresSystem 'arg1', 'arg2', 'arg3'

C:\fullPathToSnoozeGuard.ps1 : Cannot process argument transformation on parameter 'pollingRate'. Cannot
convert value "arg3" to type "System.Int32". Error: "Input string was not in a correct format."
    + CategoryInfo          : InvalidData: (:) [SnoozeGuard.ps1], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,SnoozeGuard.ps1

Why does the -File cause it to stop treating the arguments as an array? What do I need to change in regards to my command?


Solution

    • When using the -File parameter of powershell.exe, the Windows PowerShell CLI, array argument values are not supported.[1]

      • Also note that '...' quoting is not recognized as such in this case; you must use "..." quoting.
    • Use the -Command parameter instead, which interprets the argument(s) that follow(s) it as PowerShell code, in the context of which array arguments are supported, as they are in-session:

    C:\fullPathToPowershell.exe -Command "C:\fullPathToSnoozeGuard.ps1 -requiresSystem 'arg1', 'arg2', 'arg3'"
    

    Additional information:

    • With respect to passing array arguments, specifically, this answer provides background information.

    • For general, comprehensive guidance on when to use -File vs. -Command, see this answer.


    [1] The same applies to pwsh, the PowerShell (Core) 7 CLI.
    However, note that these two CLIs differ with respect to whether -File or -Command is the default parameter in the absence of either: powershell.exe defaults to -Command, whereas pwsh \ pwsh.exe defaults to -File.