Ok, your original script was horribly inefficient and badly designed. Here is the powershell to do what you want, no temp files needed. Normally, I wouldn't have nearly this many comments, but I want to make sure everyone understands what I did. The output files will be in the working directory from where you execute this method.
Usage(in cmd/batch): powershell -command "& { . \FileContainsThisFunction.ps1; Extract-Hosts original.csv }"
Usage(in powershell): . \FileContainsThisFunction.ps1; Extract-Hosts 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 }
}
Edit: Fixed typo in second Content addition, it should have read OutWks.Content += $_
Edit+: Replaced Where magic with Foreach to make it easier to understand; Added Out-Null to suppress output after pipeline.
Hopefully, this script will take you one step closer to writing rich pipeline processors in powershell.