我试图创建一个脚本来转换放在处理脚本上的 Markdown 文件。
为此,我创建了一个 (process.bat
(,它将删除的文件的名称传递给 PowerShell 脚本:
powershell.exe -NoProfile -File "./process.ps1" -Document %*
@pause
PowerShell文件(process.ps1
(将单独处理每个文件:
[parameter(Mandatory=$true)]
[String[]]$Document
Write-Host $args[1]
$Document | ForEach-Object {
Write-Host "Document: $_"
# convert Markdown to Html
pandoc -o ($_ -Replace '.md', '.html') -f markdown -t html $_
}
当我在批处理文件上放置两个文件时:
C:UsersXXXDocumentsWindowsPowerShellScriptsMarkdown>powershell.exe -NoProfile -File "./process.ps1" -Document "C:UsersXXXDocumentsWindowsPowerShellScriptsMarkdownFOO.md"
"C:UsersXXXDocumentsWindowsPowerShellScriptsMarkdownBAR.md"
C:UsersXXXDocumentsWindowsPowerShellScriptsMarkdownBAR.md
Document:
Press any key to continue . . .
文档未被处理。
将批处理文件的文件列表%*
传递到 PowerShell 的建议方法是什么?
当powershell.exe
使用-File
参数从外部调用 PowerShell CLI 时,它不支持数组- 仅支持单个参数。[1]
(此外,您忽略了将参数定义包装在param(...)
块中,这实际上导致它被忽略。
最简单的解决方案是使用ValueFromRemainingArguments
选项定义参数,以便它自动收集参数变量中的所有位置参数:
param(
[Parameter(Mandatory, ValueFromRemainingArguments)]
[String[]] $Document
)
然后通过PowerShell CLI调用脚本而不-Document
:
powershell.exe -NoProfile -File "./process.ps1" %*
作为使用帮助程序批处理文件的替代方法,您可以:
定义一个快捷方式文件(
*.lnk
(,该文件将 PowerShell 脚本显式调用为powershell.exe -File pathtoyourscript.ps1
(不带其他参数(然后将其用作放置目标。
注意: 不能直接使用 PowerShell 脚本 (*.ps1
(作为放置目标的原因是 PowerShell 脚本文件不能直接执行- 相反,打开(双击(*.ps1
文件会将其打开以进行编辑。
然后,您需要将pause
(或类似内容,例如Read-Host -Prompt 'Press Enter to exit.'
(添加到PowerShell脚本中,以防止它在完成后立即关闭窗口。
或者,将脚本保留原样并使用-NoExit
(放在-File
之前(使 PowerShell 会话保持打开状态。
[1] 这同样适用于PowerShellCoreCLI,pwsh
。