Powershell 中模块函数的参数

Parameters to a function of a module in Powershell

在尝试用它创建一个函数之前,我能够执行这个命令..

$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 : Cannot validate argument on parameter 'ArgumentList'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. At c:\path\to\module\myModule.psm1:39 char:38 + saps -FilePath $cmd -ArgumentList <<<< $args -WindowStyle Hidden -Wait + CategoryInfo : InvalidData: (:) [Start-Process], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartProcessCommand

我试过多种方法调用这个函数..

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

您必须将参数作为字符串数组传递给 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'

更新:

is there a way to pass the exe file to the function as well? I'll eventually have multiple exe files coming into the function that logs the command and then executes it.

当然可以:

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'