Parenthetical Redirection
Posted: 21 Jul 2021 13:01
I was trying to find out more about the rules of redirection to file through the use of parentheses. In some cases, I find this works fine, but in others the batch script crashes. I am attempting to collect some system information and write it to file. Here is an example of where this is failing:
If I remove the brackets after the echo, it prints the information to the console. If I remove the parentheses surrounding "Locally stored network credentials" and "A user logged on to this computer" it echos the information to file. I tried escaping the parentheses, but that did not work. Is there a way to keep the parentheses? If not, are there any other rules I should be aware of when re-directing to file with parentheses?
I know I can do this, but I'd like the code to look cleaner:
Code: Select all
@echo off
setlocal enabledelayedexpansion
for /f "tokens=3 delims=: " %%a in ('wevtutil qe Security /q:"*[System[(EventID=4624)]] and *[EventData[Data[@Name='LogonType'] and (Data=2 or Data=11)]]" /c:1 /rd:true /f:text ^|findstr "Type:"') do for /f "tokens=*" %%b in ("%%a") do set logonType=%%b
if %logonType% EQU 11 set logonTypeInfo=Cached Interactive (Locally stored network credentials)
if %logonType% EQU 2 set logonTypeInfo=Interactive (A user logged on to this computer)
for /f "tokens=* delims=: " %%c in ('wevtutil qe Security /q:"*[System[(EventID=4624)]] and *[EventData[Data[@Name='LogonType'] and (Data=2 or Data=11)]]" /c:1 /rd:true /f:text ^|findstr "Date:"') do for /f "tokens=*" %%d in ("%%c") do set logonDate=%%d
if defined logonDate set logonDate=!logonDate:~6,-9!
set logonInfo=%logonDate:~5,2%/%logonDate:~8,2%/%logonDate:~0,4% at %logonDate:~11,8%
set exportPath="%userprofile%\info_%username%.txt"
(
echo Logon Info:
echo Last Logon: %logonInfo% [%logonTypeInfo%]
)> %exportPath%
I know I can do this, but I'd like the code to look cleaner:
Code: Select all
echo Logon Info: >%exportPath
echo Last Logon: %logonInfo% [%logonTypeInfo%] >> %exportPath