0
我寫了一個函數和過濾器來分析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'[email protected]()}
# 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
您可以通過'Analyze'函數將文件屬性添加到對象。 – PetSerAl
@PetSerAl,我認爲,但它看起來像一個黑客。也許這是唯一的方法... – craig
如果您希望下一個函數使用它,您必須以某種方式返回到管道。 – Matt