Savill's FAQs: Using PowerShell File Comparison Capability
Three times a week, John Savill tackles your most pressing IT questions. Today: Learning about PowerShell file comparison capability; filtering search results containing certain strings; and using the pipeline in PowerShell commands.
December 14, 2017
Three times a week (Monday/Wednesday/Friday), John Savill tackles your most pressing IT questions.
Read through the FAQ archives, or send him your questions via email.
Today: Learn about the PowerShell file comparison process (more tips and tricks to get the most out of PowerShell), filtering search results containing certain strings, and using the pipeline in PowerShell commands.
Q. How can I compare two files using PowerShell?
A. PowerShell has the Compare-Object cmdlet. It compares objects, and those objects can include an array of text. To compare two files, you could read in the file and then compare. For example the command below begins the PowerShell file comparison process for the content of two files and shows any difference:
Compare-Object (get-content D:TempNPSmanualexport5dec_nps2.xml) (get-content D:TempNPSmanualexport5dec_nps1.xml)
Below is an example of the execution:
InputObject SideIndicator
----------- -------------
=>
<=
Q. How can I show results from PowerShell except for results containing a certain string?
A. I recently had a number of responses and need to remove any entries that contained a certain string. Fortunately this is very simple using the -notmatch operator. For example:
Get-ADOrganizationalUnit -LDAPFilter "(Name=$OUName)" | where {$_.DistinguishedName -notmatch "EXP"}
In this example all OUs that have the name of the variable $OUName are returned. Each is then passed to the next line that examines the distinguished name of the OU and if that OU distinguished name contains EXP it will not be passed down the pipeline. This approach can be used for really any type of comparison.
Q. In PowerShell scripts I sometimes see % after the pipe character. What does this do?
A. Using the pipeline in PowerShell is very powerful and enables objects to be passed between commands. It's very common to have a number of objects and then to run a command against each object passed, for example:
get-process | ForEach-Object { if ($_.CPU -ge 10) {$_.name}}
This gets a list of all processes then for each process object if the CPU consumed time is over or equal to 10 then its name is passed down the pipeline.
You can shorten this to just:
get-process | % { if ($_.CPU -ge 10) {$_.name}}
The % is just an alias for the ForEach-Object (you can also write ForEach).
About the Author
You May Also Like