You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写遍历.yaml文件执行命令并重命名输出的PowerShell脚本

PowerShell 实现脚本

直接可用的完整脚本如下:

# 命令模板,和你Python代码里的定义逻辑一致
$CommandTemplate = "toPDF main.tex xyz"

# 获取当前工作目录下所有后缀为.yaml的文件
$yamlFiles = Get-ChildItem -Filter *.yaml -File

# 遍历所有yaml文件执行操作
foreach ($file in $yamlFiles) {
    # 替换模板占位符为当前文件名
    $runCommand = $CommandTemplate.Replace("xyz", $file.Name)
    # 执行命令
    cmd /c $runCommand
    # 生成对应PDF文件名,重命名输出文件
    $pdfFileName = $file.Name.Replace(".yaml", ".pdf")
    Rename-Item -Path "main.pdf" -Destination $pdfFileName -Force
}
优化写法推荐

如果你的文件名可能包含空格,更建议直接调用命令而不是做字符串替换,避免解析错误:

$yamlFiles = Get-ChildItem -Filter *.yaml -File
foreach ($file in $yamlFiles) {
    & toPDF main.tex $file.Name
    # 仅修改文件后缀,避免文件名中包含.yaml字符串时误替换
    $pdfFileName = [System.IO.Path]::ChangeExtension($file.Name, ".pdf")
    Rename-Item -Path "main.pdf" -Destination $pdfFileName -Force
}
逻辑对应说明
  • Get-ChildItem -Filter *.yaml -File 等价于Python代码里的glob.glob("*.yaml"),-File参数保证只返回文件,排除同名目录
  • 字符串Replace方法的用法和Python完全一致
  • Rename-Item 等价于Python的os.rename,-Force参数表示如果目标PDF已存在会直接覆盖,不需要二次确认,不需要覆盖可以删除该参数

内容的提问来源于stack exchange,提问作者likethevegetable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:06:04