powershell - Filter a few computers before exporting from pipeline -
i need filter out 4 machines prior exporting csv file. have no clue how filter them out. tried if clause produced nothing. please help.
$old = (get-date).adddays(-90) # modify -90 match threshold $oldcomputers = get-adcomputer -searchbase "ou=workstations,dc=corporate,dc=local" -searchscope 2 -filter { passwordlastset -le $old } -properties * $oldcomputers if ($_.name -notlike "1919dd" -or $_.name -notlike "1919smaheshware" -or $_.name -notlike "1919ietest" -or $_.name -notlike "1920bpasceritb") { export-csv c:\temp\over90daysmachines.csv -notypeinformation -force -append }
for 1 thing, able use current object variable ($_
) need pipeline context. putting if
statement after echoing variable doesn't automagically feed echoed value(s) if
statement. need change this:
$oldcomputers if ($_.name -notlike "1919dd" -or ...) { export-csv c:\temp\over90daysmachines.csv -notypeinformation -force -append }
into this:
$oldcomputers | where-object { $_.name -notlike "1919dd" -or ... } | export-csv c:\temp\over90daysmachines.csv -notype -force
however, change filter won't work correctly, because connected -notlike
clauses via -or
when should have used -and
. meant process objects if name doesn't match of given values. logical expression evaluate $false
name have match all of reference value at same time. isn't possible, expression evaluates $true
.
example:
assume have variable $v
should not equal either a
, b
, or c
. applying logic, expression in powershell:
($v -notlike 'a') -or ($v -notlike 'b') -or ($v -notlike 'c')
if $v
takes instance value a
expression becomes
('a' -notlike 'a') -or ('a' -notlike 'b') -or ('a' -notlike 'c') ↔ ($false) -or ($true) -or ($true) ↔ $true
to check if give value equals neither of reference values need connect clauses via -and
:
('a' -notlike 'a') -and ('a' -notlike 'b') -and ('a' -notlike 'c') ↔ ($false) -and ($true) -and ($true) ↔ $false
$oldcomputers | where-object { $_.name -notlike "1919dd" -and $_.name -notlike "1919smaheshware" -and $_.name -notlike "1919ietest" -and $_.name -notlike "1920bpasceritb" } | export-csv c:\temp\over90daysmachines.csv -notype -force
note btw, -notlike
operator behaves -ne
operator when reference string doesn't contain wildcard characters. if you're not doing fuzzy matches anyway simplify expression checking if given name (not) found in array of names instead of doing multiple checks (in)equality:
$excludes = '1919dd', '1919smaheshware', '1919ietest', '1920bpasceritb' $oldcomputers | where-object { $excludes -notcontains $_.name } | export-csv c:\temp\over90daysmachines.csv -notype -force
another option regular expression (non-)match:
$oldcomputers | where-object { $_.name -notmatch '^1919dd|1919smaheshware|1919ietest|1920bpasceritb$' } | export-csv c:\temp\over90daysmachines.csv -notype -force
Comments
Post a Comment