好的,您的原始脚本效率极低且设计糟糕。这是执行您想要的操作的powershell,不需要临时文件。通常情况下,我不会有这么多评论,但我想确保每个人都理解我的所作所为。输出文件将位于执行此方法的工作目录中。
用法(在 cmd/batch 中):powershell -command "& { . \FileContainsThisFunction.ps1; Extract-Hosts original.csv }"
用法(在 powershell 中):。\FileContainsThisFunction.ps1; 提取主机 original.csv
function Extract-Hosts {
param(
[Parameter(Mandatory=$true)]
[String]$InputFile
)
if(-not (Test-Path $InputFile)) { throw ("Input file doesn't exist: {0}" -f $InputFile) }
# Extract filename without path or extension
$BaseName = Get-Item $InputFile | Select -ExpandProperty Basename
# Create a custom object that conains the outfilename and the content for lwks and wks
$OutLwks = @{ File = ('{0}-lwks.csv' -f $Basename); Content = @() }
$OutWks = @{ File = ('{0}-wks.csv' -f $Basename); Content = @() }
# First, delete the output files if they exist
$OutLwks, $OutWks | ForEach { if (Test-Path -Path:($_.File)) { Remove-Item $_.File } }
# Import the original csv into the pipeline
Import-Csv $InputFile |
# We only care about the IP and Hostname columns
Select -Property IP, Hostname |
# Where the hostname is not empty, nor contains n/a or n/s
Where { $_.Hostname -iNotMatch '(^$|n/a|n/s)' } |
ForEach-Object {
# If it contains lwks, add it to that list
if ($_ -imatch 'lwks') {
($OutLwks.Content += $_)
}
# if it contains wks but NOT lwks, add to the other list
elseif ($_ -imatch 'wks') {
($OutWks.Content += $_)
}
} | Out-Null # Sends objects to null after pipeline processing.
# Splat each one into the appropriate CSV file
$OutLwks, $OutWks | ForEach-Object {
$_.Content | Export-Csv -Path $_.File -NoTypeInformation }
}
编辑:修正了第二个内容添加中的错字,它应该是 OutWks.Content += $_ 编辑+:用 Foreach 替换了 Where magic,使其更容易理解;添加了 Out-Null 以抑制流水线后的输出。
希望这个脚本能让你更接近在 powershell 中编写丰富的管道处理器。