【发布时间】: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