From 776cb72c143a46b755c706d23896e34dc7647af7 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:08:13 -0500 Subject: [PATCH 1/4] Read a job's CancelToken case-insensitively, and refuse keys that differ only in case A case-sensitive [hashtable]::new() job with 'canceltoken' got the kit's own token in its place, since the check used the job's own comparer and the worker's copy is case-insensitive. Two keys differing only in case collapsed into one, the later silently winning; such a job is now refused, up front for -JobParams and as it arrives for -NextJobProvider. --- ParallelKit.Harness.ps1 | 36 ++++++++++++++++++++++++++++++++++++ ParallelKit.ps1 | 34 +++++++++++++++++++++++++++++++--- 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 615f905..03f52bd 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5324,6 +5324,42 @@ $bcJob = [hashtable]::new(); $bcJob['name'] = 'a' $bcOut = $null; $bcError = $null try { $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(,$bcJob) -WorkerScript { param([Parameter(Mandatory)][string]$Name) $Name } } catch { $bcError = [string]$_ } Test-Assert ($null -eq $bcError -and $null -ne $bcOut -and $bcOut.Errors.Count -eq 0) ("a mandatory parameter supplied in another case, in a case-sensitive hashtable, isn't counted as missing (" + $bcError + ")") +# A case-sensitive job's own 'canceltoken' is its CancelToken, as binding +# would have it: the kit doesn't put its own in its place. The caller's token +# here is cancelled, so the worker can tell which one it got. +$bcMine = [System.Threading.CancellationTokenSource]::new(); $bcMine.Cancel() +$bcTokenWorker = { param($Id, $CancelToken) $CancelToken.IsCancellationRequested } +$bcJob = [hashtable]::new(); $bcJob['canceltoken'] = $bcMine.Token; $bcJob['Id'] = 1 +$bcSeen = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(,$bcJob) -WorkerScript $bcTokenWorker -ResultHandler { param($r) $bcSeen.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +Test-Assert ($null -eq $bcError -and $bcSeen.Count -eq 1 -and $bcSeen[0] -eq $true) ("-JobParams: a case-sensitive job's 'canceltoken' reaches the worker, not the kit's token (got the caller's: " + ($bcSeen -join ',') + "; " + $bcError + ")") +$bcGiven = @{ N = 0 } +$bcSeen = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -WorkerScript $bcTokenWorker -ResultHandler { param($r) $bcSeen.Add($r) }.GetNewClosure() -NextJobProvider { + if ($bcGiven.N -ge 1) { return $null } + $bcGiven.N++; $j = [hashtable]::new(); $j['canceltoken'] = $bcMine.Token; $j['Id'] = 2; return $j + }.GetNewClosure() +} catch { $bcError = [string]$_ } +Test-Assert ($null -eq $bcError -and $bcSeen.Count -eq 1 -and $bcSeen[0] -eq $true) ("-NextJobProvider: the same (got the caller's: " + ($bcSeen -join ',') + "; " + $bcError + ")") +$bcMine.Dispose() +# Two keys differing only in case would collapse into one in the worker, the +# later silently winning: refused, naming both. +$bcJob = [hashtable]::new(); $bcJob['Id'] = 1; $bcJob['id'] = 2 +$bcRan = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 0 }, $bcJob) -WorkerScript { param($Id) $Id } -ResultHandler { param($r) $bcRan.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +Test-Assert ($bcError -match "job 1 supplies '(Id|id)' and '(Id|id)', which differ only in case" -and $bcError -match 'Nothing was started' -and $bcRan.Count -eq 0) ("-JobParams: a case-sensitive job with 'Id' and 'id' is refused before anything starts (" + $bcError + "; ran " + $bcRan.Count + ")") +$bcGiven = @{ N = 0 } +$bcRan = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -WorkerScript { param($Id) $Id } -ResultHandler { param($r) $bcRan.Add($r) }.GetNewClosure() -NextJobProvider { + $bcGiven.N++ + if ($bcGiven.N -eq 1) { return @{ Id = 0 } } + if ($bcGiven.N -eq 2) { $j = [hashtable]::new(); $j['Id'] = 1; $j['id'] = 2; return $j } + return $null + }.GetNewClosure() +} catch { $bcError = [string]$_ } +Test-Assert ($bcError -match "a job from -NextJobProvider supplies '(Id|id)' and '(Id|id)', which differ only in case" -and ($bcRan -join ',') -eq '0') ("-NextJobProvider: the same, refused as it arrives (" + $bcError + "; ran " + ($bcRan -join ',') + ")") # Not refused: a mandatory CancelToken (the kit supplies it), Mandatory = # $false, and parameter sets (which parameters are needed depends on the set). $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }) -WorkerScript { param([Parameter(Mandatory)][System.Threading.CancellationToken]$CancelToken, [Parameter(Mandatory = $false)]$Opt, $Id) $Id } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 5c3a890..8d0ca2d 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3864,6 +3864,10 @@ function Invoke-PkRunspaceBatch { # A fixed list can be checked before a single worker starts. if ($null -ne $JobParams) { for ($jobIndex = 0; $jobIndex -lt $JobParams.Count; $jobIndex++) { + $caseKeys = Get-PkCaseDuplicateJobKey -Job $JobParams[$jobIndex] + if ($null -ne $caseKeys) { + throw ("Invoke-PkRunspaceBatch: job " + $jobIndex + " supplies " + $caseKeys + ", which differ only in case. Parameter names don't, so the worker would get only one of them. Keep one. Nothing was started.") + } foreach ($key in $JobParams[$jobIndex].Keys) { if (-not $declaredParams.Contains([string]$key)) { throw ("Invoke-PkRunspaceBatch: job " + $jobIndex + " supplies '" + $key + "', but -WorkerScript's param() block doesn't declare it. Nothing was started.") @@ -4002,13 +4006,22 @@ function Invoke-PkRunspaceBatch { if ($null -ne $sbKey) { throw (Get-PkScriptBlockJobMessage -Job "a job from -NextJobProvider" -Key $sbKey) } } - $ps = [PowerShell]::Create() - $ps.RunspacePool = $pool $jobValues = @{} foreach ($key in $nextJob.Keys) { $jobValues[$key] = $nextJob[$key] } - if ($declaredParams.Contains('CancelToken') -and -not $nextJob.ContainsKey('CancelToken')) { + # $jobValues is case-insensitive, like binding: fewer keys than + # the job means a case-sensitive [hashtable]::new() job had two + # differing only in case (a -JobParams job's were refused before + # the run). + if ($jobValues.Count -ne $nextJob.Count) { + throw ("Invoke-PkRunspaceBatch: a job from -NextJobProvider supplies " + (Get-PkCaseDuplicateJobKey -Job $nextJob) + ", which differ only in case. Parameter names don't, so the worker would get only one of them. Keep one.") + } + # And read here, not on the job, so a case-sensitive job's + # 'canceltoken' counts as its own. + if ($declaredParams.Contains('CancelToken') -and -not $jobValues.ContainsKey('CancelToken')) { $jobValues['CancelToken'] = $Cts.Token } + $ps = [PowerShell]::Create() + $ps.RunspacePool = $pool $jobLocation = "" if ([System.IO.Directory]::Exists($workerLocation)) { $jobLocation = $workerLocation } # A local scope too, so variables a job sets (preference @@ -4194,6 +4207,21 @@ function Get-PkCommandKind { return 'UnloadableModuleFunction' } +function Get-PkCaseDuplicateJobKey { + # Two keys of a job hashtable that differ only in case, as "'Id' and + # 'id'", else $null. Only a case-sensitive [hashtable]::new() can hold + # them; the worker's copy is case-insensitive, like parameter binding, so + # they'd collapse into one, the later silently winning. + param([Parameter(Mandatory)][hashtable]$Job) + $seen = @{} + foreach ($key in $Job.Keys) { + $name = [string]$key + if ($seen.ContainsKey($name)) { return ("'" + $seen[$name] + "' and '" + $name + "'") } + $seen[$name] = $name + } + return $null +} + function Get-PkScriptBlockJobKey { # The first key of a job hashtable whose value is a scriptblock, or holds # one up to three levels down (in arrays, lists, dictionaries and From 2b95bef3eb717ae0a4573314765578bedfc6b65d Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:23:53 -0500 Subject: [PATCH 2/4] Keep a surrogate pair at the cap's head/tail split when the output fits When -MaxOutputChars' head would end on the first half of a surrogate pair, it turned that half away but the tail kept its own size, so output exactly as long as the cap lost the pair. The tail now takes the slot the head turns away. --- ParallelKit.Harness.ps1 | 18 ++++++++++++++---- ParallelKit.ps1 | 12 ++++++++---- Source/PkChildProcessJob.cs | 12 ++++++++---- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 03f52bd..ba32ec3 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5542,17 +5542,27 @@ $beR = Get-HarnessCapRun -Arguments '/d /c 1>&2 echo 0123456789ABCDEFGHIJ' -Cap Test-Assert ($beR.Stderr -ceq "01234HIJ`r`n" -and $beR.StderrDroppedChars -eq 12 -and $beR.StdoutDroppedChars -eq 0) ("stderr is capped the same way, on its own ('" + ([string]$beR.Stderr -replace "`r", '\r' -replace "`n", '\n') + "', dropped " + $beR.StderrDroppedChars + ")") # A cut never splits a surrogate pair. cmd /u writes UTF-16: four emoji are -# 8 characters, plus CRLF. A cap of 6 puts the head's end and the tail's -# start inside pairs. +# 8 characters, plus CRLF. A cap of 7 puts the head's end inside a pair (its +# first half, and the slot, go to the tail) and the tail's start inside +# another. $beEmoji = [char]::ConvertFromUtf32(0x1F600) -$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ' + $beEmoji * 4) -Cap 6 -Encoding 'unicode' +$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ' + $beEmoji * 4) -Cap 7 -Encoding 'unicode' $beText = [string]$beR.Stdout $beLone = 0 for ($i = 0; $i -lt $beText.Length; $i++) { if ([char]::IsHighSurrogate($beText[$i])) { if ($i + 1 -lt $beText.Length -and [char]::IsLowSurrogate($beText[$i + 1])) { $i++ } else { $beLone++ } } elseif ([char]::IsLowSurrogate($beText[$i])) { $beLone++ } } -Test-Assert ($beText -ceq ($beEmoji + "`r`n") -and $beLone -eq 0 -and $beR.StdoutDroppedChars -eq 6) ("a cut inside a surrogate pair drops the whole pair, never half (" + $beText.Length + " characters kept, " + $beLone + " half pairs, dropped " + $beR.StdoutDroppedChars + ")") +Test-Assert ($beText -ceq ($beEmoji * 2 + "`r`n") -and $beLone -eq 0 -and $beR.StdoutDroppedChars -eq 4) ("a cut inside a surrogate pair drops the whole pair, never half (" + $beText.Length + " characters kept, " + $beLone + " half pairs, dropped " + $beR.StdoutDroppedChars + ")") +# Output exactly as long as the cap is kept whole, even with a pair where the +# head would end: the tail takes the slot the head turns away. +$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ab' + $beEmoji + 'c') -Cap 7 -Encoding 'unicode' +Test-Assert ($beR.Stdout -ceq ('ab' + $beEmoji + "c`r`n") -and $beR.StdoutDroppedChars -eq 0) ("output exactly at the cap, with a surrogate pair at the head's end, comes back whole (" + ((Format-HarnessCapRun $beR) -replace [regex]::Escape($beEmoji), '') + ")") +$beText = foreach ($beCase in @(@{ Text = $beEmoji; Cap = 2 }, @{ Text = 'a' + $beEmoji + 'b'; Cap = 4 }, @{ Text = 'ab' + $beEmoji + 'cd'; Cap = 6 })) { + $beTask = [PkStreamReadTask]::Run([System.IO.StringReader]::new($beCase.Text), $beCase.Cap) + if ($beTask.Result -cne $beCase.Text -or $beTask.DroppedChars -ne 0) { ($beCase.Text -replace [regex]::Escape($beEmoji), '') + ' cap ' + $beCase.Cap + ": kept '" + ($beTask.Result -replace [regex]::Escape($beEmoji), '') + "', dropped " + $beTask.DroppedChars } +} +Test-Assert ($null -eq $beText) ("the same for an emoji under a cap of 2, ab under 4 and abcd under 6" + $(if ($beText) { " (" + ($beText -join '; ') + ")" })) # Long output: what's held stays within the cap while the program writes, # and the count adds up to the whole. diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 8d0ca2d..2d60eba 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -292,8 +292,11 @@ public sealed class PkStreamReadTask : Task public volatile bool ReaderClosed; // The cap's tail: the last chars read, a ring once it's full. It // grows with the output, so a cap costs nothing until output reaches - // it. _tailCap is 0 with no cap. - private readonly int _headCap, _tailCap; + // it. _tailCap is 0 with no cap. A head that turns away a pair's + // first half gives the tail its slot, before the tail is allocated, + // so output that fits the cap is kept whole. + private readonly int _headCap; + private int _tailCap; private bool _headFull; private char[] _tail; private int _tailStart, _tailCount; @@ -334,8 +337,9 @@ public sealed class PkStreamReadTask : Task if (take == _headCap - _text.Length) { _headFull = true; - // The head never ends on the first half of a surrogate pair. - if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; } + // The head never ends on the first half of a surrogate + // pair: that half goes to the tail, and its slot too. + if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; _tailCap++; } } _text.Append(chunk, 0, take); i = take; diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 9020fbd..ee54788 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -50,8 +50,11 @@ private sealed class Buffer public volatile bool ReaderClosed; // The cap's tail: the last chars read, a ring once it's full. It // grows with the output, so a cap costs nothing until output reaches - // it. _tailCap is 0 with no cap. - private readonly int _headCap, _tailCap; + // it. _tailCap is 0 with no cap. A head that turns away a pair's + // first half gives the tail its slot, before the tail is allocated, + // so output that fits the cap is kept whole. + private readonly int _headCap; + private int _tailCap; private bool _headFull; private char[] _tail; private int _tailStart, _tailCount; @@ -92,8 +95,9 @@ private void Append(char[] chunk, int n) if (take == _headCap - _text.Length) { _headFull = true; - // The head never ends on the first half of a surrogate pair. - if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; } + // The head never ends on the first half of a surrogate + // pair: that half goes to the tail, and its slot too. + if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; _tailCap++; } } _text.Append(chunk, 0, take); i = take; From e8a5c9850a79739544f7f6654b7fc51cb85c53ee Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:39:13 -0500 Subject: [PATCH 3/4] Check for an abort before each group the dispatcher fetches The group-fetch loop tested only the token, which is cancelled after it, so an abort raised by -GroupProvider, -JobBuilder, -GroupCompleteCallback or -GroupReleaseCheck still asked -GroupProvider for more groups and built them, up to -MaxQueueAhead, or every group when they had no jobs. --- ParallelKit.Harness.ps1 | 29 +++++++++++++++++++++++++++++ ParallelKit.ps1 | 5 ++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index ba32ec3..d8dc00d 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1040,6 +1040,35 @@ $d = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 1 -AbortTimeoutSec -JobBuilder { param($g) if ($late.Aborting) { $late.LateBuilds++ }; return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() ` -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; if (-not $late.Aborting) { $late.Aborting = $true; Request-PkAbort } }.GetNewClosure() Test-Assert ($d.Aborted -and $late.Groups -eq 1 -and $late.LateBuilds -eq 0) ("dispatch: a -JobFinalize that requests an abort gets no more groups from -GroupProvider (asked for " + $late.Groups + " group(s), " + $late.LateBuilds + " built after the abort)") +# The same for an abort from the callbacks that run while groups are fetched, +# with room to queue 3 groups ahead: -GroupProvider isn't asked again, and no +# group asked for after the abort is built. -GroupCompleteCallback and +# -GroupReleaseCheck run there for groups with no jobs. +foreach ($fetchCase in 'GroupProvider', 'JobBuilder', 'GroupCompleteCallback', 'GroupReleaseCheck') { + Reset-Harness + $fetch = @{ Asked = 0; AbortedAt = -1; AskedAfter = 0; LateBuilds = 0; Case = $fetchCase } + $fetchAbort = { if ($fetch.AbortedAt -lt 0) { $fetch.AbortedAt = $fetch.Asked; Request-PkAbort } }.GetNewClosure() + $fetchParams = @{ + MaxConcurrent = 1; MaxQueueAhead = 3; AbortTimeoutSeconds = 5 + GroupProvider = { + if ($fetch.Asked -ge 10) { return $null } + $fetch.Asked++ + if ($fetch.AbortedAt -ge 0) { $fetch.AskedAfter++ } + if ($fetch.Case -eq 'GroupProvider') { & $fetchAbort } + return $fetch.Asked + }.GetNewClosure() + JobBuilder = { + param($g) + if ($fetch.AbortedAt -ge 0 -and $g -gt $fetch.AbortedAt) { $fetch.LateBuilds++ } + if ($fetch.Case -eq 'JobBuilder') { & $fetchAbort; return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) } + }.GetNewClosure() + JobFinalize = { param($job, $pending) $null = Complete-PkProcess -Job $job } + } + if ($fetchCase -eq 'GroupCompleteCallback') { $fetchParams.GroupCompleteCallback = { param($g) & $fetchAbort }.GetNewClosure() } + if ($fetchCase -eq 'GroupReleaseCheck') { $fetchParams.GroupReleaseCheck = { param($g) & $fetchAbort; return $true }.GetNewClosure() } + $d = Invoke-PkProcessDispatch @fetchParams + Test-Assert ($d.Aborted -and $fetch.AbortedAt -ge 1 -and $fetch.AskedAfter -eq 0 -and $fetch.LateBuilds -eq 0) ("dispatch: a -" + $fetchCase + " that requests an abort while groups are fetched gets no more groups (asked " + $fetch.AskedAfter + " more time(s) after the abort, " + $fetch.LateBuilds + " built)") +} # Your own long step inside Invoke-PkRun has to poll. Reset-Harness diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 2d60eba..1bc41e6 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -2868,7 +2868,10 @@ function Invoke-PkProcessDispatchCore { } } - while ((-not $pkProviderExhausted) -and $pkActiveGroupCount -lt $pkMaxQueueAhead -and (-not $pkCancelToken.IsCancellationRequested)) { + # The abort flag per group too, so an abort raised by -GroupProvider, + # -JobBuilder, -GroupReleaseCheck or -GroupCompleteCallback asks for + # no more groups on this pass. + while ((-not $pkProviderExhausted) -and $pkActiveGroupCount -lt $pkMaxQueueAhead -and (-not $pkCancelToken.IsCancellationRequested) -and (-not [PkConsoleCtrl]::AbortRequested)) { # Invoke-PkCallback inlined, to count the values the provider # output. Collected by plain assignment, `return ,@('a', 'b')` (one # value, a list) and two values output separately are the same From a27848996cfec4771cf77e13858ba30843d1005b Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:55:25 -0500 Subject: [PATCH 4/4] Docs: say what cmd.exe's delayed expansion does to a quoted argument --- ParallelKit.ps1 | 6 ++++-- README.md | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 1bc41e6..da3d002 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1539,8 +1539,10 @@ function ConvertTo-PkArgumentString { # batch-file program they also write a quote as "" instead of \", which # cmd.exe can't be tricked by. This function's own output uses \": for # those, give the kit the list instead. Not covered for those programs - # either way: cmd expands %NAME% inside quotes, and splits batch arguments - # at = (left unquoted, since some programs read NAME=value themselves). + # either way: cmd expands %NAME% inside quotes (and, with delayed expansion + # on, !NAME!, dropping a ^ from an argument that holds a !), and splits + # batch arguments at = (left unquoted, since some programs read NAME=value + # themselves). # .PARAMETER Arguments # The arguments, in order. A $null one is left out; an empty string is passed # as "". A file or folder object (from Get-ChildItem or Get-Item) is its full diff --git a/README.md b/README.md index 03e687f..9454045 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,7 @@ Each command is a hashtable with `FilePath`, `Arguments` and optionally `Working - The program gets exactly that list back, spaces, quotes and trailing backslashes included. Don't pre-quote elements: a quote inside one is passed on as a quote character. - `$null` elements are left out, a file or folder object from `Get-ChildItem` or `Get-Item` is its full path, and an element that's itself a list is an error. - The quoting follows the rules most Windows programs use. `cmd.exe` itself (`FilePath = 'cmd.exe'`, `Arguments = @('/d', '/c', 'tool.exe', $file)`) gets the batch-file quoting described next, and the program after `/c` gets the rest of the list as given, with the same exception as for `%*` there (a `"` in an element, and a program built against `msvcrt.dll`). `cmd.exe` strips the quotes from a program path with spaces, though, so for one of those give it one string: `'/d /s /c ""C:\My Tools\tool.exe" "a b""'`. -- A `.bat` or `.cmd` program runs through `cmd.exe`, and the list is quoted for it: an element holding `&`, `|`, `<`, `>`, `^`, `(`, `)`, `,`, `;` or `"` reaches it as one argument and can't make `cmd.exe` run anything else. A `"` is written `""` for it, so the batch file itself sees the quote doubled in `%1` or `%~1`. A program it passes `%*` on to gets the list back as given if it was built with Microsoft's C runtime from 2008 on, as most are. One built against the older `msvcrt.dll`, as most MinGW builds are, reads a `"` in an element differently and can split it or run it into the next; elements without a `"` are fine. An element with a line break is an error. What quoting can't stop: `cmd.exe` expands `%NAME%` when a variable by that name exists, and splits batch arguments at `=` (left unquoted, since some programs read `NAME=value` themselves). The batch file can also undo the quoting: `%~1` strips the quotes, so a line like `echo %~1` runs the `& echo INJECTED` in an element `a & echo INJECTED`. Keep it quoted in the batch file (`"%~1"`), or use `%1`. +- A `.bat` or `.cmd` program runs through `cmd.exe`, and the list is quoted for it: an element holding `&`, `|`, `<`, `>`, `^`, `(`, `)`, `,`, `;` or `"` reaches it as one argument and can't make `cmd.exe` run anything else. A `"` is written `""` for it, so the batch file itself sees the quote doubled in `%1` or `%~1`. A program it passes `%*` on to gets the list back as given if it was built with Microsoft's C runtime from 2008 on, as most are. One built against the older `msvcrt.dll`, as most MinGW builds are, reads a `"` in an element differently and can split it or run it into the next; elements without a `"` are fine. An element with a line break is an error. What quoting can't stop: `cmd.exe` expands `%NAME%` when a variable by that name exists, and splits batch arguments at `=` (left unquoted, since some programs read `NAME=value` themselves). With delayed expansion on (`cmd /v:on`, `setlocal EnableDelayedExpansion` in the batch file, or the registry setting `cmd /?` describes), `!NAME!` is expanded inside quotes too, and a `^` in an element that holds a `!` is dropped. In a batch file, an unset `!NAME!` or a lone `!` is dropped as well. The batch file can also undo the quoting: `%~1` strips the quotes, so a line like `echo %~1` runs the `& echo INJECTED` in an element `a & echo INJECTED`. Keep it quoted in the batch file (`"%~1"`), or use `%1`. Only the list form gets this quoting. A string, including one built with `ConvertTo-PkArgumentString`, is passed as written.