【问题标题】:Powershell functions copy-item error-exception with 2 parameters [duplicate]带有2个参数的Powershell函数复制项错误异常[重复]
【发布时间】:2021-11-16 10:08:00
【问题描述】:

这是我的问题;

$source = "\\Somewhere\Overtherainbow\something.exe"
$destinationSource = "C:\temp"


Function MyCopyFunction([string]$from, [string]$to)
{
   $src= $source+$from
   $dest = $destinationSource+$to
    
   Copy-Item -Path $src -Destination $dest -Recurse
}

Function MyFunction([string]$p1, [string]$p2)
{
    MyCopy($p1, $p2)
}

    switch("1"){
    "1" {
     MyFunction("Dir1","Dir2") break;
}
}

简单吧? 为什么当使用 2 个参数调用“MyCopyFunction(p1,p2)”时它抱怨第二个参数不存在。但是,如果我只使用 1 个参数而不是两个参数打开“MyCopyFunction($p1)”并手动提供 -Destination 值,那么问题的根源是什么?

这是一个例外.... Copy-Item -Path $from -Destination $to -Recurse CategoryInfo : ObjectNotFound: ( :String) [Copy-Item], ItemNotFoundExcptionFullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

【问题讨论】:

  • MyFunction "Dir1" "Dir2" 无括号
  • 我知道你可以调用带有或不带 () 的函数 MyFunction "para1","para2" 与 MyFunction("para1","para2") 相同,这不是真的吗?而且我已经尝试过有和没有()相同的结果
  • @Ahhzeee No....
  • 简而言之:PowerShell函数、cmdlet、脚本和外部程序必须像shell命令 - foo arg1 arg2 - 不像像C#方法-foo('arg1', 'arg2')。如果您使用, 分隔参数,您将构造一个命令将其视为单个参数数组。为防止意外使用方法语法,请使用Set-StrictMode -Version 2 或更高版本,但请注意其其他影响。请参阅this answer 了解更多信息。

标签: function powershell copy-item


【解决方案1】:

主要问题在这里,

MyCopyFunction(p1,p2)

当你像这样调用函数时,PowerShell treats the input as a single array containing two elements and pass it positionally to the first variable(In this case it's $from)。取而代之的是,您应该将调用站点更改为 MyCopyFunction "Dir1" "Dir2" 以使其正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 2016-05-04
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多