我是PowerShell的新手,当我尝试将参数传递给函数时,我发现了一个非常奇怪的行为:
代码
Param(
[Parameter(Mandatory=$true)][string]$vhdSourceDir,
[Parameter(Mandatory=$true)][string]$vhdDestinationDir,
[Parameter(Mandatory=$true)][array]$hypervisorList,
[int]$vhdKeep = 10
)
function getDirectoryBuildNumber ($dir) {
# Returns a number like 627c6ddeb8776914 from a path like:
# c:\BulidAgent\work\627c6ddeb8776914\packer\windows\box\hyperv\win2012r2std-cheflatest-001.box
return ( Get-ChildItem $dir | Where-Object {$_.Name -match "^[A-Za-z0-9]{16}$" } | Sort-Object LastAccessTime -Descending | Select-Object -First 1 )
}
function findBoxFile ($dir, $build) {
echo "looking for build $build at $dir "
echo "the dir is $dir and the build is $build"
# e.g c:\BulidAgent\work\627c6ddeb8776914\packer\windows\box\hyperv\win2012r2std-cheflatest-001.box
return ( Get-ChildItem $dir\$build\packer\windows\box\hyperv\ | Where-Object Extension -in '.box' | Sort-Object LastAccessTime -Descending | Select-Object -First 1 )
}
Function Main ()
{
$THEBUILD=getDirectoryBuildNumber($vhdSourceDir)
echo "THEBUILD is $THEBUILD"
findBoxFile($vhdSourceDir,$THEBUILD)
#echo "BOXFILE is $BOXFILE"
}
main
问题
以下是我用脚本调用的参数:
.\boxMove.ps1 -vhdSourceDir C:\BuildAgent\work -vhdDestinationDir e:\ -hypervisorList 'foobar'
这是它生成的输出
THEBUILD is 527c6ddeb8776914
looking for build at C:\BuildAgent\work 527c6ddeb8776914
the dir is C:\BuildAgent\work 527c6ddeb8776914 and the build is
Get-ChildItem : Cannot find path 'C:\BuildAgent\work 527c6ddeb8776914\packer\windows\box\hyperv\' because it does not exist.
参数显示无序。例如,“寻找构建应该如此显示”
looking for build 527c6ddeb8776914 at C:\BuildAgent\work
但它显示为
looking for build at C:\BuildAgent\work 527c6ddeb8776914
“dir is ..”一词也应该是
the dir is C:\BuildAgent\work and the build is 527c6ddeb8776914
但它的内容为
the dir is C:\BuildAgent\work 527c6ddeb8776914 and the build is
为什么powershell不按顺序打印字符串?
答案 0 :(得分:2)
当您将参数传递给函数时,请不要将它们封装在括号中并且传递多个参数的位置,它们应<逗>不以逗号分隔,而应使用空格来分隔它们。
例如:
findBoxFile($vhdSourceDir,$THEBUILD)
应为:
findBoxFile $vhdSourceDir $THEBUILD
然后你会发现这会消除你在错误排序的输出中遇到的问题。
答案 1 :(得分:0)
首先,清理你的功能定义。而不是
function (params){code}
你应该使用
function
{
Param ($Param1,$param2)
code
}
此外,当接受一个数组作为参数时,而不是使用[array],指定数组类型,(在你的情况下可能是字符串),这样就是(第4行)
[Parameter(Mandatory=$true)][string[]]$hypervisorList,
很难确切地说出脚本失败的原因,但我首先要清理明显的问题并重新测试。