Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell: How to get cmd comp to run quietly?

I want to test the results of both the cmd commands comp and FC running in PowerShell on a series of files. I have succeeded in getting FC to run quietly in a script and yield correct results. In a cmd batch file, comp can run quietly by prefixing it with echo N |, but that is not working in PowerShell.

Here is a test script:

$LastExitCode = 99
$sItem_1 = "C:\temp\file 1.txt"
$sItem_2 = "C:\temp\file 2.txt"
write-output "Do FC:"
cmd.exe /c "FC /b ""$sItem_1"" ""$sItem_2"" > null"
write-output $LastExitCode
$LastExitCode = 99
write-output "Do comp:"
cmd.exe /c "echo N | comp ""$sItem_1"" ""$sItem_2"" > null"
write-output $LastExitCode

and here is the console output of that script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS> test 2.ps1
Do FC:
0
Do comp:
cmd.exe : Compare more files (Y/N) ? 
At test 2.ps1:9 char:1
+ cmd.exe /c "echo N | comp ""$sItem_1"" ""$sItem_2"" > null"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Compare more files (Y/N) ? :String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PS> 

In the second line of output, the zero exit code means that FC found the files to be identical. But when PowerShell attempted to run comp, it choked on the "Compare more" prompt.

How can I get this to run?

>Solution :

  • Use comp.exe‘s /M option to suppress the prompt for further comparisons.

  • There is no need to call comp.exe or fc.exe via cmd /c from PowerShell. Given that they’re external programs (executables), you can invoke them directly.

    • Use >$null to silence stdout output, 2>$null to silence stderr; *>$null silences both streams.
    • In direct invocation of external programs, PowerShell never requires you to enclose variable values in "..."

Therefore:

$sItem_1 = "C:\temp\file 1.txt"
$sItem_2 = "C:\temp\file 2.txt"

"Do FC:"
FC /b$ sItem_1 $sItem_2 >$null
$LastExitCode

$LastExitCode = 99
"Do comp:"
comp /M $sItem_1 $sItem_2 >$null
$LastExitCode
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading