i'm trying to in powershell verify if xcopy did copy something. Thanks for any help.
xcopy /D /S /E "C:\folder1\*.*" "C:\folder2" /y
IF %CopiedFilesCount% >0 {
Start-Process C:\folder3\execute.bat
}
else{
"0 file copied"
}
In bat file this code does almost what i wan't. Trying to change "SourceFile" to "SourceFolder" and "DeleteFile" to "execute command or file"
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=C:\folder1\file2.txt"
set "DeleteFile=test.txt"
set "DestinationDirectory=C:\folder2\"
for /F %%I in ('%SystemRoot%\System32\xcopy.exe "%SourceFile%" "%DestinationDirectory%" /C /D /Q /Y 2^>nul') do set "CopiedFilesCount=%%I"
if %CopiedFilesCount% GTR 0 del "%DeleteFile%"
PowerShell will capture the stdout of any command as either a string or an array of strings.
From there you can use regex to capture the file copy count in the $Matches variable that is created by using -match. Note - the $Matches variable only populates when you pass in a single string. You can use -match to get the right line from an array, but then you need to match again to get your capture groups. "?" creates a named capture group we can access as a property of $Matches.
$result = xcopy /D /S /E "C:\folder1\*.*" "C:\folder2" /y
($results | Where-Object {$_ -match "(\d+) File"}) -match "(?<Count>\d+) File"
if ([int]$Matches.Count -gt 0) {
# Do Stuff
}
else {
# Write a message, write to a log, whatever
}