Search code examples
powershellscriptingpipeline

Access Pipeline Variable Attributes That Have invalid variable names


I am writing a powershell advanced function that will take input from the pipeline. More specifically, I will be piping in from import-csv. The problem is the column headers to the csv file I am using uses syntax invalid to ps. Here is what my code is like

function my-function{
    [CmdletBinding()]
    params
    (
        [Parameter(Mandatory=$false,ValueFromPipeline=$true,          
                    ValueFromPipelineByPropertyName=$true)]
        [string]$Id = $_.ID,


        [(Parameter(Mandatory=$false,ValueFromPipeline=$true,
                      ValueFromPipelineByPropertyName=$true)]
        [string]$IdRaw =  $_."ID(RAW)",
    )

    BEGIN{
         #Sets up a db connection
    }
    PROCESS{
         #Builds an insert query with csv members
    }
    END{
         #closes db connection
    }
}

ID,ID(RAW),Date Time,Date Time(RAW),Type,Type(RAW)
29874,29874,4/18/2012 23:58,41018.20753, Servername, ServernameRaw

When I execute this with my csv input, the value of $Id becomes 2905, while the $IdRaw variable takes on a string representation of the entire $_ hashtable. Just to elaborate any paramter with a valid name {URL, ID, Status} all work. Any that contain a space or (RAW) receive the entire $_ variable.

-Patrick


Solution

  • #Edit to include updated code
    $x=import-csv c:\temp\testinput.csv
    
    function my-function{
     [CmdletBinding()]
        param
        (
            [Parameter(Mandatory=$false,ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string]$Id,
            [Parameter(Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
            [alias("ID(RAW)")][string]$IdRaw 
        )
    
        begin{
             #Sets up a db connection
             Write-Debug "Starting"
        }
        process {
             #Builds an insert query with csv members
             write-debug "IDRaw=$IDRaw"
        }
        end {
             #closes db connection
                     Write-Debug "Ending"
    
        }
    }
    
    $x | my-function
    
    sample file contents

    ID,ID(RAW),Date Time,Date Time(RAW),Type,Type(RAW) 29874,29877,4/18/2012 23:58,41018.20753, Servername1, ServernameRaw1 29875,29878,4/19/2012 23:58,41018.20753, Servername2, ServernameRaw2 29876,29879,4/20/2012 23:58,41018.20753, Servername3, ServernameRaw3