Search code examples
powershellcsvconditional-statementspipeline

Output to Pipeline from within IF ELSE statement


UPDATE: I just found out that the client I am running this on is PS V1. I can't use splatting.

I have a script for processing csv files. I don't know ahead of time if the file will have a header or not so I'm prompting the user to either input a header or use the one in the file:

$header = Read-Host 'Input your own header?'

What I want to do is be able to check whether the header variable has been set to decide if I want to use that flag when executing the Import-CSV commandlet.

I have tried a number of things along the lines of:

IF($Header){Import-Csv $File -delimiter $delimiter -Header $header }
ELSE 
{Import-Csv $File -delimiter $delimiter} |

Or

IF($Header){Import-Csv $File -delimiter $delimiter -Header $header | %{$_} }
ELSE 
{Import-Csv $File -delimiter $delimiter | %{$_}}

The first example results in complaints of an empty pipeline. The second results in the first column of the file just being ouptut to the console and then errors when the file is done processing because the rest of the pipeline is empty.

As always any help would be appreciated.

Thanks, Bill


Solution

  • The easiest way is just to use the -OutVariable option on Import-Csv

    Import-Csv -Path:$File -Delimiter:$Delimiter -OutVariable:CSVContents will save it in $CSVContents

    From the Import-CSV Technet page:

    This cmdlet supports the common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutBuffer, and -OutVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/p/?LinkID=113216).

    Another alternative is to use an args hash and "splat" it:

    $myArgs = @{
        Path = "$HOME\temp\foo"
    }
    
    Get-Content @myArgs
    

    Update for Version 1 (untested):

    ( IF($Header) { Import-Csv $File -delimiter $delimiter -Header $header }
      ELSE { Import-Csv $File -delimiter $delimiter} ) |
    #More pipeline commands here, example:
    Format-Table
    

    Horrible disgusting version (untested):

    $ImportCommand = "Import-Csv $File -delimiter $delimiter"
    If($header -ne $null) { $ImportCommand += " -header $header" }
    Invoke-Expression $ImportCommand | 
    Format-Table