powershellcmdmax

Powershell to avoid cmd 8191 character limit


I'm creating a PowerShell that runs a simple Java program using:

Start-Process -filepath .\java.exe -ArgumentList "Input" -NoNewWindow

The Input class in this case simply accepts and prints a string.

I'm expecting strings with length greater than the cmd.exe 8191 char limit, so I need to run it in PS.

Current scenario:

I tried adding -Wait as well, but not luck.

Any idea?


Solution

  • As you state, the max. length of an interactive command line in cmd.exe (at the interactive Command Prompt, but not in batch files) is officially 8,191 characters - see the documentation. If you try to submit a command line via the Run dialog (WinKey-R), the limit appears to be even lower.

    However, this does not apply to command lines in PowerShell, - neither at the interactive prompt nor in .ps1 files - where the limit is much higher - 32,766 characters.[1]

    In other words: commands launched from within PowerShell are not subject to the 8,191-character limit (unless they themselves impose their own limit, which a call to cmd.exe /c does, for instance) - irrespective of whether you use Start-Process or Invoke-Expression (neither of which you should use for invoking console applications / scripts - see this answer and this answer) or by direct invocation (by file path, possibly preceded by &, the call operator - e.g., .\javaRun.ps1 or & .\javaRun.ps1) - none of these methods involve cmd.exe

    As for calling external programs from PowerShell:


    [1] I don't have an official reference, but you can verify the limit experimentally as follows: C:\Windows\system32\choice.exe /d y /t 0 /m ('x' * (32766-46)) 2>$null. -46 subtracts the length of the static prefix of the command (note that PowerShell encloses the executable in "..." behind the scenes), and creates as many x chars. as needed to amount to an overall command-line length of line is 32,766. The call succeeds (in the sense that it is successfully submitted and choice.exe is actually invoked, irrespective of whether it then reports an error or not), and produces no output (there's incidental stderr output, which 2>$null discards). If you increase the length by only 1 character (change -46 to -45), the invocation breaks fundamentally with "Program 'choice.exe' failed to run: The filename or extension is too long".
    Presumably, the limit is ultimately imposed by the CreateProcess WinAPI function, whose docs state: "The maximum length of this string is 32,767 characters, including the Unicode terminating null character".