【问题标题】:PowerShell how to present function parameters in the form of CSVPowerShell如何以CSV的形式呈现函数参数
【发布时间】:2021-07-04 09:10:35
【问题描述】:

我是 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

【问题讨论】:

    标签: powershell-5.1


    【解决方案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:\BEKDocs\Test.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:\BEKDocs\Test.csv -NoTypeInformation
    
    } #End Function ToCSV
    
    ToCsv "One" "Two" "Three" "Four"
    

    结果:(见于 NP++)

    "Arg1","Arg2","Arg3","Arg4"
    "One","Two","Three","Four"
    
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2016-04-20
      • 2021-11-13
      • 2019-06-14
      • 2020-07-13
      • 2021-06-17
      • 1970-01-01
      • 2021-09-18
      • 2013-10-06
      相关资源
      最近更新 更多