1

This script is baffling me. I'm trying to write a script that takes the most recent shadow copy dir and put it in a var. This is what I have so far.

@ECHO off
set ShadowDir=
vssadmin list shadows|for /f "tokens=4 delims=: " %%A IN ('FINDSTR "GLOBALROOT"') do set ShadowDir=%%A
ECHO The dir is %ShadowDir%
pause

And this is the output.

C:\WINDOWS\system32>set ShadowDir=\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy14

C:\WINDOWS\system32>set ShadowDir=\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy15

C:\WINDOWS\system32>set ShadowDir=\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy16

C:\WINDOWS\system32>set ShadowDir=\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy17

C:\WINDOWS\system32>set ShadowDir=\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy18
The dir is
Press any key to continue . . .

As you can see, it is parsing correctly and giving me the desired output. But the ShadowDir var remains empty even with the set command being issued.

Any idea what's going on?

DavidPostill
  • 7,734
  • 9
  • 41
  • 60

1 Answers1

3

I'd use

for /f "tokens=4 delims=: " %%A IN ('vssadmin list shadows^|FINDSTR "GLOBALROOT"') do set ShadowDir=%%A

passing vssadmin output to findstr.

Magoo
  • 77,302
  • 8
  • 62
  • 84
  • That worked! Thanks, But out of curiosity, can you explain why? The output was being piped the way I had it but the var remained empty. – Ad-Man-Gamer Feb 01 '15 at 20:18
  • 2
    Because a pipe cause that the processes at both sides of the pipe run in a _separate cmd.exe session_ each, so this don't works either: `echo value | set /P var=`. For further details, see [here](http://stackoverflow.com/questions/8192318/why-does-delayed-expansion-fail-when-inside-a-piped-block-of-code) – Aacini Feb 01 '15 at 20:29
  • 1
    I believe you were outputting the `vssadin` command to the `for` - but the `for` was accepting input from the `findstr`. The `findstr` had no input, so it delivered an error message to `for` and that error message did not have a 4th token using `: ` as delimiters. Hence `%%A` was not established and the `set` not invoked, regardless of the screen report (can't reproduce, sorry.) By moving the `vssadmin` into the command-to-be-executed, then the output of `vssadmin` is delivered to `findstr` and `findstr`'s output to `for`. – Magoo Feb 01 '15 at 20:29