我是PowerShell的新手,我有一项非常简单的任务:将三个函数参数输出为CSV字符串。我得到的是:
function ToCsv($v1, $v2, $v3) {
Write-Host $v1, $v2, $v3
Write-Host "$v1,$v2,$v3"
Write-Host $v1 + "," + $v2 + "," + $v3
}
ToCsv("One", "Two", "Three")
One Two Three
One Two Three,,
One Two Three + , + + , +
将一组函数参数输出为逗号分隔字符串的正确方法是什么?
我正在使用PowerShell 5.1
标记,
这需要一点努力,但不需要太大的努力。
Function ToCsv($v1, $v2, $v3) {
#Convert arguments to an Ordered Hash Table
$MyArgs = [Ordered]@{
Arg1 = "$v1"
Arg2 = "$v2"
Arg3 = "$v3"
}
#Convert the Hash table to a PS Custom Object.
$object = new-object psobject -Property $MyArgs
#Export the PS Custom Object as a CSV file.
Export-csv -InputObject $object -Path G:BEKDocsTest.csv -NoTypeInformation
}
ToCsv "One" "Two" "Three"
结果:(如NP++所示(
"Arg1","Arg2","Arg3"
"One","Two","Three"
HTH-
更新:
这里有一个更好的解决方案,可以处理任意数量的参数。
Function ToCsv {
$ArgCnt = $Args.Count
$object = new-object psobject
For ($Cntr = 0; $Cntr -lt $ArgCnt; $Cntr++) {
$AMArgs = @{InputObject = $object
MemberType = "NoteProperty"
Name = $("Arg" + $($Cntr + 1))
Value = "$($Args[$($Cntr)])"
}
Add-Member @AMArgs
}
Export-CSV -InputObject $object -Path G:BEKDocsTest.csv -NoTypeInformation
} #End Function ToCSV
ToCsv "One" "Two" "Three" "Four"
结果:(如NP++所示(
"Arg1","Arg2","Arg3","Arg4"
"One","Two","Three","Four"