我正在尝试编写一个带有3个参数的powershell函数
Function CopyVHD ($filename, $sourcevhd, $destination)
{
echo "filename is $filename"
echo "source is $sourcevhd"
echo "destination is $destination"
# Validate that the VHD doesn't exist on remote
if ( Test-Path "$sourcevhd\$filename" )
{
echo "File $filename already exists at $destination"
}
else
{
echo "copying $sourcevhd\\$filename to $destination"
Copy-Item $sourcevhd\$filename "$destination" -Recurse
}
}
然后传入3个参数
CopyVHD("foo.vhd","c:\","d:\")
为什么powershell将3个参数合并为1?如果您在下面的输出中注意到,变量filename
已消耗所有3个参数,而参数source
和destination
为空。
PS C:\Windows\system32> C:\Users\example\Documents\closed-pile.ps1
newest vhd is foo.vhd
filename is foo.vhd C:\ D:\
source is
destination is
copying \\foo.vhd C:\ D:\ to
Copy-Item : Cannot find drive. A drive with the name '\foo.vhd C' does not exist.
At C:\Users\example\Documents\closed-pile.ps1:28 char:7
+ Copy-Item $sourcevhd\$filename "$destination" -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\foo.vhd C:String) [Copy-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
我尝试过不同的变量名,因为我错误地使用了保留字。 我尝试过不同的空间语法。
CopyVHD ("foo.vhd","c:\","d:\")
CopyVHD("foo.vhd","c:\","d:\")
CopyVHD("foo.vhd", "c:\", "d:\")
CopyVHD( "foo.vhd", "c:\", "d:\" )
我在同一个脚本中有另一个函数,可以正确接受2个参数。为什么这个功能不起作用?
更新
我尝试了以下语法,该链接的SO问题中显示了该语法。它给出了同样的失败
CopyVHD "foo.vhd", "C:\", "D:\"
UPDATE2
也尝试用单引号
CopyVHD 'foo.vhd', 'C:\', 'D:\'
功能仍然无法识别3个参数
PS C:\Windows\system32> C:\Users\sowen\Documents\closed-pile.ps1
filename is foo.vhd C:\ D:\
source is
destination is
答案 0 :(得分:5)
您不必使用逗号分隔PowerShell中的参数,逗号用于显示一个参数的多个条目。
您应该调用此函数的方法是使用空格分隔参数。或者更好的是,提供参数名称。
CopyVHD A B C
或强>
CopyVHD -filename A -sourcevhd B -destination C
>filename is a
source is b
destination is c