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.
*>$null
is 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
$LASTEXITCODE
variable.
See also:
- This answer provides background information.
- GitHub docs issue #6239 provides guidance on when use of
Start-Process
is and isn't appropriate.
As for what you tried:
You fundamentally cannot suppress output from a process launched with
Start-Process -NoNewWindow
on 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.exe
were the-FilePath
argument and you passed arobocopy
command to it.>
redirections are a shell feature, androbocopy
itself 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.
#>
}