Nitin Chaudhari
Nitin Chaudhari

Reputation: 1507

Powershell - How to use import-csv for SwitchParameter

I have a custom cmdlet written in C# which takes SwitchParameter as one of its arguments, I want to execute my cmdlet using import-csv, how should I write my csv so that I am able to pass correct SwitchParameter value?

I have tried True, False, 0 , 1, with and without quotes in CSV however they dont seem to work, I always get false in my code

[Parameter(Mandatory = false, ValueFromPipelineByPropertyName=true)]
public SwitchParameter Enable { get; set; }

I am running Powershell version 2.0, the command I want to execute is :

Import-Csv c:\data.csv | Add-MyData

Upvotes: 3

Views: 2376

Answers (1)

Frode F.
Frode F.

Reputation: 54941

When you use Import-CSV, all properties are string-objects. So if you use 0 and 1, you need to cast it to int, and the to bool. Ex:

test.csv

Name,Enabled
"Hey",1
"Lol",0

Script:

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

You can then pass that to your switch, like:

#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

Upvotes: 3

Related Questions