I have csv files with wsus raport ( there are server names ) I have also txt file with server names which are in my scope.
I would like remove entry from my csv files if not match txt files.
I found solution how to to something appositive ( keep lines if match)
$SourceFile = 'C:\temp\wsus.csv'
$scope = Get-Content C:\Temp\windows_server.txt
foreach ($Pattern in $scope)
{
(Get-Content $SourceFile) | Where-Object { $_ -notmatch $Pattern } | Set-Content $SourceFile
}
I was hopping that I change -notmatch to -match and it will work but doesn't.
Best Regards, Krzysztof
CodePudding user response:
You basically need to write it exactly the other way round:
Get-Content $sourceFile | where {
foreach($pattern in $scope) {
if ($_ -match $pattern) {
return $true
}
}
}
Another alternative would be using Select-String
:
Get-Content $sourceFile | Select-String -Pattern $scope
Also, when working with CSV, you should consider using the appropriate cmdlets (like Import-Csv
).
CodePudding user response:
Assuming your wsus.csv looks anything like this:
Server,Something you need to know,Something you want to forget
Srv01,Main storage,blahblah
Srv02,Mail server,more blah
and your windows_server.txt simply holds servernames, each on a separate line, then you could do this:
$SourceFile = 'C:\temp\wsus.csv'
$scope = Get-Content C:\Temp\windows_server.txt
$csv = Import-Csv -Path $SourceFile | Where-Object {$scope -contains $_.Server }
# now export the scoped csv (I'd suggest to a new file, but you can overwrite the $SourceFile if you must)
$csv | Export-Csv -Path 'C:\temp\ScopedWsus.csv' -NoTypeInformation