我有一个用 C# 编写的自定义 cmdlet,它将 SwitchParameter
作为其参数之一,我想使用 import-csv 执行我的 cmdlet,我应该如何编写我的 csv 以便我能够传递正确的 SwitchParameter
值?
我在 CSV 中尝试了 True、False、0、1,带引号和不带引号,但它们似乎不起作用,我的代码总是出错
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName=true)]
public SwitchParameter Enable { get; set; }
我正在运行 Powershell 2.0 版,我要执行的命令是:
Import-Csv c:\data.csv | Add-MyData
最佳答案
当您使用 Import-CSV
时,所有属性都是 string
对象。因此,如果您使用 0
和 1
,则需要将其转换为 int
,并将其转换为 bool
。例如:
测试.csv
Name,Enabled
"Hey",1
"Lol",0
脚本:
Import-Csv .\test.csv | % { $_.Enabled = [bool]($_.Enabled -as [int]); $_ }
#You could also cast it with [bool]([int]$_.Enabled), I just like to mix it up :)
Name Enabled
---- -------
Hey True
Lol False
然后您可以将其传递给您的交换机,例如:
#My test-func
function testfunc ($Name, [switch]$Enabled) {
"$Name has switchvalue $Enabled"
}
Import-Csv .\test.csv | % {
$_.Enabled = [bool]($_.Enabled -as [int])
testfunc -Name $_.Name -Enabled:$_.Enabled
}
Hey has switchvalue True
Lol has switchvalue False
关于Powershell - 如何将 import-csv 用于 SwitchParameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16646855/