从Powershell调用一个带有非常长的可变参数列表的程序?

时间:2011-03-31 20:34:23

标签: powershell batch-file

我目前正在尝试将一系列批处理文件转换为powershell脚本。我想以递归方式为目录中存在的源文件运行编译器。编译器需要一长串参数。问题是,我希望参数是可变的,所以我可以根据需要更改它们。这是来自批处理文件的典型调用(为了可读性和长度而简化):

  

“C:\ PICC Compilers \ picc18.exe”--pass1   “C:\ Src Files \ somefile.c”   “-IC:\ Include Files”“ - IC:\ Header   文件“-P   --runtime =默认值,+清晰,+初始化,-keep,+下载+ stackwarn,-config,+ CLIB,-plib   --opt = default,+ asm,-speed,+ space,9 --warn = 0 --debugger = realice -Blarge --double = 24 --cp = 16 -g --asmlist“--errformat = Error [ %n]%f;%l。%c   %s“” - msgformat =咨询[%n]%s“ - OBJDIR =”C:\ Built Files“   “--warnformat =警告[%n]%f;%l。%c%s”

当包含在批处理文件中时,此命令执行正常,但是当我将命令复制并粘贴到PowerShell中时,我开始收到错误。这只是我第二天使用PowerShell,但我过去使用.NET开发。我设法凑合了以下尝试:

$srcFiles = Get-ChildItem . -Recurse -Include "*.c"
    $srcFiles | % {
    $argList = "--pass1 " + $_.FullName;
    $argList += "-IC:\Include Files -IC:\Header Files -P --runtime=default,+clear,+init,-keep,+download,+stackwarn,-config,+clib,-plib --opt=default,+asm,-speed,+space,9 --warn=0 --debugger=realice -Blarge --double=24 --cp=16 -g --asmlist '--errformat=Error   [%n] %f; %l.%c %s' '--msgformat=Advisory[%n] %s' '--warnformat=Warning [%n] %f; %l.%c %s"
    $argList += "--OBJDIR=" + $_.DirectoryName;
    &"C:\PICC Compilers\picc18.exe" $argList }

我知道上面的代码可能存在多个问题,即如何传递参数以及如何处理参数列表中的引号。这是不正确的,它应该说明我想要实现的目标。关于从哪里开始的任何建议?

2 个答案:

答案 0 :(得分:6)

从PowerShell调用命令行应用程序可能非常棘手。几个星期前,@ Jaykul写了一篇很棒的博客文章The problem with calling legacy/native apps from PowerShell,在那里他描述了人们在这种情况下会遇到的问题。当然也有解决方案;)

编辑 - 更正网址

该文章不再可用,因此只能通过web.archive.org查看 - 请参阅cached article

答案 1 :(得分:4)

使$arglist成为数组而不是字符串。单个字符串将始终作为单个参数传递,这是您 想要的。

相关问题