I want to assign to a variable the error message printed by an xcopy command from a powershell script. If I simply assign the command to a variable, it only saves the last line, where it says the number of files copied
> $out = xcopy C:\test.txt C:\
File not found - test.txt
> $out
0 File(s) copied
I want to save the error message, meaning the string "File not found".
I already tried all methods suggested here How to show output of xcopy in powershell script while it's running, but also piping it to Tee-Object -Variable out only saves the last line of the output and not the error message (same as above).
The closest I got was by using redirection xcopy C:\a.txt C:\ 2>&1 | Out-Host , but this still doesn't save it to a variable of my choice, only to the global $error[0] variable
My desired output would be a string with the error message. In the above example:
> $out
File not found - test.txt
$xcoutput = (xcopy C:\TEST.TXT C:\ 2>&1)?[string]$xcoutput[1]. If you post it as answer I'll mark it as the solution. Anyway, now i am more interested in understanding the reason behind this behaviour... What difference do the parenthesis do? And why a simple assignment only stores the copy result and not the error message?