Powershell - 如何将 import-csv 用于 SwitchParameter

标签 powershell

我有一个用 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 对象。因此,如果您使用 01,则需要将其转换为 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/

相关文章:

powershell - 如何使用 PowerShell 引用 .NET 程序集

powershell - 如何通过 Windows PowerShell 的组策略 cmdlet 获取/设置/更新注册表值?

azure - 无法安装 Az 模块

powershell - PowerShell 中的 Get-ChildItem 操作不当

powershell - 用于启动/停止虚拟机的 Azure Runbook 显示 "Completed"但没有任何反应

arrays - 如何使用powershell将字符串变量拆分为两个数组对象变量?

regex - Powershell替换丢失换行符

csv - 替换 powershell 输出中的 NULL 值

shell - 在 PowerShell 中添加数字

powershell - 在 powershell 中比较两个哈希表