I have a batch file which runs a python script. The python script after completion sends a number like shown below:
I need my batch file to read its own output as it runs and then use this (the number 3 shown in figure below to do some processing
Is this possible with batch?
EDITED FOR CLARITY:
I want to have a script which uses "net use" command.
The output from this specific command is as shown below... which will be printed to cmd window in which script is running ! Now I want my script to read this output ..like if a certain address is found in the already mapped drives list it will do something..like unmap the drive
I don't understand quite well what your purpose is, what has to do python to do with capture the net use command output?
As a rule of thumb, to capture any command output, you must use a for loop (i.e. here capturing clipboard content using powershell
rem get clipboard content into variable
set "psCmd=powershell -Command "add-type -an system.windows.forms; [System.Windows.Forms.Clipboard]::GetText()""
for /F "usebackq delims=" %%# in (`%psCmd%`) do set "clipContent=%%#"
So, in order to grab the output of net use
#echo off
for /f "skip=6 tokens=2,3" %%a in ('net use') do (
echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
But, I suggest that you better use wmic (following two are similar)
#echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic path Win32_LogicalDisk Where DriveType="4" get DeviceID, ProviderName"`) do (
echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
or
#echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic path Win32_MappedLogicalDisk get DeviceID, ProviderName"`) do (
echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
Since, you may add the /node:"some_other_computer_name" switch to wmic and may list mapped drives from any computer on the net, i.e
#echo off
for /f "useback skip=1 tokens=1,2" %%a in (`"wmic /node:"hp-ml110" path Win32_MappedLogicalDisk Where DriveType="4" get DeviceID, ProviderName"`) do (
echo/%%a | find ":">NUL && echo/Drive letter %%a - Remote name %%b
)
exit/B
Hope it helps.
Related
This question already has an answer here:
Variables are not behaving as expected
(1 answer)
Closed 2 years ago.
I'm trying to write a script but I'm really bad at writing the batch scripts. I'm trying to create a script that recognizes local hard drives and puts the letter of those hard drives in a variable, and after that I use that variable in another for loop to decrypt the hard drive if it's encrypted.
Example:
:check
for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=3" get name /format:value') do (
set vvv=%%d
for /f "tokens=1,*" %%A in ('manage-bde -status %vvv% ^| findstr Conversion') do set var1=%%B
Rem Try to find if value is Encrypted or not
echo %vb1%|find "Encrypted" >nul
if errorlevel 1 ( goto :check) else ( goto :decrypt_c))
#Echo Off
:check
for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=3" get name /format:value') do (
echo %%d
manage-bde -off %%d )
pause
That code works fine until echo %%d, when I try to put it into manage-bde command does not work...When I have for example 3 hard drives, I will do loop and turn off BitLocker for all partitions. Thanks!
Perhaps you'd be better off using the Win32_EncryptableVolume Class.
This example will create variables, e.g. %EncryptedDriveLetter[1]%, %EncryptedDriveLetter[2]%, %EncryptedDriveLetter[3]% etc., with the respective content of e.g. C:, E:, F:
#Echo Off & SetLocal EnableExtensions DisableDelayedExpansion
For /F Delims^== %%G In ('2^> NUL Set EncryptedDriveLetter[')Do Set "%%G="
For /F Delims^= %%G In ('^""%SystemRoot%\System32\wbem\WMIC.exe" ^
/NameSpace:\\root\CIMv2\Security\MicrosoftVolumeEncryption Path ^
Win32_EncryptableVolume Where ^
"ConversionStatus!='0' And EncryptionMethod!='0' And VolumeType<'2'" ^
Get DriveLetter 2^> NUL ^| "%SystemRoot%\System32\find.exe" ":"^"'
)Do (Set /A i+=1 & SetLocal EnableDelayedExpansion
For %%H In (!i!) Do EndLocal & Set "EncryptedDriveLetter[%%H]=%%G")
Set EncryptedDriveLetter[ & Pause
Notes: This must be run 'As administrator', and the last line is included just to provide some visual output. You would of course, replace that, with the rest of your script.
Just to be sure that you understand why I provided this methodology; if you were simply wanting to decrpt the encrypted drives, you don't need a for loop, or variables or manage-bde. You would just change the Get method to Call and use Decrypt.
For example:
#"%SystemRoot%\System32\wbem\WMIC.exe" /NameSpace:\\root\CIMv2\Security\MicrosoftVolumeEncryption Path Win32_EncryptableVolume Where "ConversionStatus!='0' And EncryptionMethod=!'0' And VolumeType<'2'" Call Decrypt
Just to mention, if the protection status prior to decryption was 1, i.e. Protection On, upon successful completion the protection status will be changed to 0, i.e. Protection Off.
need to extarct partial string from a line in log file. I want to read a entries in log file, here is an example:
Thu 08/29/2019 10:46:43.22 setup.bat USB REIMAGE - WinPE reimage of .wim END
I want to extract only day, date and time
I have tried for loop to extract and it doesnot help me
For /F "UseBackQ Delims==" %%A In ("R:\reimage.log") Do Set "lastline=%%A"
IF "%lastline%" == "USB REIMAGE - WinPE reimage of"(
set lastline=!line:~0,4!
echo "The last reimage performed by installer was on %lastline%"
pause
)
The example I gave in the comment was to show how we use tokens. Something like this should do what you want though:
#echo off
for /f "tokens=1-3" %%i in ('type R:\reimage.log ^| findstr /I "USB REIMAGE - WinPE"') do echo %%i %%j %%k
I know c++ pretty well and unix commands (bourn shell) fairly well, but I am very unfamiliar with batch files.
I'm working on getting serial numbers for all of our machines to verify that they are named properly, and are issued to the correct user. Please note that this is my first post and am just giving you the down and dirty code.
This is what I have so far (good for one computer)
hostname >> computerlog.txt rem send the pcname to txtfile computerlog
rem get serial number from bios
wmic bios get serialnumber >> computerlog.txt
rem get serial number from network location (pcname is a network pc)
wmic /user:johnnyboy/node:pcname bios get serialnumber >> computerlog.txt
What I would like to do is use a loop to read the names in and store them as a variable, run the command above, and output the name followed by serial number to a text file.
I don't know how to use a loop or create a variable.
Thank you for all of your help.
Provided the data in the file YourData.csv has this format
"NODENAME","USERNAME","PASSWORD"
"Computer1","Johnnyboy","secret"
This batch should do what you want:
#Echo off&SetLocal EnableExtensions EnableDelayedExpansion
(Echo "NODENAME","SerialNumber"
For /f "usebackq skip=1 tokens=1-3 delims=," %%A in (
"YourData.csv"
) Do For /f "tokens=2 delims==" %%S in (
'wmic /NODE:%%A /USER:%%B /PASSWORD:%%C bios get serialnumber /value^|find "="'
) Do For /f "delims=" %%T in ("%%S") Do Echo %%A,"%%T"
) > "YourSerials.csv"
Since the wmic output is in UTF16 and one for loop can't compensate the conversion remnants cr,cr,lf the third for will do this.
Sample output:
> type YourSerials.csv
"NODENAME","SerialNumber"
"HP-G1610","CZxxxyyyPM "
Be warned that wmic here was terribly slow.
snippets:
set "varName=varValue"
:loopName
:: do something
goto:loopName
:: take each line of log to %%t - variable of cycle
for /f "usebackq delims=" %%t in ("computerlog.txt") do echo.%%t
example:
setlocal enabledelayedexpansion
set counter=0
for /f "usebackq delims=" %%t in ("computerlog.txt") do (
set "var!counter!=%%t"
set /a counter+=1
)
set var
I am trying to create a batch file that will return a file location, including partition (or drive) so I can use it for more manipulation in that batch file.
The file name is known but the partition and directory are not known. Is that possible?
You can try something like that :
#echo off
Title Searching for file by name
Mode con cols=75 lines=3
cls & color 0A
Set SearchResult=SearchResult.txt
If Exist %SearchResult% Del %SearchResult%
echo(
set /P "FileName=Type the file name for looking for = "
Setlocal EnableDelayedExpansion
for /f "tokens=2" %%i in ('wmic logicaldisk where "drivetype=3" ^|find /i ":"') do (
Set MyDrive=%%i
echo( & cls
echo( & echo Please Wait for moment .... Searching for "%FileName%" on "!MyDrive!\"
#where /r !MyDrive!\ "%FileName%" >> %SearchResult%
)
Start %SearchResult%
The following script -- let us call it findfile.bat -- searches for a file with the name given as a command line argument (for instance, findfile.bat "lostfile.txt") on local disks and network drives as an example:
#echo off
for /F "skip=1" %%I in (
'wmic LOGICALDISK WHERE ^( ^
DriveType^=3 OR^
DriveType^=4^
^) GET DeviceID'
) do (
for /F "delims=" %%J in ("%%I") do (
2> nul where /R %%J\ "%~1"
)
)
The wmic command is used to retrieve the drives available on the current system. In the example there are two DriveType values allowed: 3, meaning local disks, and 4, meaning network drives. You can adapt the filter as you like -- reference site Win32_LogicalDisk class for all the possible values. To not filter any drive types, simply remove the entire WHERE clause and use the remaining wmic command line wmic LOGICALDISK GET DeviceID instead.
This information below is contained in a text file and formatted as such.
/var/www/xxx/html/videos/video_folder_1
/var/www/xxx/html/videos/video_folder_2
/var/www/xxx/html/videos/video_folder_3
/var/www/xxx/html/videos/video_folder_4
/var/www/xxx/html/videos/video_folder_5
/var/www/xxx/html/videos/video_folder_6
/var/www/xxx/html/videos/video_folder_7
I also have a variable called %file_name% in the batch file already defined.
So lets say that is it is %file_name% = V001-video_folder_6.mp4
As you can see there is some more extra information, V001- and .mp4.
I would like to use the var %file_name% to search the text file and return the entire line. In this case it would return /var/www/xxx/html/videos/video_folder_6 and then put this information in a new var, let us say, %folder_path%.
I think I would use findstr however I have been playing around and not getting the best results.
The problem with the methods that use findstr is that they are slow, because they require to execute findstr.exe (a ~30KB file) each time. A simpler/faster solution is to use just internal Batch commands with the aid of an array. If the number of names to process is large, the difference in time between the two methods may be marked.
#echo off
setlocal EnableDelayedExpansion
rem Load the lines from text file into an array with the last part as index:
for /F "delims=" %%a in (test.txt) do (
set "line=%%a"
for %%b in (!line:/^= !) do set "lastPart=%%b"
set "folder[!lastPart!]=%%a"
)
set "file_name=V001-video_folder_6.mp4"
rem Get the folder from file_name:
for /F "tokens=2 delims=-." %%a in ("%file_name%") do set "folder_path=!folder[%%a]!"
echo Folder path is: %folder_path%
Let us assume the posted lines are in file Test.txt in current working directory.
#echo off
set "file_name=V001-video_folder_6.mp4"
for /F "tokens=2 delims=-." %%A in ("%file_name%") do set "folder=%%A"
for /F "delims=" %%P in ('%SystemRoot%\System32\findstr.exe "/C:%folder%" Test.txt') do (
set "folder_path=%%P"
goto NextCommand
)
:NextCommand
echo Full folder path is: %folder_path%
Open a command prompt window, enter the command for /?, hit key RETURN or ENTER and read output help to understand this little code.
The command goto inside FOR loop results in an immediate exit from loop processing output of findstr.exe after first found line containing the folder path of interest.
Perhaps better in case of searched folder is not found in text file:
#echo off
set "file_name=V01-VIDEOS for school (Miss Patrick).mp4"
for /F "tokens=2 delims=-." %%A in ("%file_name%") do set "folder=%%A"
for /F "delims=" %%P in ('%SystemRoot%\System32\findstr.exe "/C:%folder%" Test.txt') do (
set "folder_path=%%P"
goto FoundFolder
)
echo "%folder%" not found in file Test.txt.
pause
goto :EOF
:FoundFolder
echo Full folder path is: "%folder_path%"
pause
This should work:
::file_name=V001-video_folder_6.mp4
::file containing folder paths is called paths.txt
for /f "tokens=2 delims=-." %%a in ("%file_name%") do set FN=%%a
for /f %%a in ('findstr /E /L "%FN%" "paths.txt"') do set folder_path=%%a
echo %folder_path%
Which does what you want in effectively two lines.