我正在编写一个powershell高级函数,它将从管道中获取输入。更具体地说,我将从import-csv输入。问题是我正在使用的csv文件的列标题使用对ps无效的语法。这是我的代码就像
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
当我使用我的csv输入执行此操作时,$ Id的值变为2905,而$ IdRaw变量采用整个$ _哈希表的字符串表示形式。只是为了详细说明任何有效名称{URL,ID,Status}的参数都可以。任何包含空格或(RAW)的都会收到整个$ _变量。
-Patrick
答案 0 :(得分:3)
#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
示例文件内容
ID,ID(RAW),日期时间,日期时间(RAW),类型,类型(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