我写了一个函数和过滤器来分析CSV文件的内容。
创建列对象管道的函数:
function Analyze {
[CmdletBinding()]
Param(
[String]
$File
)
# get column headers from CSV; enumerate
$Headers = (Get-Content $File | Select-Object -First 1).Split(',')
$Headers | ForEach-Object {
# create an object that represents each column; initialize values
$Column = [PsCustomObject]@{'Name'=$_;'Measurements'=@()}
# add to pipeline
$Column
}
}
过滤以计算每列内容的最小值:
filter Min {
Param(
[string]$File
)
# create Logparser query
$Query = "SELECT Min($($_.Name)) AS Minimum FROM '$File'"
# excute query; return results as XML
[xml] $xml = & logparser $Query -stats:off -o:xml
# create object to contain measurement and its value
$Measurement=[PsCustomObject]@{'Name'='Minimum';Value=$xml.root.row.Minimum.Trim()}
# add to collection and return to pipeline
$_.Measurements+=$Measurement
$_
}
过滤以计算每列内容的最小值:
filter Max {
Param(
[string]$File
)
# create Logparser query
$Query = "SELECT Max($($_.Name)) AS Maximum FROM '$File'"
# excute query; return results as XML
[xml] $xml = & logparser $Query -stats:off -o:xml
# create object to contain measurement and its value
$Measurement=[PsCustomObject]@{'Name'='Maximum';Value=$xml.root.row.Maximum.Trim()}
# add to collection and return to pipeline
$_.Measurements+=$Measurement
$_
}
用法:
pushd C:\users\<user>\Desktop
$File = '.\d.csv'
Analyze -File $File | Min -File $File | Max -File $File
popd
有没有办法构建过滤器,以便我可以这样称呼它:
pushd C:\users\<user>\Desktop
Analyze -File '.\d.csv' | Min | Max
popd
答案 0 :(得分:0)
基于@Mathias R. Jessen的评论,我重构了函数和过滤器:
Data
需要禁用过滤器的管道:
function Analyze {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[alias('f')]
[String]
$File,
[Switch] $Min,
[Switch] $Max,
[Switch] $Top
)
# get column headers from CSV; enumerate
$Included = (Get-Content $File | Select-Object -First 1).Split(',')
$Included | ForEach-Object {
# create a hash that represents each column; initialize values
$Column = [PsCustomObject]@{'Name'=$_;'Measurements'=@()}
# apply specified filter; pass object via pipeline
if ($Min) { $Column | Min -File $File }
if ($Max) { $Column | Max -File $File }
if ($Top) { $Column | Top -File $File }
# add to pipeline
$Column
}
}
用法:
filter Min {
[Parameter(Mandatory=$True,Position=1)]
[alias('f')]
Param(
[string]$File
)
$Query = "SELECT Min([$($_.Name)]) AS Minimum FROM '$File'"
[xml] $xml = & logparser $Query -stats:off -o:xml
$Measurement=[PsCustomObject]@{'Name'='Minimum';Value=$xml.root.row.Minimum.Trim()}
$_.Measurements+=$Measurement
# pipeline disabled; created multiple instances of Column object
#$_
}
# similar changes to these filters
filter Max {}
filter Top {}