2012-07-10 61 views
0

以下是我拨打.\GetEMSInstallers的功能。对于一些不明原因的第一个参数总是失去了价值:PowerShell函数中的第一个参数会丢失它的值吗?

function Get-EMSInstallers { 

param (
    $ems_for_amx_source = '\\server\ems_path', 
    $installers_dir = 'D:\installers' 
) 

process { 

    if (!(Test-Path "$installers_dir\EMS4AMX")) { 
     "Copying files and folders from $ems_for_amx_source to $installers_dir\EMS4AMX" 
     copy $ems_for_amx_source "$installers_dir\EMS4AMX" -rec -force 
    } 
} 

} 
Get-EMSInstallers $args 

当我把它叫做我得到这样的输出:

Copying files and folders from to D:\installers\EMS4AMX 
Copy-Item : Cannot bind argument to parameter 'Path' because it is an empty array. 
At C:\Users\ad_ctjares\Desktop\Scripts\Ems\GetEMSInstallers.ps1:12 char:17 
+    copy <<<< $ems_for_amx_source "$installers_dir\EMS4AMX" -rec -force 
    + CategoryInfo   : InvalidData: (:) [Copy-Item], ParameterBindingValidationException 
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyArrayNotAllowed,Microsoft.PowerShell.Commands.CopyI 
    temCommand 

回答

1

当你没有任何参数传递给仍然得到-EMSInstallers您有一个$ args数组 - 它只是空的。所以$ ems_for_amx_source参数被设置为这个空数组。

换句话说,围绕这一方式:

if ($args) 
{ 
    Get-EMSInstallers $args 
} 
else 
{ 
    Get-EMSInstallers 
} 

有可能是一个更powershelly办法做到这一点 - 我可能会,如果想到后来修订本。 :-)但是,无论如何,这会让你开始。

+1

您可以使用[splatting](http://technet.microsoft.com/zh-cn/magazine/gg675931.aspx)将数组中的所有值传递给函数,而不是将该数组作为单个函数传递参数:'Get-EMSInstallers @ args'(或使用OP的另一个问题的答案和[在脚本上声明参数,而不是嵌套函数](http://stackoverflow.com/a/11423516/2495): )。 – 2012-08-19 13:26:27

+0

+1给皇帝的评论 - 谢谢填补我。 – azhrei 2012-08-20 00:15:41

相关问题