I am trying to delete a folder using robocopy mirroring like this:
Start-Process -FilePath "robocopy.exe" -ArgumentList "$emptyDir $sourcePath /mir /e /np /ns /nc /njs /njh /nfl /ndl" -Wait -PassThru -NoNewWindow but still get a line of output for every deleted file 
I tried adding >nul 2>&1 as explained in another answer here Start-Process -FilePath "robocopy.exe" -ArgumentList "$emptyDir $sourcePath /mir /e /np /ns /nc /njs /njh /nfl /ndl >nul 2>&1" -Wait -PassThru -NoNewWindow but still get the same output.
CodePudding user response:
Since you're running robocopy in the current console window (-NoNewWindow), synchronously (-Wait), there is no reason to use Start-Process at all - just invoke robocopy directly, which also allows you to use > redirections effectively:
robocopy.exe $emptyDir $sourcePath /mir /e /np /ns /nc /njs /njh /nfl /ndl *>$null
Note:
Direct execution makes a program's stdout and stderr output directly available to PowerShell, via its success and error output streams.
*>$nullis a convenient PowerShell shortcut for silencing all output streams - see about_Redirection.Another benefit of direct invocation is that the external program's process exit code is reported in PowerShell's automatic
$LASTEXITCODEvariable.
See also:
- This answer provides background information.
- GitHub docs issue #6239 provides guidance on when use of
Start-Processis and isn't appropriate.
As for what you tried:
You fundamentally cannot suppress output from a process launched with
Start-Process -NoNewWindowon the PowerShell side.Trying to silence command output at the source, i.e. as part of the target process' command line with
>nul 2>&1, would only work ifcmd.exewere the-FilePathargument and you passed arobocopycommand to it.>redirections are a shell feature, androbocopyitself isn't a shell.
CodePudding user response:
You can try to pass arguments via splatting, and then use the object pipeline to parse line by line.
In the example below, I'm going to split the arguments into two groups, in case you wanted to change out the options programmatically.
$roboFileArgs = @(
<#
If you're sure your argument is already a string or
a primitive type, there's no need to quote it.
#>
$emptyDir
$sourcePath
)
$roboFlags = "/mir","/e","/np","/ns","/nc","/njs","/njh","/nfl","/ndl"
# We can use splatting to pass both lists of arguments
robocopy.exe @roboFileArgs @roboFlags |
Foreach-Object {
<#
process output line by line and turn it into objects
or pipe to Out-Null if you truly don't care.
#>
}
