【问题标题】:Argumentlist failing to populate param in scriptblockArgumentlist 未能在脚本块中填充参数
【发布时间】:2018-02-14 16:33:20
【问题描述】:

 

这不是关于 Visual Studio 的帖子,因为我可以在 powershell 命令行上复制该问题

我正在尝试在 Visual Studio 2015 中启动一个 powershell 脚本作为构建后事件的一部分。为了完整起见,我的构建后事件代码是:

powershell -executionPolicy bypass -Command  “& {Invoke-command -scriptblock {Param($path); write-host $path} -ArgumentList '$(ProjectDir)'}"

 

然后这会被 VS 转换成一个批处理文件,如下所示:

powershell -executionPolicy bypass -Command  “& {Invoke-command -scriptblock {Param($path); write-host $path} -ArgumentList 'd:\somepath\somefile.msi'}"

 

 

它的目的是为了反驳这样一个事实,即开发人员在不同的驱动器上拥有数据,所以我不知道脚本最终会放在哪里。我将在路径字符串的开头使用卷信息,但现在,让它回显路径将是一个胜利..

 

如果我使用 Invoke-Command 并运行它,一切都会按预期工作:

PS D:\> Invoke-command -scriptblock {Param($path); write-host $path} -ArgumentList 'd:\somepath\somefile.msi'

d:\somepath\somefile.msi 

 

如果我将它包装到要传递给 powershell 的 –command 参数中,argumentlist 永远不会填充参数,并且我会在脚本块中得到一个空的 $path 字符串。

PS D:\ > powershell -Command “& {Invoke-command -scriptblock {Param($path); write-host $path} -ArgumentList 'd:\somepath\somefile.msi'}"

            

 

关于我哪里出错了有什么建议吗?

 

非常感谢

【问题讨论】:

    标签: powershell-3.0


    【解决方案1】:

    是否需要 Invoke-Command cmdlet?我相信该命令用于远程处理(在远程机器上执行命令)。

    查看 PowerShell.exe 语法,我看不到对 ArgumentList 参数的任何引用:

    PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
        [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
        [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
        [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
        [-ConfigurationName <string>]
        [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
        [-Command { - | <script-block> [-args <arg-array>]
                      | <string> [<CommandParameters>] } ]
    

    有一个 args 参数,但我无法让它工作。我实际上不确定它的目的是否是将参数值传递给 PowerShell 命令。我的做法是……

    1) 创建一个ps1文件:

    param (
        $Path
    )
    Write-Host $Path
    

    2) 使用以下批处理文件启动 ps1 脚本:

    powershell -file .\test.ps1 -path 'C:\Test'
    

    希望这是与您的场景兼容的解决方案。

    【讨论】:

    • 一个单独的脚本文件是我考虑过的一个选项,但这将是最后的手段,因为我不想在每个可能受到影响的项目中引入中间脚本。但是,我将回顾我对脚本块的 -Command 和关联的 -args 参数的使用。感谢您抽出宝贵时间回复。
    【解决方案2】:

    按照@Michaeljames 的建议查看了我的 -Command 用法后,很明显我可能混合了 2 种不同的方法。

    如下更正我的代码有预期的效果:

    PS H:\> powershell -Command {param([string]$path) write-host "$($path.substring(0,1)):\Scripts\somescript.ps1"} -Args 'd:\somepath\somefile.msi'
    
    D:\Scripts\somescript.ps1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-13
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多