【问题标题】:Parameters to a function of a module in PowershellPowershell中模块功能的参数
【发布时间】:2015-12-04 14:20:25
【问题描述】:

我能够在尝试使用它之前执行此命令..

$unzip ="c:\path\To\myZip.zip"
$dst = "c:\destination"
saps "c:\Program Files\winzip\wzunzip.exe" "-d $unzip $dst" -WindowStyle Hidden -Wait

然后我在一个模块中创建了这个函数,我试图将参数传递给..

function RunCmd ($cmd){
    write-host "cmd: $cmd" 
    saps $cmd -WindowStyle Hidden -Wait 
}

我已验证模块已正确导入,但是当我尝试将参数传递给函数时,我收到错误,指出无法读取参数。

我尝试了多种方法来传递参数,但没有任何效果。

例子

$cmd = @{'FilePath'= '$unzip';
     'ArgumentList'= '-d $unzip dst';}
RunCmd  @cmd


RunCmd """$unzip"" ""-d $unzip $dst"""

我注意到命令和参数将通过双引号传递给函数执行第二种选择,但那是我得到参数空异常的时候。

我也尝试过更改函数以分别传递命令和参数,但没有成功..

function RunCmd ($cmd, $args){
    write-host "cmd: $cmd" 
    saps $cmd $args -WindowStyle Hidden -Wait 
}

有什么想法吗?

更新:

这是我的新功能..

function RunCmd ($log, $cmd, $args){
    Log-Cmd $log
    saps -FilePath $cmd -ArgumentList $args -WindowStyle Hidden -Wait 
}

也试过了..

> function RunCmd ($log, $cmd, [string[]]$args){
>     Log-Cmd $log
>     saps -FilePath $cmd -ArgumentList $args -WindowStyle Hidden -Wait  }

但是当函数尝试执行时,我收到一个错误,指出参数为空。

Start-Process:无法验证参数“ArgumentList”上的参数。 参数为 null、空或参数集合的元素 包含一个空值。提供一个不包含任何 null 值,然后再次尝试该命令。在 c:\path\to\module\myModule.psm1:39 char:38 + saps -FilePath $cmd -ArgumentList

我尝试了多种方法来调用这个函数..

RunCmd -log $log -cmd $unzip -args '-d', '$unzip', '$dst'
RunCmd $log $unzip '-d', '$unzip', '$dst'
RunCmd $log $unzip "-d", "$unzip", "$dst"

【问题讨论】:

  • 显示来自各种尝试的准确调用和准确错误。

标签: powershell powershell-2.0


【解决方案1】:

您必须将参数作为字符串数组传递给Start-Process cmdlet。这是一个非常基本的例子:

function Unzip-File ($ZipFile, $Destination)
{
    $wzunzip = 'c:\Program Files\winzip\wzunzip.exe'
    Start-Process -WindowStyle Hidden -Wait -FilePath $wzunzip -ArgumentList (
        '-d',
        $ZipFile,
        $Destination
    ) 
}

Unzip-File 'c:\path\To\myZip.zip' 'c:\destination'

更新:

有没有办法将 exe 文件也传递给函数?生病 最终有多个 exe 文件进入记录的功能 命令,然后执行它。

当然:

function Start-ProcAndLog ($ExeFile, $CmdLine)
{
    Start-Process -WindowStyle Hidden -Wait -FilePath $ExeFile -ArgumentList $CmdLine
}

# Note commas in second parameter: '-arg1', '-arg2', '-arg3' is an array
Start-ProcAndLog 'c:\path\to\file.exe' '-arg1', '-arg2', '-arg3'

【讨论】:

  • 有没有办法将 exe 文件也传递给函数?我最终会有多个 exe 文件进入记录命令然后执行它的函数。
  • 请查看更新。似乎传递的数组列表作为 null 传递给函数。我什至尝试制作参数数组,然后将其传递给这样的函数.. $args = @('-d', $unzip, $dst) 没有成功
  • @marc117 您在函数中使用了$args 变量。 $argsAutomatic variable 并且仅当函数没有声明参数时才存在。这就是为什么在你的情况下它是null。只需使用任何其他非保留名称作为参数。
  • 做到了!谢谢beatcracker
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
相关资源
最近更新 更多