Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1001.

Solve : check if file exist over ftp?

Answer»

I have a backup over FTP and sometimes happend backup didn't finished or even started.
How can I check over FTP if file exist if not, to run backup again?
I found this but not quite understand batch.
Can someone help me with it? Thank you.

Code: [Select]echo off

:FETCHFILE
ftp -s:ftp.txt
IF EXIST filetocheckfor.txt (
   REM the file was there, so do something
) ELSE
   echo Trying again...
   REM ping "sleep" would GO here
   GOTO FETCHFILE
)


here is my ftp batch for backup. this is txt file which is called with batch
Code: [Select]open 184.50.15.14
username
password
status
binary
cd /imagine_zip
lcd D:\zipano_arhiv\imaginesql
mdelete *.7z.*
mput "*.7z.*"
quit
del /Q D:\zipano_arhiv\imaginesql\*.*
close
quit
Sometimes also happends that files which are copied over ftp on end side they are zero bytes and have no clue why.One way to do this would be to use the batch file to generate a temporary ftp script and use that to download the file, then check if it exists on the local machine. This would be a pretty bad APPROACH though.

I think the easiest way is to download the wget tool for windows: http://users.ugent.be/~bpuype/wget/

Then in your batch file you'd TYPE something like this:

Code: [Select]echo off
start /wait wget ftp://username:[email protected]_address/thefolder/thefile.txt
if exist thefile.txt (
   echo file was found.
) else (
   echo file missing.
)

I don't know if this will work with spaces in the file name. You probably have to put quotes around it. Also NOTE the forward slashes in the wget's path.thak you for helping.
I know that works with ftp too, maybe someone else knows how. Quote from: Linux711 on February 19, 2015, 05:13:06 AM

One way to do this would be to use the batch file to generate a temporary ftp script and use that to download the file, then check if it exists on the local machine. This would be a pretty bad approach though.

It's likely that wget will download and create a zero byte file, but the filesize could then be tested - to see if it the correct filesize too.I have managed to delete zero bytes files on server so what I need is check if file is there if it is not than ftp backup should run again.http://www.dostips.com/DtTipsFtpBatchScript.php#Batch.FtpBatchUploadOnlyNewFiles
Quote from: Squashman on February 19, 2015, 07:16:04 AM
http://www.dostips.com/DtTipsFtpBatchScript.php#Batch.FtpBatchUploadOnlyNewFiles

I see that script is in parts the same like I found out.
but have no clue what should be in part

 REM the file was there, so do something

Code: [Select]echo off

:FETCHFILE
ftp -s:ftp.txt
IF EXIST filetocheckfor.txt (
   REM the file was there, so do something
) ELSE
   echo Trying again...
   REM ping "sleep" would go here
   GOTO FETCHFILE
)It is synching the FTP folder with your local folder!
If the file does not exist on the FTP site but exists in the folder on your computer it will upload it.OK this is the script I try to SETUP folders to upload but not working, maybe I have set some settings wrong.
Can someone please quick check of it and make some suggestions?
Thank you.

Code: [Select]Echo Off
Setlocal Enabledelayedexpansion

REM -- Define File Filter, i.e. files with extension .txt
Set FindStrArgs=/E /D:"*.7z.*"

REM -- Extract Ftp Script to create List of Files
Set "FtpCommand=ls"
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
Rem Notepad "%temp%\%~n0.ftp"

REM -- Execute Ftp Script, collect File Names
Set "FileList="
For /F "Delims=" %%A In ('"Ftp -v -i -s:"%temp%\%~n0.ftp"|Findstr %FindStrArgs%"') Do (
    Call Set "FileList=%%FileList%% "%%A""
)

REM -- Extract Ftp Script to upload files that don't exist in remote folder
Set "FtpCommand=mput"
For %%A In (%FileList%) Do set "Exist["%%~A"]=Y"
For /F "Delims=" %%A In ('"dir /b "%localdir%"|Findstr %FindStrArgs%"') Do (
    If Not defined Exist["%%~A"] Call Set "FtpCommand=%%FtpCommand%% "%%~A""
)
Call:extractFileSection "[Ftp Script 1]" "-">"%temp%\%~n0.ftp"
rem  Notepad "%temp%\%~n0.ftp"

For %%A In (%FtpCommand%) Do Echo.%%A

REM -- Execute Ftp Script, download files
ftp -i -s:"%temp%\%~n0.ftp"
Del "%temp%\%~n0.ftp"
GOTO:EOF


:extractFileSection StartMark EndMark FileName -- extract a section of file that is defined by a start and end mark
::                  -- [IN]     StartMark - start mark, use '...:S' mark to allow variable substitution
::                  -- [IN,OPT] EndMark   - optional end mark, default is first empty line
::                  -- [IN,OPT] FileName  - optional source file, default is THIS file
:$created 20080219 :$changed 20100205 :$categories ReadFile
:$source http://www.dostips.com
SETLOCAL Disabledelayedexpansion
set "bmk=%~1"
set "emk=%~2"
set "src=%~3"
set "bExtr="
set "bSubs="
if "%src%"=="" set src=%~f0&        rem if no source file then assume THIS file
for /f "tokens=1,* delims=]" %%A in ('find /n /v "" "%src%"') do (
    if /i "%%B"=="%emk%" set "bExtr="&set "bSubs="
    if defined bExtr if defined bSubs (call echo.%%B) ELSE (echo.%%B)
    if /i "%%B"=="%bmk%"   set "bExtr=Y"
    if /i "%%B"=="%bmk%:S" set "bExtr=Y"&set "bSubs=Y"
)
EXIT /b


[Ftp Script 1]:S
!Title Connecting...
open 184.50.15.14
username
password

!Title Preparing...
cd /imagine_zip
lcd D:\zipano_arhiv\imaginesql
binary
hash

!Title Processing... %FtpCommand%
%FtpCommand%

!Title Disconnecting...
disconnect
bye
and this are my ftp settings

Code: [Select]open 184.50.15.14
username
password
status
binary
cd /imagine_zip
lcd D:\zipano_arhiv\imaginesql
mdelete *.7z.*
mput "*.7z.*"
quit
del /Q D:\zipano_arhiv\imaginesql\*.*
I get all the time this
FINDSTR: Bad command line
FINDSTR: Bad command line


and don't know why scritp trying to connect
http://www.dostips.comNo where in that code does it do any type of connection to DosTips.com Quote from: Squashman on February 28, 2015, 01:41:48 PM
No where in that code does it do any type of connection to DosTips.com
you are right
I checked again I maded a log from script it doesn't.
But script still don't work
First part looks like there is trouble searching file.can someone help me with this please?
1002.

Solve : Batch to delete files on reboot?

Answer»

Greetings

I'm looking to create a batch FILE that will delete FILES on the next reboot. Not something that will just attempt to delete them there and then because the target file(s) will be in use.

In comparison, it would act like "KillBox" or "Remove on Boot", but I want batch code that will do this.

In addition, it would be nice if it would also apply to directories.

I honestly don't know if it's possible or whether this technique requires more advanced programming than DOS.

If you're really that INTERESTED, the reason for such is to remove multiple files associated with malware, particularly those of VX2/Look2Me.

If anyone knows and would tell me how I could achieve this, I'd be rather appreciative Do you want the files be deleted before the operating system starts? If not, adding the appropriate commands to the autoexec.bat or autoexec.nt should be sufficient.

Code: [Select]del /f /s /q <path>
deletes all files and folders in <path>. Add this line to the appropriate autoexec or to a normal batch file which is called under Windows as scheduled task at startup or added to the startup folder.

Cheers,
[glb]cs[/glb]I suppose that's an option. But it depends on whether it would run before the startup processes.

The principal is, that VX2/Look2Me infections create random DLL's upon each reboot, with the help of Registry entries. So the question is whether the script will delete the DLL's before they are renamed.

Although there are tools to deal with this infection, it's the idea that intruiges me.

I see one possibility is to use a batch file to copy or move the current autoexec to a temporary location and then replace it with a modified version. Then, per the scripting, the system will reboot and delete the files (hopefully) and after that, it will delete the modified autoexec and reinstate the original.

If you see what I mean, do you think that could be feasible?Okay, this is the score so far...

I have created a folder : C:\Fix : Inside there is...

- RUN ME.BAT - Quote

move C:\autoexec.bat "%WINDIR%\temp"

move C:\fix\autoexec.bat C:\

start reboot.exe
- AUTOEXEC.BAT - Quote
del /f /q  C:\fix\bad.txt

start C:\fix\replace.bat
- REPLACE.BAT - Quote
del C:\autoexec.bat
move "%windir%\temp\autoexec.bat" C:\

There is also a rebooting utility, which upon execution reboots the system. Oh yes, and of course the target file, BAD.TXT

As you can see, the idea here is to put the current AUTOEXEC into the Windows\Temp directory and move the new one to C:\ and then reboot. AUTOEXEC would then run on reboot and firstly delete the text file. Then replace will be executed to restore the original AUTOEXEC.

Unfortunately, all goes well up until deleting the text file. I don't think AUTOEXEC.BAT is being loading per system boot. Any ideas? Quote from: Mere_Mortal on January 24, 2005, 04:21:09 PM
Okay, this is the score so far...

I have created a folder : C:\Fix : Inside there is...

- RUN ME.BAT -- AUTOEXEC.BAT -- REPLACE.BAT -There is also a rebooting utility, which upon execution reboots the system. Oh yes, and of course the target file, BAD.TXT

As you can see, the idea here is to put the current AUTOEXEC into the Windows\Temp directory and move the new one to C:\ and then reboot. AUTOEXEC would then run on reboot and firstly delete the text file. Then replace will be executed to restore the original AUTOEXEC.

Unfortunately, all goes well up until deleting the text file. I don't think AUTOEXEC.BAT is being loading per system boot. Any ideas?

I follow all steps but it doesn't work with me
I use Deep freeze if you went to use it this a link to download it http://so2.co/deepPlease Ignore the Post above...

Especially since the Topic is 9 years old... Quote from: aehbb on March 05, 2015, 09:36:06 AM

I follow all steps but it doesn't work with me
I use Deep freeze if you went to use it this a link to download it http://so2.co/deep
HMM.  Are you licensed to redistribute Deep Freeze without anyone paying for it?He is now on our beloved Watch List...
1003.

Solve : create bat file to start file with different user?

Answer»

Hello i am beginner user and i need HELP

I want to create bat FILE to start .exe file  with "run as different user" then it should be written user name and password and then pressed ok.

can anyone  help me You do know that by doing this the username and password for the other account would be easy for SOMEONE to view in the batch file right?  Is this to elevate privileges just for a specific EXE on a user PRIVILEGED account? Also which version of Windows?I know but I’m in different domain and the program which should be run is under different domain user and pass.


windows 7 ultimate  64 bit

1004.

Solve : Backup batch file and hashing?

Answer»

It's been a while since I've been here, but I used to be a pretty active user. Anyway, our network recently got hit by the CryptoWall virus (it encrypts all your files and then asks you to pay to decrypt). Luckily I had a backup that was just over a week old, so we didn't loose too much.

I have been using a batch file that someone on here helped me write a few years ago. Now I'd like to make some modifications to make it more secure. The batch file first uses the xcopy command with a few switches to only backup new or modified files from the source so that it doesn't have to copy the entire server every time. The batch file secondly uses two short loops to go through the entire directory tree and delete files from the backup that have been removed from the source. The problem with this is if the source gets deleted or corrupted, it will delete all those files from the backup (huge problem). What I've decided it should do is log the total file count on the source each time it backs up and if the count is < the previous count by some arbitrary number (100 is good), then it does not delete the files from the backup.

I'd also like to implement some hashing, but I know that can't be DONE directly in batch. Does anyone know of any command line programs that will go through an entire directory tree and generate a list of hashes and then be able to go back a verify those hashes against the files?

Here is the batch file so far:
Code: [Select]echo off
setLocal EnableDelayedExpansion
title Folder Sync System
color 0a
set backCMD=xcopy /c /f /d /e /h /i /r /y
set /p backPath=Enter the name of the folder to backup:
set sourcePath=Z:\%backPath%
set backPath=%cd%%backPath%

echo Backing up %sourcePath% to %backPath%. . .
echo.

rem BACKUP THE FILES THAT HAVE BEEN CHANGED
%backCMD% %sourcePath% %backPath%

echo.
echo Removing old stuff in %backPath%. . .
echo.

rem CHECK FOR FILES THAT HAVE BEEN REMOVED FROM
rem THE SOURCE AND DELETE THEM FROM THE BACKUP DIRECTORY
for /r %backPath% %%g in (*.*) do (
set var=%%g
if not exist "%sourcePath%!var:%backPath%=!" (
echo File:!var!
echo.
del /f /q "!var!"
)
)

rem REMOVE ANY EMPTY DIRECTORIES FROM BACKUP
for /d /r %backPath% %%g in (*) do (
set var=%%g
if not exist "%sourcePath%!var:%backPath%=!" (
echo Dir:!var!
echo.
rd /s /q "!var!"
)
)

echo %date% : %time% : %backPath% >> backup.log
echo Finished backing up %sourcePath%
echo Log entry added in backup.log
pause
exit
Well we used md5 on our linux servers years ago.I was thinking a possible better way to do this would be to have a dedicated folder for files deleted from the source which would move from the backup to this folder. The only thing I don't know how to do is have the move command create an empty directory structure to move the file to.

say I want to move a file:
move thing.txt C:\bla\bla\bla

but bla bla bla does not exist. Is there a way to automatically create the structure?I searched around and it looks like I just need to remove the filename part of the path and then I can just use the md command to make the empty directories. (I was not aware that md will create a full path, not just one folder.)

Code: [Select]set pathonly=%%~dpg
I could not find any hashing utility to my liking, so I wrote my own in C. It scans and verifies an entire directory tree. It uses OpenSSL for the md5 library. If anyone uses it, let me know of any problems because I just finished it.

Usage:
recmd5 [scan or verify] [name of hash file] [directory to scan (only include if using scan)]

When scanning, it will generate [NAME]_md5.log file in the current directory and that will contain all the hashes.
When verifying, it will generate [NAME]_md5_err.log containing all the corrupted and missing files.

http://www.filedropper.com/recmd5Don't use the link in the previous post. The compiler wasn't linking it right so I had to include the whole runtimes. I fixed it, so the standalone exe is attached.

[attachment deleted by admin to conserve space]I used a tool called fastsum in 2004 to verify my backups

Code: [Select]FastSum - extremely fast utility for your files INTEGRITY control.
FastSum calculates short and strong digests of your data via POPULAR MD5
algorithm to use it as references checksums for ulterior data integrity
verification.

FastSum - Allows to rectify the errors occurring while data transfer.
For example: Network transfers, CD-R and DVD burning and much more. It
is developed for easy processing of a huge files count and has usable
command-line interface. It is an analogue of a famous md5sum Unix
platform utility.

Using Fastsum

FastSum is a console application, it means that the parameters are set
from the command line. There are two basic modes: checksums calculation
- checksums are used as samples for ulterior verification of sample
values with the current ones to identify the integrity of files between
the verifications. The second mode is – verification mode. Parameters
have the following SYNTAX:

FSUM [Path] [File | /T:Type] [/C:File] [/V] [/O] [/R]

Quote

I used a tool called fastsum in 2004 to verify my backups

Looks like exactly what I needed.

Anyway, I need help with the script in the OP. It doesn't work if I type a folder with a space in the name. I tried surrounding it with quotes, but it still causes an error on the part of the code to delete files in backup. "The filename, directory name, or volume label syntax is incorrect." Can someone help with this?Test this:

Code: [Select]echo off
setLocal EnableDelayedExpansion
title Folder Sync System
color 0a
set backCMD=xcopy /c /f /d /e /h /i /r /y
set /p backPath=Enter the name of the folder to backup:
set "sourcePath=Z:\%backPath%"
set "backPath=%cd%%backPath%"

echo Backing up "%sourcePath%" to "%backPath%". . .
echo.

rem BACKUP THE FILES THAT HAVE BEEN CHANGED
echo %backCMD% "%sourcePath%" "%backPath%"
pause
%backCMD% "%sourcePath%" "%backPath%"
echo.Did you see the post above?Thanks for the help. I tried that and the deleting files part still doesn't work (the part after what you posted). The first part works fine with the quotes around it, but when I add quotes everywhere in the other part, it still doesn't work.

I added quotes around %backPath%, but it made no difference. There's no quotes around the echos because it doesn't MATTER. Here is the part that still doesn't work:
Code: [Select]rem CHECK FOR FILES THAT HAVE BEEN REMOVED FROM
rem THE SOURCE AND DELETE THEM FROM THE BACKUP DIRECTORY
for /r "%backPath%" %%g in (*.*) do (
set var=%%g
if not exist %sourcePath%!var:%backPath%=! (
echo File:!var!
echo.
del /f /q "!var!"
)
)

rem REMOVE ANY EMPTY DIRECTORIES FROM BACKUP
for /d /r "%backPath%" %%g in (*) do (
set var=%%g
if not exist "%sourcePath%!var:%backPath%=!" (
echo Dir:!var!
echo.
rd /s /q "!var!"
)
)
I didn't notice there were scrollbars so didn't see the rest of the code.

What errors do you see on the console?  Your changes look correct by adding quotes in the for commands but we can't see what changes are above it atm.

WRT the echo command - in general that variable also needs to be quoted in certain circumstances, such as when it contains an & or other poison characters.


You also removed the double quotes around this %sourcePath%!var:%backPath%=! Quote
You also removed the double quotes around this %sourcePath%!var:%backPath%=!

  WOW. Can't believe I didn't see that. That fixed the problem. I know the original had that, but I was making a lot of changes to the file.

Thanks for mentioning that.

BTW the error was:
"The filename, directory name, or volume label syntax is incorrect."

Um... One more thing. So now I want to replace the del command you see in the code with md and move. You can see what I want to do in this pseudo code:

md "%backPath%_DELETED\[path to file without name here]"
move "%backPath%[path to file]" "%backPath%_DELETED\[path to file]"

If it's not too complicated, could you help me with this? Thanks.Replace the top line with the lower block and run it with dummy test files to see what is echoed to the console. 

If it's right then close the window with the mouse and remove the 2 echo statements and the pause

Code: [Select]del /f /q "!var!"
Code: [Select]echo if not exist "%backPath%_DELETED%%~pg" md "%backPath%_DELETED%%~pg"
echo move "%%g" "%backPath%_DELETED%%~pg"
pause
I read your post, and I'll get to testing it when I can.
1005.

Solve : Manipulate Result of Function?

Answer»

I wrote out a routine a couple of weeks back that queries a server for a list of users and then resets the user's connection based on how long their session has been active/idle.  The long form of this script repeated many of the same commands in a For loop that contained an IF statement.

I decided to move many of the repeated commands to a function to simplify/optimize the script but in doing so I separated the "IF" commands from the "For" loop and now my script isn't working properly.  Obviously putting the script back together the way it was will solve the problem but I am hoping that there is something to be learned here.  So, this is a sample of what I had:

Code: [Select]For /f "tokens=1-8 delims=,:/ " %%A in ('query user ^| findstr /i /v "disc USERNAME"') Do (
::Set variables using the data from the query above
set name=%%A
set status=%%D
set idletime=%%E

        If /i %%E GTR 5 (
    Reset Session %%C
    Echo !ncol!!scol!!icol!!time! >>"%SessionLog%"
)
)

^ That works just fine.  This is what I changed it to:

Code: [Select] Call :_fn_FORMATTABLE
If /i !IDLETIME! GTR 5 (
Reset Session !SESSIONID!
Echo !ncol!!scol!!icol!!time! >>"%SessionLog%"
)


:_fn_FORMATTABLE
For /f "tokens=1-8 delims=,:/ " %%A in ('query user ^| findstr /i /v "> USERNAME"') Do (
::Set variables using the data from the query above
Set NAME=%%A
Set SESSION=%%B
Set SESSIONID=%%C
Set DIDLETIME=%%E:%%F
Set IDLETIME=%%E
Set LOGONTIME=%%H

Goto:EOF
)

Again, when the IF condition was inside the For/Do loop everything worked.  Also, the script doesn't fail as it is written now but because the SESSIONID variable isn't being looped through (I think), it only holds the last value assigned to it by the query that's made.  In other words there may be 40 user sessions that meet the condition of the "IF" statement but only one session is processed.  Is there a way to call a function like my :_fn_FORMATTABLE without having to output all of the values found for SESSIONID to a txt file for the "IF" statement to run against? I guess what I'm asking is if there is a way to continue the for/do loop that is in the function as if it is written with the "IF" statement?

Thanks for any help you can give me.  I really don't want to have to revert to setting variables and processing the same for/do command  4 separate times in my script.  Note that both the function and the older version of the script include many other variables that I set for formatting output to a log.  So while the code I included doesn't look so bad, it is several lines longer in both versions of my script.  It's not so bad when it's all lumped together in a function but the script gets hard to navigate when it repeats time and again in the body of the script.

MJYou may get a better result by providing the FULL script and someone who has the time and interest can analyse it and provide an optimised version, assuming it is achievable.

A problem with asking a question about a small segment is often that it is out of context - and the best solution may be entirely different when the context is known.

Foxidrive +1
You could have code in your script that may be affecting the environment without realizing it.OK guys, I can't remember a time when you've let me down so the entire script is below.  This version of the script is the one that I want to make work (as opposed to the previous version where the contents of the :_fn_FORMATTABLE function was written out in each ":__clearsessions_" section of the script and everything worked .  My problem with this version of the script is with the call to :_fn_FORMATTABLE.

Code: [Select]Cls
Echo Off
:: Created by: MJ
:: 11/13/2014
:: Description: Contains the tools and routines used to update and reboot  servers
:: Dependencies:  Script must be called from the Server Maintenance Menu script
:: Command Window Settings
Set SCRIPTITLE=REBOOT/UPDATE UTILITY
TITLE %SCRIPTITLE%
Color 9F
mode con cols=60 lines=18 >nul

::---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
:ENVIRONMENT
::Allows special updates to be installed/made during the regular server maintenance routine
Set URGENT=YES
::Direct the script to execute the process (routines in this script) that was selected on the Server Maintenance Menu
Set UChoice=%1
::Modifies logic to allow new copies of the "DeleteProfiles" components to be downloaded to the server
Set DelProUp=YES

setlocal enabledelayedexpansion
Set STAR=****************************************************************************
Set ShSTAR=********************************************
Set Line=--------------------------------------------------------
Set ShLine=---------------------------------------------
Set DLine========================================================
Set LogDLine===========================================================================
Set ShDLine=============================================
Set "spaces=                               "
Set "indent=     *"
Set CPUPath=\\domain-01\dfs$\k****k\users\k****k_matt\homedir\Scripts\==Program Updaters==\Adobe Java Updates
Set RepositoryPath=\\domain-01\dfs$\k****k\groups\ITadmin\Script Repository
Set SessionLog=\\%computername%\c$\Util\AutoReboot\Logs\[Recent]\%date:~10,4%%date:~4,2%%date:~7,2%_Session.log
Set ProgDir=\\%computername%\c$\Util\AutoReboot
:ENDENVIRONMENT
:DEPCHECK

:END DEPCHECK
:Start
If [%UChoice%]==[] Color 4E & Echo %SCRIPTITLE% & Echo %STAR% & Echo. & Echo. & Echo This script must be called from the Server Maintenance Menu script^^! & Echo. & Echo. & Echo %STAR% & timeout /t 3 >Nul & Goto End
If %UChoice%==1 Set PROCESS=REBOOTUP
If %UChoice%==2 Set PROCESS=REBOOTUP
If %UChoice%==3 Set PROCESS=___PCUT_Configure
If %UChoice%==5 Set PROCESS=___updates_WINDOWSUPDATE
If %UChoice%==6 Set PROCESS=___updates_HP
If %UChoice%==8 Set PROCESS=___updates_URGENT
Echo %SCRIPTITLE% & Echo %DLine% & Echo.
Goto %PROCESS%
:ENDStart

:REBOOTUP
:_rebootup_CONFIG
::WLBS
Call :_fn_WLBS
::Create Directories for logs and program files
If Not Exist "%ProgDir%\Logs\[Recent]\" md "%ProgDir%\Logs\[Recent]\" >Nul 2>&1
If Not Exist "%ProgDir%\Logs\Drain\" md "%ProgDir%\Logs\Drain\" >Nul 2>&1
If Not Exist "%ProgDir%\Logs\Session\" md "%ProgDir%\Logs\Session\" >Nul 2>&1
If Not Exist "%ProgDir%\Logs\WU\" md "%ProgDir%\Logs\WU\" >Nul 2>&1
If Not Exist "%ProgDir%\Logs\Profiles\" md "%ProgDir%\Logs\Profiles\" >Nul 2>&1
::**TEMPORARY**Move the contents of C:\Temp that was previously  home of the Reboot Utility's logs and program dependencies to C:\Util\AutoReboot
Move /Y "C:\temp\ProfileCleanup\Logs\*" "%ProgDir%\Logs\Profiles\" >Nul 2>&1
If Exist "C:\temp\AutoReboot" RD /s /q "C:\temp\AutoReboot"
If Exist "C:\temp\ProfileCleanup" RD /s /q "C:\temp\ProfileCleanup"
If Exist "C:\temp\Auto Reboot\" Move /Y "C:\temp\Auto Reboot\*" "C:\util\AutoReboot\Logs\Profiles\" >Nul 2>&1
If Exist "C:\temp\Auto Reboot\" RD /s /q "C:\temp\Auto Reboot\"
::**TEMPORARY**Remove the Auto Reboot folder.  The space in the name of this folder was causing problems with the script so it was replaced with the AutoReboot folder
If Exist "C:\util\Auto Reboot\" RD /s /q "C:\util\Auto Reboot\"
::All logging done by the Reboot_Update Utility is saved in C:\Util\AutoReboot\Logs\[Recent].  This folder shows all of the logs that were collected the last time the corresponding scripts ran and logs were collected.  The following routine moves these files into folders specific to their function, making room for another Set of the most recent logs.
If Exist "%ProgDir%\Logs\[Recent]\*WU.log" Move  /Y "%ProgDir%\Logs\[Recent]\*WU.log" "%ProgDir%\Logs\WU\" >Nul 2>&1
If Exist "%ProgDir%\Logs\[Recent]\*_Profiles.log" Move /Y "%ProgDir%\Logs\[Recent]\*_Profiles.log" "%ProgDir%\Logs\Profiles\"  >Nul 2>&1
If Exist "%ProgDir%\Logs\[Recent]\*_Session.log" Move /Y "%ProgDir%\Logs\[Recent]\*_Session.log" "%ProgDir%\Logs\Session\" >Nul 2>&1
If Exist "%ProgDir%\Logs\[Recent]\*_Drain.log" Move /Y "%ProgDir%\Logs\[Recent]\*_Drain.log" "%ProgDir%\Logs\Drain\" >Nul 2>&1
::Create the Session Reset log
Echo SESSION RESET LOG    %date% >>"%SessionLog%"
Echo %LogDLine% >>"%SessionLog%"
Echo. >>"%SessionLog%"
Echo       USER                 STATUS     IDLE TIME     RESET TIMESTAMP   >>"%SessionLog%"
Echo ---------------------     --------   -----------   -----------------   >>"%SessionLog%"
:_rebootup_INITIATE
Set /P=* Initiating the server reboot routine....... <Nul
timeout /t 2 >Nul & Echo Done^^! & Echo.
:__rebootup_CLEARSESSIONS
Set /P=* Searching %computername% for logged in users.... <Nul
Call :_fn_QUERYUSERS CLEARSESSIONS
:___clearsessions_DISCONSOLE
::Query the server for disconnected sessions and reset them
start "" tsadmin.msc
Set /P=* Resetting disconnected sessions............ <Nul
Call :_fn_FORMATTABLE
If /i !SESSIONID!==Disc (
Reset Session !SESSION!
Echo !ncol!!dscol!!icolnul!!time! >>"%SessionLog%"
)
If /i !SESSION!==Console (
LOGOFF !SESSIONID!
Echo !ncol!!dscol!!icolnul!!time! >>"%SessionLog%"
)
Echo Done^^! & timeout /t 2 >Nul
Call :_fn_QUERYUSERS

:___clearsessions_ACTIVE
call :_fn_MESSAGE 10
Echo %indent%-4-* Minute Countdown....
timeout /t 240 >Nul
:____active_LONGIDLE
Set /P=* Resetting Long Idle sessions .............. <Nul
Call :_fn_FORMATTABLE
If /i !LOGONTIME! LSS 32 (
Reset Session !SESSIONID!
Echo !ncol!!scol!!dicol!!time! >>"%SessionLog%"
)
Echo Done^^! & timeout /t 2 >Nul
Call :_fn_QUERYUSERS

:____active_SHORTIDLE
call :_fn_MESSAGE 5
Echo %indent%-4-* Minute Countdown....
timeout /t 240 >Nul
Set /P=* Resetting Short Idle sessions ............. <Nul
Call :_fn_FORMATTABLE
If /i !IDLETIME! GTR 5 (
Reset Session !SESSIONID!
Echo !ncol!!scol!!icol!!time! >>"%SessionLog%"
)
Echo Done^^! & timeout /t 2 >Nul
Call :_fn_QUERYUSERS

:____active_LOGOFF
Call :_fn_MESSAGE 2
Echo %indent%-2-* Minute Countdown....
timeout /t 120 >Nul
Set /P=* Logging off remaining sessions ............ <Nul
Call :_fn_FORMATTABLE
Logoff !SESSIONID!
Echo !ncol!!scol!!icol!!time! >>"%SessionLog%"
Echo Done^^! & Echo. & timeout /t 2 >Nul

:__rebootup_clearsessions_END
::Next 2 lines complete the logs. 
Echo. >>"%SessionLog%" & Echo. >>"%SessionLog%"
Echo %ShDLine%  >>"%SessionLog%"
:__rebootup_UPDATES
Call :_fn_WLBS
:___updates_URGENT
Set /P=* Installing URGENT updates.................. <Nul
start /wait Call "%RepositoryPath%\Scripts - Terminal Server\Printers\RemovePrinterBloat.bat"
start /wait Call "\\domain-01\dfs$\k****k\groups\ITadmin\Script Repository\Scripts - Terminal Server\Hotfix\KB2479710 (Remote Desktop Services)\KB2479710_Installer.bat" called
Echo Done^^! & timeout /t 2 >NUL
If %UChoice%==8 Goto END
If %UChoice%==1 Goto __rebootup_PCUT
:___updates_CPU
::Update Flash, Shockwave, Java, Adobe Reader, GotoMeeting
Set /P=* Installing Program Updates.................<Nul & PING -n 2 localhost >Nul
Start /wait Call "%CPUPath%\CoreProgramsUpdater.bat"
Echo Done^^!
:___updates_WINDOWSUPDATE
mode con cols=60 lines=10 >nul
Set /P=* Installing Windows Updates.................<Nul & PING -n 2 localhost >Nul
CScript "\\%computername%\c$\util\AutoReboot\wsusAutoUpdate.vbs" >NUL
Echo Done^^! & timeout /t 2 >NUL
:___updates_HP
Set /P=* Starting HP system updates................. <Nul
IPConfig /all | Findstr /I "Virtual Hyper-V" >Nul
If %ErrorLevel%==1 ("C:\Program Files\Internet Explorer\iexplore.exe" "https://127.0.0.1:2381/cgi-bin/vcagent/cgi") Else (Echo ***V-NIC detected.*** & Echo Press any key to continue after Windows updates are finished applying. & pause >Nul)
Echo Done^^! & timeout /t 2 >NUL
If %UChoice%==6 Goto END
:__rebootup_updates_END
:__rebootup_PCUT
:___PCUT_Configure
Set /P=* Configuring Profile Cleanup Task........... <Nul
If Not Exist "%ProgDir%\Logs\Profiles\" md "%ProgDir%\Logs\Profiles\"
If /I [%DelProUp%]==[YES] (
Del "%ProgDir%\Del*" /Q >NUL 2>&1
Del "%ProgDir%\Sch*" /Q >NUL 2>&1
Copy "%~dp0\LocalServerFiles\*" "%ProgDir%" /Y >Nul 2>&1
) Else (
For /f %%I in ('dir /b "%~dp0\LocalServerFiles" ^| findstr /i /b "del sched"') do If Not Exist "%ProgDir%\%%I" Copy "%~dp0\LocalServerFiles\%%I" "%ProgDir%" >Nul
)
Echo Done^^! & timeout /t 2 >NUL
:___PCUT_Run
::Part of the Reboot/Update routine.  Run an unattended, silent version of the Profile Cleanup tool.
If %Uchoice%==3 (
Start Call "%ProgDir%\DeleteProfiles.bat"
Goto END
) ELSE (
Set /P=* Scheduling the Profile Cleanup Task........ <Nul
Start /wait /min Call "%ProgDir%\ScheduleCleanup.bat"
Echo Done^^! & PING -n 2 localhost >Nul
Goto ENDROUTINE
)
:_rebootup_pcut_END
:ENDROUTINE
Endlocal
Set /P=* Configuring k****k Shutdown................ <Nul
If %computername%==TS155-101 If %UChoice%==1 (C:\temp\k****kShutdown\k****kShutdown.exe -REBOOT -REASON "Scheduled Reboot" -NODIALOG -NOCONFIRM >Nul) Else (C:\temp\k****kShutdown\k****kShutdown.exe -REBOOT -REASON "Scheduled Reboot / Windows Updates / Program Updates" -NODIALOG -NOCONFIRM >Nul)
If %UChoice%==1 (\\domain-01.com\dfs$\util\k****kShutdown\k****kShutdown.exe -REBOOT -REASON "Scheduled Reboot" -NODIALOG -NOCONFIRM >Nul) Else (\\domain-01.com\dfs$\util\k****kShutdown\k****kShutdown.exe -REBOOT -REASON "Scheduled Reboot / Windows Updates / Program Updates" -NODIALOG -NOCONFIRM >Nul)
Echo Done^^!
Goto END

:FN
::Functions
:_fn_QUERYUSERS
::pause
query user | findstr /i /v "> USERNAME" >Nul 2>&1
Set fnErrorLevel=%ErrorLevel%
If [%1]==[CLEARSESSIONS] (
Echo Done^^! & timeout /t 2 >Nul
If %fnErrorLevel%==1 Echo %indent% Users not found, moving on * & Echo N^/A >>"%SessionLog%" & Goto __rebootup_clearsessions_END
) Else (
If %fnErrorLevel%==1 Echo %indent% Add'l users not found, moving on * & Goto __rebootup_clearsessions_END
)
Goto:EOF
:_fn_FORMATTABLE
::Query the server for "active" users but exclude the account that is logged in to run this script.  This account is signified by the > symbol next to their name in the output of the query user command.  If there are no active sessions then the script will move past the CLEARSESSIONS segment
For /f "tokens=1-8 delims=,:/ " %%A in ('query user ^| findstr /i /v "> USERNAME"') Do (
::Set variables using the data from the query above
Set NAME=%%A
Set SESSION=%%B
Set SESSIONID=%%C
::If %1=disc (Set DSTATUS=%%C) Else (Set SESSIONID=%%C)
Set STATUS=%%D
Set DIDLETIME=%%E:%%F
Set IDLETIME=%%E
Set LOGONTIME=%%H
::Manipulate the variables captured above to display the data in column form in logs
Set ncol=!NAME!!spaces!
Set ncol=!ncol:~0,27!
Set dscol=!DSTATUS!!spaces!
Set dscol=!scol:~0,12!
Set scol=!STATUS!!spaces!
Set scol=!scol:~0,15!
Set icolnul=    -!spaces!
Set icolnul=!icolnul:~0,16!
Set dicol=!DIDLETIME!!spaces!
Set icol=!IDLETIME!!spaces!
Set icol=!icol:~0,13!
Goto:EOF
)
:_fn_MESSAGE
If %1==10 Set "WARNTIME=10" & Set MESSAGE="**SERVER REBOOT**  The server you are logged into is scheduled to be rebooted in the next 10 minutes.  Please save your work and log out of k****k (Start>Log Off).  When you log back in you will be directed to a server that does not need maintenance."
If %1==5 Set "WARNTIME=05" & Set MESSAGE="**SERVER REBOOT**  The server you are logged into will be rebooted in 5 minutes. UNSAVED WORK WILL BE LOST!  Please log out of k****k (Start>Log Off) immediately."
If %1==2 Set "WARNTIME=02" & Set MESSAGE="**SERVER REBOOT**  The server you are logged into will be rebooted momentarily. UNSAVED WORK WILL BE LOST!  Please log out of k****k (Start>Log Off) immediately."
Set /P=* %WARNTIME% Minute Warning^^! - Notifying users......<Nul & timeout /t 3 >Nul
::Query sessions for all active users except the user who is running this script and alert them that the server will be rebooting.
For /f "tokens=1-8 delims=,:/ " %%A in ('query user ^| findstr /i /v "> disc USERNAME"') Do msg %%C %MESSAGE%
Echo Done^^!
Goto:EOF

:_fn_WLBS
::Drain 2003 servers that are managed by WLBS. 
If Exist C:\WINDOWS\System32\wlbs.exe (
Set /P=WLBS is draining %computername% for 60 minutes....<Nul
CD C:\
wlbs drainstop >Nul & wlbs drainstop >Nul
\\domain-01.com\dfs$\util\k****kShutdown\k****kShutdown.exe -StartMaintenance 60 -Reason "Scheduled Maintenance"
Echo Done^!
)
Goto:EOF
:END
::popd
Exit

I'm open to any suggestions for improvements in the script since I'm certain that there's still plenty for me to learn.  But I'm most concerned with somehow making my calls to _fn_FORMATTABLE work - preferably without having to output the results of this function to a text file that I can reference in the :__rebootup_CLEARSESSIONS section of the script.

Thanks for the help.

MJshouldn't this be using the environmental variable %username%?
Code: [Select]findstr /i /v "> USERNAME" Quote from: powlaz on February 17, 2015, 07:48:38 AM

OK guys, I can't remember a time when you've let me down so the entire script is below.  This version of the script is the one that I want to make work

For a script that looks very convoluted, without good information about the script's function and how it is dependent on other scripts,
it's a huge job to analyse it.  Possibly impossible.

From what you've said the script doesn't work either.  That's adding an extra layer of impossible.Squashman - the heading of one of the columns returned by the command Code: [Select]query user is "Username".  I don't need the header row read which is why that's in there.
Otherwise, script aside or in theory, is it possible for a function to be called that will assign multiple different values (Value1, Value2, Value3, etc.)  to Variable-A and have every one of those values (Value1, Value2, Value3, etc.) represented by Variable-A used in another part of the script?

Thanks,

MJMy query user output does not have a > in front of the word USERNAME so I am not sure how your output is matching to skip the first line. I assumed you were trying to not match the current logged in user.
Code: [Select]C:\Users\squashman>query user
 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>squashman             console             1  Active      none   2/17/2015 3:54 PMIf you want to get rid of the header row then use SKIP=1 as an option with the FOR /F command.
Code: [Select]C:\Users\squashman>for /f "skip=1 delims=" %G in ('query user') do echo %G
>squashman                console             1  Active      none   2/17/2015 3:54 PMI finally realized what is wrong with your FINDSTR.  Since you are not using the /C option it tries to inversely match a ">" and the word "USERNAME".  Essentially you get no output!
Code: [Select]C:\Users\squashman>query user |findstr /i /v "> USERNAME"

C:\Users\squashman>I think I finally understand what you are trying to change your code to and NO it is not grabbing the last session.  It is grabbing the first session and then exiting because you have a GOTO :EOF inside the code block.

The way you are initially doing this is the correct way to do it.  I am not sure why you think splitting out part of a function into two separate functions would work.  You need to be able to TEST each user session so the best way to do that is to have the IF comparison within the function itself.

The only way to get it too work the way you want it too is to make the IF comparison another function that you call out to from the first function and you definitely do not want to do that.  Using the CALL command greatly decreases the speed of a batch file.  So multiple CALLS will really slow it down.

Now we could get into MACROS but that would blow your mind and we really do not discuss batch macros on this site like we do over on dostip.com.Thanks for your help guys.  I ELIMINATED the new function and the script is working again.  I have no idea what Macros are in Batch but I'm interested.  Maybe I'll see you on dostip.com

Thanks,

MJ Quote from: powlaz on February 17, 2015, 07:48:38 AM
OK guys, I can't remember a time when you've let me down so the entire script is below.  This version of the script is the one that I want to make work

In case my comment wasn't entirely clear - It seemed as though you asked for help to modify a working batch file
and in response to my request gave us a batch file that doesn't work.

That code also relies on so many external batch files that weren't provided, and little info about the task - that's why I suggested that it was impossible.
1006.

Solve : hi What are the three general ways that the type of data in a file?

Answer»

hi What are the THREE general WAYS that the type of data in a file can be identified?


I'll be locking all of your homework REQUESTS.

1007.

Solve : Detecting Filetype of Drag & Drop file?

Answer»

So i made a simple, little AAC to MP3 converter including the adding of MP3 Tags.
For this i use Faad (A part of FAAC), Lame & Tag

http://sourceforge.net/projects/faac/
http://www.rarewares.org/aac-decoders.php#faad2-win
http://lame.sourceforge.net/
http://www.synthetic-soul.co.uk/tag/

After writing the batch i however discovered that Faad2 is also capable of extracting the AAC from certain types of containers like MP4 files,  completely eliminating the need for me to extract those manually before feeding them to my batch.
Unless i don't have the MP4 to begin with but just the AAC file.

Sadly however this does cause an issue with my already written batch if i try to Drag & Drop a MP4 file on to the batch.

The batch i wrote renames the file created by Faad, the wav file, since it keeps the file extension of the AAC in the filename of the freshly created WAV file.
So for example; "Artist - Song.AAC" becomes "Artist - Song.AAC.WAV"

And Lame does the same with the freshly created MP3 file, that is then named "Artist - Song.WAV.MP3"

So to combat that i let it perform a rename after each process, after which Tag.exe adds tags to the MP3 and my MP3 file is done.

However when a MP4 file is dragged & dropped onto the batch instead of an AAC file.. the rename code, of course, fails.

Now the easy solution would be to created a seperate batch for MP4 files as well and use it along side the batch for the AAC files, but i'd vastly prefer to have all the code in 1 batch file instead.
So to ACCOMPLISH this i thought of letting the batch file detect what the filetype is of the file dropped onto it, and then to let it perform a GOTO to the part of the code for the AAC file and the MP4 file respectively.
I tried messing around with the IF command but to no avail.. I also tried the FOR command as well but i understand that command's capabilities even less.

So my QUESTION is simple; how do i make a batch file detect the filetype of whatever file is dragged & dropped onto it ?

Here's my code so far, please don't laugh as i'm no expert in how to utilize batch commands efficiently.

Code: [Select]ECHO OFF
color 81
:Original version by NiTeCr4Lr
:title AAC to MP3 CLI
faad -b 2 -l 2 -o %1.wav %1
title AAC to MP3 CLI
move /-Y %1.wav "C:\Program Files\AAC to MP3 CLI"
cls
ren *.aac.wav *.
ren *.aac *.wav
del %1
cls
lame -cbr -b320 -m j -q0 *.wav
del *.wav
ren *.wav.mp3 *.
ren *.wav *.mp3
Tag --auto --scheme "A - T" *.mp3
move /-Y *.mp3 "C:\Documents and Settings\NiTeCr4Lr\Bureaublad"
exit

Note:

Title after Faad since Faad hijackes the title of the Batch window and the title resets after Faad closes.

In addition, i realize the moving of the files seems inefficient but i let it do so since the shortcut to the batch file resides on my desktop, where more often than not a lot more AAC, MP4 & MP3 files reside as well. And i don't want my code touching any of those at all, especially not the "Del" part of the code
(Ok, ok.. It's also because somewhere in the code "%1" wouldn't work properly due to some path problem.. I'm very much a noob at using things like "%1" correctly.)

P.S. If anybody would be crazy enough to want to use my inefficient code to convert MP4/AAC files to MP3 files in a fairly cumbersome way, feel free to do so.
A thank you and a reference if posted elsewhere would however be appreciated. Quote

Drag & Drop a MP4 file on to the batch.
What does that mean?    Quote from: Geek-9pm on March 25, 2015, 11:56:55 PM
What does that mean?   

It means that if you have a batch file on your desktop, you then drag a MP4 or AAC file with your mouse and let the mouse button go (drop) it when it's on the batch file icon.
So the batch then takes the file and processes it.This modification should process the files - inside the same folder where the original files are and handle any supported extension.

If your executables are not on the path, then they will need the FULL location SPECIFIED to the files
- so if they are all located on the desktop then it should work with "%userprofile%\desktop\"


"%userprofile%\desktop\faad.exe" rest of the line
"%userprofile%\desktop\lame.exe" rest of the line
"%userprofile%\desktop\Tag.exe" rest of the line


and if they are elsewhere and you need a guide, then let us know where they are located.

This should also process more than one dragged file - one after another.
Test it with some sample files.

Code: [Select]echo off
:: Original version by NiTeCr4Lr
:: title AAC to MP3 CLI
title AAC to MP3 CLI
color 81
cls
:begin
pushd "%~dp1" || (echo error - the target folder "%~dp1" seems to be missing & pause & goto :EOF)
faad -b 2 -l 2 -o "%~n1.wav" "%~1"
lame -cbr -b320 -m j -q0 "%~n1.wav"
del "%~n1.wav"
Tag --auto --scheme "A - T" "%~n1.mp3"
move /-Y "%~n1.mp3" "C:\Documents and Settings\NiTeCr4Lr\Bureaublad"
popd
shift
if not "%~1"=="" goto :begin
Quote from: NiTeCr4Lr on March 25, 2015, 11:42:19 PM
The batch i wrote renames the file created by Faad, the wav file, since it keeps the file extension of the AAC in the filename of the freshly created WAV file.
So for example; "Artist - Song.AAC" becomes "Artist - Song.AAC.WAV"

And Lame does the same with the freshly created MP3 file, that is then named "Artist - Song.WAV.MP3"
No they do not.  As Foxidrive has pointed out in his code, you coded it that way! Quote from: Squashman on March 26, 2015, 08:05:45 AM
No they do not.  As Foxidrive has pointed out in his code, you coded it that way!

I figured i'd test what you said by dragging and dropping files on to Faad.exe & Lame.exe without the batch.
You're right about Faad, no file extension from the previous filetype in the new file's name.
With Lame however, you were right yet wrong :p

Since i've been using just the Lame part of the batch (no pun intended, that was bound to happen :p) for a couple of years now, my version of Lame is "3.98.2".
The version you probably tested (or know of by experience that it doesn't add the previous file extension ) is i'm guessing "3.99.5"
Since when i dropped a WAV file on the 3.99.5 version, it like Faad didn't include the previous extension anymore, yay!

However, after testing the difference between 3.98.2 and 3.99.5 it became clear i'd prefer to keep using the 3.98.2 version..
Under the same conditions with the same high quality parameters 3.98.2 took 36 seconds to encode a MP3 where 3.99.5 took 1 Minute & 15 Seconds.... Quote from: foxidrive on March 26, 2015, 07:14:54 AM
This modification should process the files - inside the same folder where the original files are and handle any supported extension.

If your executables are not on the path, then they will need the full location specified to the files
- so if they are all located on the desktop then it should work with "%userprofile%\desktop\"


"%userprofile%\desktop\faad.exe" rest of the line
"%userprofile%\desktop\lame.exe" rest of the line
"%userprofile%\desktop\Tag.exe" rest of the line


and if they are elsewhere and you need a guide, then let us know where they are located.

Thank you so much for your effort and time !
I indeed encounter a path issue.
The shortcut to the batch file is on my desktop but it links to the batch, and all the other files like faad, lame & tag, in the following path
"C:\Program Files\AAC to MP3 CLI"
(I like to keep all finished projects there :p)

I figured a simple chdir command at the beginning could fix that very easily..
Though, i saw the "%~dp1" you used at the pushd command, and since i'm not familiar with pushd
(it seems like a.. pipe? thing.. Something i've been wanting to use since before i started adding the AAC/Faad & Tag parts to the original code, which was only Lame encoding, but didn't have the know how for :p)

With some logical thinking i'm guessing the "%~dp1" take the d & p of "%1" right ?
So that's why it's stuck on my desktop ("Bureaublad" in Dutch) since "%1" is on there :p?

I'll wait for your reply before i start to mess around with the code of which those few new things i don't fully understand ..

I'm trying to confirm and learn from your code, though :p.
Also i'm guessing that "popd" is an 'off-switch' for "pushd" if you will  ?

I didn't even at all know about the Shift command and how it worked :p! I did a Shift/? seems handy ! Quote
Substitution of batch parameters (%n) has been enhanced.  You can
 now use the following optional syntax:

     %~1         - expands %1 removing any surrounding quotes (")
     %~f1        - expands %1 to a fully qualified path name
     %~d1        - expands %1 to a drive letter only
     %~p1        - expands %1 to a path only
     %~n1        - expands %1 to a file name only
     %~x1        - expands %1 to a file extension only
     %~s1        - expanded path contains short names only
     %~a1        - expands %1 to file attributes
     %~t1        - expands %1 to date/time of file
     %~z1        - expands %1 to size of file
     %~$PATH:1   - searches the directories listed in the PATH
                    environment variable and expands %1 to the fully
                    qualified name of the first one found.  If the
                    environment variable name is not defined or the
                    file is not found by the search, then this
                    modifier expands to the empty string

 The modifiers can be combined to get compound results:

     %~dp1       - expands %1 to a drive letter and path only
     %~nx1       - expands %1 to a file name and extension only
     %~dp$PATH:1 - searches the directories listed in the PATH
                    environment variable for %1 and expands to the
                    drive letter and path of the first one found.
From what you have said, all it needs is the change in the pushd command

It pushes a directory onto a stack, changes to it, and the popd pops it back off again as you gathered.
Pushd can have many levels but cd /d "C:\Program Files\AAC to MP3 CLI" will work here just as well
above the :begin label - and remove the pushd/popd lines.

Squashman has pointed out the useful help in the for /?

Code: [Select]echo off
:: Original version by NiTeCr4Lr
:: title AAC to MP3 CLI
title AAC to MP3 CLI
color 81
cls
:begin
pushd "C:\Program Files\AAC to MP3 CLI"
faad -b 2 -l 2 -o "%~n1.wav" "%~1"
lame -cbr -b320 -m j -q0 "%~n1.wav"
del "%~n1.wav"
Tag --auto --scheme "A - T" "%~n1.mp3"
move /-Y "%~n1.mp3" "C:\Documents and Settings\NiTeCr4Lr\Bureaublad"
popd
shift
if not "%~1"=="" goto :begin
Quote from: Squashman on March 26, 2015, 12:54:31 PM

Using the code supplied by foxidrive i don't get how to adjust that even with the info in Squashman's post in order to get it to get it to run for the path "C:\Program Files\AAC to MP3 CLI" instead of the desktop ..

Maybe i'm having a senior moment right now, very likely in fact Quote from: NiTeCr4Lr on March 26, 2015, 09:46:27 PM
i don't get how to adjust that to get it to run for the path "C:\Program Files\AAC to MP3 CLI" instead of the desktop ..

The most recent post runs from that folder - the pushd command changes the folder to "C:\Program Files\AAC to MP3 CLI"

Did it do something odd when you tried it? Quote from: foxidrive on March 26, 2015, 06:55:13 PM
From what you have said, all it needs is the change in the pushd command

It pushes a directory onto a stack, changes to it, and the popd pops it back off again as you gathered.
Pushd can have many levels but cd /d "C:\Program Files\AAC to MP3 CLI" will work here just as well
above the :begin label - and remove the pushd/popd lines.

Squashman has pointed out the useful help in the for /?

Code: [Select]

I don't know what a stack is in this form of terminology but if it works i'm not complaining :p
 
Quote from: foxidrive on March 27, 2015, 03:48:54 AM
The most recent post runs from that folder - the pushd command changes the folder to "C:\Program Files\AAC to MP3 CLI"

Did it do something odd when you tried it?

Sorry, i had posted that post before i saw that you had posted ! My bad.

I tried the new code and apart from the title being "FAAD" after Faad was already done and Lame had it's turn, it stopped at copying the mp3 back to "Bureaublad" because it couldn't find the MP3 due to it still having the WAV extension in it's title after Lame was done.
(So the whole before mentioned in another post "Artist - Song.WAV.MP3" ..)

The title is easily fixed by adding that after the Faad line again, but the filetype extension in new file name issue i do not know how to address efficiently while keeping your code night and tight :p..
So apart from using that old bit of code of mine "ren *.wav.mp3 *." and then "ren *.wav *.mp3" how could i address that ?Can you test this version and mark/copy/paste the text on the screen into a reply, when it pauses?
The messages on the screen help to follow what is going wrong.

Code: [Select]echo off
:: Original version by NiTeCr4Lr
:: title AAC to MP3 CLI
title AAC to MP3 CLI
color 81
cls
:begin
pushd "C:\Program Files\AAC to MP3 CLI"
faad -b 2 -l 2 -o "%~n1.wav" "%~1"
lame -cbr -b320 -m j -q0 "%~n1.wav"
del "%~n1.wav"
Tag --auto --scheme "A - T" "%~n1.mp3"
cls
move /-Y "%~n1.mp3" "C:\Documents and Settings\NiTeCr4Lr\Bureaublad"
dir /b "%~n1*"
pause
popd
shift
if not "%~1"=="" goto :beginHere's the marked, copied & pasted text displayed

"Het systeem kan het opgegeven bestand NIET vinden.
Test.wav.mp3
Druk op een toets om door te gaan. . ."

Which translated says:
"System can't find the ..given.. file.
Test.wav.mp3
Press a key to continue..."

So like i said in the post before, it's that whole "filetype extension in new file name issue"

Lame still puts out "Artist - Song.WAV.MP3" instead of "Artist - Song.MP3" because i use the 3.98.2 version of Lame which takes less than 50% of the time than the "3.99.5" version does without losing any noticeable quality, but does put out with the wav extension in the new file new sadly..

Quote from: NiTeCr4Lr on March 27, 2015, 02:02:47 PM
The filetype extension in new file name issue i do not know how to address efficiently while keeping your code night and tight :p..
So apart from using that old bit of code of mine "ren *.wav.mp3 *." and then "ren *.wav *.mp3" ...
Before I load that release of lame and test it - try this and see what it shows.

BTW, where are the LAME binary files for Windows?  The link you posted looks to only be for the source code.

Code: [Select]echo off
:: Original version by NiTeCr4Lr
:: title AAC to MP3 CLI
title AAC to MP3 CLI
color 81
cls
:begin
pushd "C:\Program Files\AAC to MP3 CLI"
faad -b 2 -l 2 -o "%~n1" "%~1"
lame -cbr -b320 -m j -q0 "%~n1"
del "%~n1"
Tag --auto --scheme "A - T" "%~n1.mp3"
move /-Y "%~n1.mp3" "C:\Documents and Settings\NiTeCr4Lr\Bureaublad"
popd
shift
if not "%~1"=="" goto :begin
1008.

Solve : Collect the share folder and file path and disk size usage?

Answer»

Dear All,

I want to use the batch to collect share folder , sub-directory and file path , disk usage from the server in Domain. 
I try to use diruse from support tool but it is not fit my expectation.

My format is one column

Total Number of folders , TotalNumber of files, Total number of file and folders usage in MB

Please kindly help me what is batch or script can get such information at that way.

Thanks,
Alfred Quote from: sun_os on March 25, 2015, 03:02:54 AM

I want to use the batch to collect share folder

Is this a mapped drive?  How is the server accessed?  Does it require authentication for the user?

Quote
My format is one column

Total Number of folders , TotalNumber of files, Total number of file and folders usage in MB

What kind of MB do you expect?  1,000,000 bytes = 1 MB ?

If the number of files and folder over a LAN are huge, then this could be a very slow task. 
Have you considered that?Yes, MB = 1 MB capacity in MB

Just want to check the number of folder on the share drives

Let me take example , I have the server to be share HOME Drive

I want to get some information how many folders and files are in the home drive.  How many those files and folders in usage

I just want to know the script or command in window

I use diruse to get such information , but it is not enough

Do you access the drive with a drive letter? 

EG: do you use H: to access the home drive?

Can you give an example of the output you need, showing a few lines of numbers etc?
Does it need to be formatted in a special way with tabs or padded columns etc?I just UPLOAD the result layout for your reference

I use diruse and dir /s/b /a:d to search total no. of files, share drive usage and no. of folders and subfolders information.

I m admin so I can access all the share drive. I run the command on the target server to get such information.

Thank you

[attachment deleted by admin to conserve space]The answers you've given to my questions are unclear, and not really what I've asked.

The task should be fairly easy, but without the info I have asked you for - you may come back
and say it doesn't work or you want something different - and it's no fun having to do things twice
just because the task isn't well described.

Nowhere has an excel file been mentioned...Hi

I use the share drive on D:HOME

I just want to get the such spreedsheet information by script.

diruse  ; Show the total size of folder and number of files but not show to number of subfolder

    Size (mb)  Files  Directory
        24.18    102  C:\SUPPORT_TOOLS
         3.20      3  C:\SUPPORT_TOOLS\ProcessExploreNT
        27.38    105  SUB-TOTAL: C:\SUPPORT_TOOLS

dir /s/b/a:d : Show the number of folder and subfolders as well
C:\support_tools\ProcessExploreNT

dir /s/b /a:d

        27.38    105  TOTAL: C:\SUPPORT_TOOLSYou can have the data in a .csv file

This is not thoroughly tested - see how it works for you.

Code: [Select]echo off
(
echo TOT_FOLDERS,TOT_FILES,TOT_SIZE,FOLDER
rem parse each folder
for /f "DELIMS=" %%a in ('dir /a:d /o:n /b /-p') do (
rem collect files
for /f "delims=" %%b in ('dir "%%a" /b /s /-p /a-d ^|find /c /v ""') do (
rem collect folders
for /f "delims=" %%c in ('dir "%%a" /b /s /-p /ad  ^|find /c /v ""') do (
rem collect total size
for /f "tokens=2,*" %%d in ('dir "%%a" /s /-p ^|find " File(s) " ') do set totalsize=%%e
setlocal enabledelayedexpansion
echo %%c,%%b,"!totalsize!","%%~fa"
endlocal
)
)
)
)>"total.csv"
Thank you for your effort to build the code for me

I check the output , it can't show the total file size and folder size

May I know is it something wrong on the command



[attachment deleted by admin to conserve space] Quote from: sun_os on March 28, 2015, 11:19:56 PM
Thank you for your effort to build the code for me
I check the output , it can't show the total file size and folder size
May I know is it something wrong on the command

I'm guessing that your Windows is not an English build.

This is what I see here in a test:

TOT_FOLDERS,TOT_FILES,TOT_SIZE,FOLDER
0,8,"11,796,480 bytes","d:\Backup\Vox\Images"
21,58,"52,505,656,317 bytes","d:\Backup\Vox\Machines"
Hi,

My domain window are built in the English version Quote from: sun_os on March 29, 2015, 07:59:09 PM
My domain window are built in the English version

I'm afraid I don't know what your domain window is.

On the computer you are launching the batch script on,  please open a cmd prompt and type the command
dir and then copy and paste the bottom 12 lines or so into a reply
 - so I can isolate where the problem is.I run the bat file on the server, it can get the result, but the some share folder contain  chinese file name and long file name. It outputs the file is too long. It is not my expectation for such situation on the END users to save in long chinese file name

Sorry I don't mention that ISSUES from share drive   

[attachment deleted by admin to conserve space]
1009.

Solve : If you were examining the data appearance of a file at a HEX level ? help?

Answer»

If you were examining the data appearance of a file at a HEX level how MIGHT you distinguish a compressed file from a GRAPHICAL IMAGE file?


Homework request locked.

1010.

Solve : Windows Backup Cleanup Bat?

Answer»

Hi

Im looking for help in creating a BAT file to remove old backups from a Windows server 2008 Windows backup set. I was THINKING of using Diskshadow command to remove some old shadow copies. Does anyone have any advice or any other methods of doing this?LOOKS like the RIGHT way to do it.  Looks pretty straight forward.  You can create a script file with all the commands and it looks like you just NEED to use the DELETE Shadows option.

https://technet.microsoft.com/en-us/library/cc772172.aspx
https://technet.microsoft.com/en-us/library/cc754915.aspx

1011.

Solve : Use Full path in For Loop?

Answer»

Hi, I'm been have trouble trying to use the folder path instead of pushd. If possible, I would like to use  the full path in the for loop instead of using the PUSHD command.

Code: [Select]echo on

pushd "\\klpr32\new folder\" && (
for %%a in (*) do (
if not exist "\\klpr32\new folder\newfiles\%%~na.txt" for %%b in ("%%~na.*") do type "%%b" >>"\\klpr32\new folder\newfiles\%%~na.txt"
)
popd
)

Not understanding your question.
Ditto...Me also.  EXPLAIN in Engerlish what the aim of the task is. Quote from: foxidrive on April 07, 2015, 06:55:16 PM

Me also.  Explain in Engerlish what the aim of the task is.
I would EVEN ACCEPT Igpay AtinlayThis might infest your bed with bugs and drink your last dram of liquor, but it's a guess at what you want to do.

Giving a clear explanation is far better than posting code that doesn't work - because broken code with no clear explanation is like giving your Ikea assembler every odd number page of the plans for your Ikea widget, and burning the even numbered pages.  It's a good thing that they get paid by the hour.

Code: [Select]echo off
for %%a in ("\\klpr32\new folder\*") do (
   PROCESSING "%%~a"
 ECHO  if not exist "%%~dpa\newfiles\%%~na.txt" copy /b "%%~na.*" "%%~dpa\newfiles\%%~na.txt"
)
pause

Even Latin PIGS are accepted legal tender here.
1012.

Solve : Batch not quite working right?????

Answer»

Hi All,

I thought I would start a new post.  I'm new to batch but learning quickly.

The below batch only partially WORKS for me. When running the batch if you hit enter without adding a client name it will add the next folder in sequence, which is fine. But when you enter a client name which is what I want to do every time, the first outcome is correct, e.g. the next available folder number with the client name following, 15-P0015 Brown for example. But, if you run it again you get 15-P0015 Green for example, instead of 15-P0016 Green.

Can anyone help me, I just can't FIGURE it out!!
Thanks a lot in advance for any help provided



echo off
setlocal enableDelayedExpansion
cd /d C:\Users\jbrown\Desktop\Test
set I=2
:NextI
if /I %I% LEQ 999 set II=0%I%
if /I %I% LEQ 99 set II=00%I%
if /I %I% LEQ 9 set II=000%I%
if not exist "15-P!II!" (
    set /p "client_name=OPTIONAL Enter a client name and press : "

    xcopy /s /e /i "15-P0000-Template" "15-P!II!!client_name!"
    goto :eof
)
set /a I+=1
if /i %I% LSS 999 goto NextI
)




[attachment deleted by admin to conserve space]echo off
setlocal enableDelayedExpansion
cd /d D:\Test
set I=2
:NextI
if /I %I% LEQ 999 set II=0%I%
if /I %I% LEQ 99 set II=00%I%
if /I %I% LEQ 9 set II=000%I%
if not exist "15-P!II!" (
    set /p "client_name=OPTIONAL Enter a client name and press <ENTER>: "

    xcopy /s /e /i "15-P0000-Template" "15-P!II!!client_name!"
    goto :eof
)
set /a I+=1
if /i %I% LSS 999 goto NextI
) <----------- Why is this here?

Not sure??  I asked someone way BACK for some help and he said that would work??Is it the same answer for this?

echo off
setlocal enableDelayedExpansion
cd /d C:\Users\jbrown\Desktop\Test
set I=2
:NextI
if /I %I% LEQ 999 set II=0%I%
if /I %I% LEQ 99 set II=00%I%
if /I %I% LEQ 9 set II=000%I%
if not exist "15-P!II!" (
    set /p "client_name=OPTIONAL Enter a client name and press <ENTER>: "

    xcopy /s /e /i "15-P0000-Template" "15-P!II!!client_name!"
    goto :eof <----------- Why is this here?
)
set /a I+=1
if /i %I% LSS 999 goto NextI
)
Yes. As I said I'm new to batch but really trying to understand, but I just can't figure out how to make it work the way I want.

Thanks I think you might now know which lines to remove.
Yes, but even with them removed the same problem is still there??  The batch still only works correctly for the first time EG: 15-P0002 Test but when run again using testing as the next name the out put is 15-P0002 testing instead of 15-P0003 testing.

echo off
setlocal enableDelayedExpansion
cd /d C:\Users\jbrown\Desktop\Test
set I=2
:NextI
if /I %I% LEQ 999 set II=0%I%
if /I %I% LEQ 99 set II=00%I%
if /I %I% LEQ 9 set II=000%I%
if not exist "15-P!II!" (
    set /p "client_name=OPTIONAL Enter a client name and press : "

    xcopy /s /e /i "15-P0000-Template" "15-P!II!!client_name!"
)
set /a I+=1
if /i %I% LSS 999 goto NextIOPTIONAL Enter a client name and press <ENTER>: test
xcopy /s /e /i "15-P0000-Template" "15-P0002test"
OPTIONAL Enter a client name and press <ENTER>: testing
xcopy /s /e /i "15-P0000-Template" "15-P0003testing"
Sorry, I don't follow what you are saying??  Capture.jpeg shows the result I get when I run the program 3 times adding 3 different names.  Capture 2.jpeg shows the result that I am looking for.

[attachment deleted by admin to conserve space]Read what I posted. Is it what you want to happen?
Sorry, yes exactly!I deleted the 2 lines which I have previously indicated.
Yes that works until you close it and then reopen the batch.   It then STARTS from the beginning number instead of the next in the sequence? Of course it will! How can it know about previous runs? You have hard coded the start number (set I=2).

OF COURSE!!!!!  Now I get it.  Thanks a million for all of your help

1013.

Solve : NT4 and %date% and %time% issue?

Answer»

I wrote a simple batch file that keeps track of when specific events happen... that is if it worked correctly. Problem is that the log file is only showing the text with no date or time info.

An instruction as simple as

echo. Run on %date% at %time% >>RunLog.log


The log file is only showing

Run on   at

Tried using echo off instead of the echo. and get the same results. i was thinking at first that it was because NT4 had an issue with echo. vs Echo off, where with echo off used I simply just echo the info and append it to log file.

Not quite sure why this is happening as for I didnt think that NT4 would have a problem with this.

Any ideas of whats going wrong or suggestions on how to fix?

Its been years since I have had to make a batch file for NT4 and I dont recall NT4 having any issues like this one  %date% and %time% weren't available natively in NT4, they came in with Windows 2000, but you can use FOR to parse the outputs of date/t and time/t.

These may work depending on your regional settings (date & time format)

FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO set date=%%B

FOR /F "TOKENS=*" %%A IN ('TIME/T') DO SET time=%%A

See here

http://www.robvanderwoude.com/datetiment.php#SetTime
Thanks Salmon for help with this.

Going to use these methods instead then. Its been almost 15 years since I have had to support a NT4 system, since when 2000 Pro/Server came out that was the hottest OS to run for corporate MS Workstation/Servers and NT4 was changed out rather quickly to 2000 with far more features and far better driver support etc. But this NT4 system remained. 

 SADLY we have a system that has to specifically run NT4 SP6 on and old Pentium III on a machine that was built in 1996, when for what it runs and does I dont see why it couldnt be upgraded to XP ( for newest OS with BEST support for legacy 16-bit programs ), but its a system at work and I am only given the privilege to support it without any unapproved by engineering etc modifications, however I can log activity of systems with scripts etc, and I am trying to pinpoint an oddity with a system and this system in addition to sending instructions to PLC's and other systems, also passes data into a MySQL DB, however the data gathered doesnt specify when specific actions are taken and so I have specific functions that call out for an executable outside of the main executable hitting the batch file before running the executable.  I then can look at the log see when something was run and then hit the database looking at a smaller window of time vs looking at an entire 16 hour run.  Quote from: DaveLembke on April 11, 2015, 09:29:39 AM

I wrote a simple batch file that keeps track of when specific events happen... that is if it worked correctly. Problem is that the log file is only showing the text with no date or time info.

Any ideas of whats going wrong or suggestions on how to fix?


Salmon has the answer, but it's likely to be a 32 bit system I gather so this may work to get reliable date and time info:

Code: [Select]:: date time using an ascii binary
echo off
:: Code by Herbert Kleebauer
echo [email protected]`0X-`/PPPPPPa(DE(DM(DO(Dh(Ls(Lu(LX(LeZRR]EEEUYRX2Dx=>d_t.com
echo 0DxFP,0Xx.t0P,[email protected]$?PIyU WwX0GwUY Wv;ovBX2Gv0ExGIuht6>>d_t.com
echo LisqMz`[email protected]`[email protected]?ogBgGG}G?j_egoNOG?w?`gBLksqgG`w?WgBgG>>d_t.com
echo G}[email protected][email protected]`LrFuBLyt~vuco{LuKooD?BFHqrIcP>>d_t.com
echo _sdDxb1T??=?rILO_sdDqx1T??=?rILO_sdDnl1T??=?rILO_sdD`c1T??>>d_t.com
echo =?rILO_sdDgg1T??=?rILO_sdDll1T??=?rILO_sdDrr1T??=??IL?0xxx>>d_t.com

d_t.com>d_t.bat
call d_t.bat
del d_t.com
del d_t.bat

echo century: %_cy%
echo    year: %_yr%
echo   month: %_mo%
echo     day: %_da%
echo    hour: %_hh%
echo  minute: %_mm%
echo  second: %_ss%
I wonder what a corporate IT department might have to say about scripts that inject binary code of unknown provenance?

Quote from: Salmon Trout on April 15, 2015, 01:05:14 PM
I wonder what a corporate IT department might have to say about scripts that inject binary code of unknown provenance?

That's always a good question.

I'd also like to know what security updates and precautions are taken on a LAN connected machine that was mothballed when Adam had his first child. Quote
I'd also like to know what security updates and precautions are taken on a LAN connected machine that was mothballed when Adam had his first child.

This system running NT4 is private LAN with no connection to internet. The fact that it is SP6 vs SP0 is probably to support a feature or code that is run on it. This system was implemented here long before I started in 2009. We even have some systems running OpenVMS on old DEC Alpha 64-bit systems. I asked why not replace 20 year old hardware/systems, and I was told that the cost was in the tens of millions for nation wide and the 20 year old DEC Alpha's are surprisingly very reliable running 24/7/365 for last 20 years. They are definitely getting their moneys worth out of this hardware. Quote from: DaveLembke on April 16, 2015, 11:00:36 AM
I asked why not replace 20 year old hardware/systems
Businesses do not replace systems because they are old. They replace systems when they can no LONGER do business with them. I think that is one thing that sometimes isn't fully understood when we see a Text-terminal at an airport or at a grocery store. Especially considering the human cost- now Stacey, who has been working there for 15 years, has to dump her muscle memory and start over with some new-fangled windows program.

Only tangentially related, I suppose. Those OpenVMS systems, THOUGH, are probably running software- replacing them means funding equivalent software for the new system. Was it contracted? who made it? How quickly can a replacement be made? How much will it cost- etc. And the answer will always be that continuing to use the current systems will be cheaper than upgrading them.There are companies that specialize in supporting organisations that are dependent on legacy hardware & software. One I was looking at says their support includes  Alpha, Sun Microsystems and VAX servers. I guess there must be lots of this kind of stuff around.
1014.

Solve : Seek help on how to use this batch file...?

Answer»

Hi there,

Yes a nube with very little experience so I am seeking help.  Here's some background info:

I have a python script 'gdalcopyproj.py' (I did not write it), and it works great.  Basically it takes a tiff geo-referenced image file and transfers that information into ANOTHER tiff image that does not have geo-referenced data.

The script is written to apply this one file at a time "gdalcopyproj.py source_file dest_file".  One uses it inside the command prompt of a program called OSGeo4W to implement the script.  For example, it looks like so in the command window.

“C:\OSGeo4W>python gdalcopyproj.py SOCAL_CZ62.tif SOCAL_CZ62_LM.tif”

My goal is to process a whole folder of files at once.  I do have a batch file that has been created for another user.  Appears to be somewhat custom for his needs. Here is that batch file:

ECHO OFF
SETLOCAL EnableDelayedExpansion
for /f "delims=" %%i in ('2^>nul dir/a-d/b .tif^| findstr/i "^......\.tif$"') do (
for /f "delims=" %%j in ('2^>nul dir/a-d/b "%%~ni_*.tif"') do (
gdalcopyproj.py "%%i" "%%j"
)
)

What I do not understand is how to use/setup this batch file.  It appears to be seeking a certain type of file which has six characters and converts similarly named files which have custom filenames after the “_”.  Is this correct?  Can I customized that to fit my needs?

Second, where does one put this batch file.  I have tried in the same folder as the files. I have tried in the directory of OSGeo4W but no luck.  I have tried running the batch directly or from inside a command window.  Still no luck.  Either I get an error message or simply nothing happens.  This where I am stuck.

Can someone explain how to use this batch file somewhat step-by-step?

Clutch

P.S. – not sure if you need the python script to help explain but here she is:


try:
    from osgeo import gdal
except ImportError:
    import gdal
import sys
if len(sys.argv) < 3:
    print("USAGE: gdalcopyproj.py source_file dest_file")
    sys.exit(1)
input = sys.argv[1]
dataset = gdal.Open( input )
if dataset is None:
    print('Unable to open', input, 'for reading')
    sys.exit(1)
projection   = dataset.GetProjection()
geotransform = dataset.GetGeoTransform()
if projection is None and geotransform is None:
    print('No projection or geotransform found on file' + input)
    sys.exit(1)
output = sys.argv[2]
dataset2 = gdal.Open( output, gdal.GA_Update )
if dataset2 is None:
    print('Unable to open', output, 'for writing')
    sys.exit(1)
if geotransform is not None and geotransform != (0,1,0,0,0,1):
    dataset2.SetGeoTransform( geotransform )
if projection is not None and projection != '':
    dataset2.SetProjection( projection )
gcp_count = dataset.GetGCPs()
if gcp_count != 0:
    dataset2.SetGCPs( gcp_count, dataset.GetGCPProjection() )
dataset = None
dataset2 = None


P.S.S -  Here is even another batch file for the same purpose if this helps but still no luck... sorry coding is not my best suit.  Appears this one would take any file name up to the point of a "_"?  am I understanding this correct?

echo off
for /f "delims=" %%a in ('dir /b *.tif ^| findstr /v /c:"_.tif"') do gdalcopyproj.py "%%~a" "%%~na_.tif"Not sure what your first batch file is doing, but try modifying your second one as such:
Code: [Select]echo off
for /f "delims=" %%a in ('dir /a-d /b *.tif ^| find /v "_." ') do python gdalcopyproj.py "%%~a" "%%~na_.tif"

the segment 'for /f "delims=" %%A in () do' tells the program to loop through the list in the parenthesis.  In this case that is 'dir /a-d /b *.tif ^| find /v "_."' which is a list of everything in the current directory, excluding files whose names contain the string "_." and folders.  For each of these, it will run the command 'python gdalcopyproj.py "%%~a" "%%~na_.tif"' where %%~a is replaced with each thing in the list, and %%~na is replaced with only that file's name.

If you run into the problem where nothing shows up, try removing the "echo off" at the beginning and post the screen.  (you can do this by right clicking and using the 'mark' function)Hey Lemonilla,

Thank you so much for taking a stab at this.  Tried a few times without success so let me give you a play-by-play:

Created a folder on my S: drive called Geotest.  In there I placed two files: ALBQ_T20.tif (CONTAINS geo info), and a second file ALBQ_T20_SH.tiff (which contains no geo info).  I placed your bat file there and ran it.  I got a quick "blip" of the command window but then nothing.  Same thing happens if I remove the ECHO off text.  No difference.

2nd test.  I moved the tiff files and the bat file into the C:\OSGeo4W directory.  Same thing happens there as well.  Are my filenames different than what you expected them to be?


Adding a 'pause' command at the end of a batch file is a good way to debug it.  If you wouldn't mind, remove "echo off" and put the pause at the end and paste the error message it gives.  This can also be accomplished by running the batch file from a cmd.exe window (command prompt window).

When I run the program (with a slight edit) it looks like it should run.  Try running the below outside of the batch file and see if there is a syntax error in calling the python script.
Code: [Select]python gdalcopyproj.py "ALBQ_T20.tif" "ALBQ_T20_.tif"


Code: (my code) [Select]echo off
for /f "delims=" %%a in ('dir /a-d /b *.tif ^| find /v "_." ') do (
REM by changing ".tif" to "%%~xa" we are maintaining the exact extension of the previous file.
REM e.g. if we call it on a .tiff file instead of .tif, it will maintain the double f at the end
REM the 'echo' is there for debugging purposes only, it shows me how the python script will be called, but bypasses the actual execution
echo python gdalcopyproj.py "%%~a" "%%~na_%%~xa"
)
pause
Code: (output) [Select]python gdalcopyproj.py "ALBQ_T20.tif" "ALBQ_T20_.tif"
python gdalcopyproj.py "ALBQ_T20_SH.tiff" "ALBQ_T20_SH_.tiff"
Press any key to continue . . .



EDIT: You might try removing the quotes around the file names, that might be messing with your python script.  Just know then that your file names cannot have spaces or they will be interpreted as new arguments.Oh look!  Somebody else with exactly the same question!  What are the odds??

http://www.dostips.com/forum/viewtopic.php?f=3&t=6409 Quote from: foxidrive on April 18, 2015, 02:15:27 AM

Oh look!  Somebody else with exactly the same question!  What are the odds??

http://www.dostips.com/forum/viewtopic.php?f=3&t=6409
At least he appears to be sharing information between the two.  Can't fault him for covering his bases.Hey, I am back.  Got tied up with a few other pressing issues.  Yes, I did post this issue at a few different forums.  Looking for options.

Here is what I did with your latest script.  Called it T2GT-CH.bat.  I placed this in a workfolder I call Geotest along with the python script and the files I wish to process.  They were the following files:

ALBQ_T20.tif                (has the geo info I need)
ALBQ_T20_BM.tif         (needs geo info)
ALBQ_T20_LM.tif          (needs geo info)
ALBQ_T20_WM.tif        (needs geo info)

I tried running your bat inside the regular command window and also tried this using the OSGeo4W command window and had the same results.  Nothing was processed.  This was in the command window:

S:\WORKFOLDER\Geotest>T2GT-CH.bat
gdalcopyproj.py "ALBQ_T20.tif" "ALBQ_T20_.tif"
gdalcopyproj.py "ALBQ_T20_BM.tif" "ALBQ_T20_BM_.tif"
gdgdalcopyproj.py "ALBQ_T20_LM.tif" "ALBQ_T20_LM_.tif"
gdalcopyproj.py "ALBQ_T20_WM.tif" "ALBQ_T20_WM_.tif"
press any key to continue...

An Update - the author of the original bat got back to me and I do have his bat file working.  You weren't sure what he was up to with his file?  I noticed there were some emoticons in there in this post for the "", was that why?  Anywho, that was so he could determine how many characters for the filename to search for.  I changed that number to match mine and the "....." as well.  I placed that bat file in the same folder as the files to process along with the python script.  Opening the OSGeo4W command window and to the path of the bat I was able to process successfully.

But I like your idea in your bat file of changing the finished file to signify a change, the "_".  Tell me, could that be optional say I want to add a small "g" at the end rather than a "_"?    So That is why I am still trying to get you bat to work... or maybe just change his to add an optional character at the end?

ClutchIt didn't process anything because I put a print statement to make sure you got the output you wanted before you messed with your files (It's a common batch practice). If the output are the commands you want to run, remove the 'echo' in the 6th line.

Yes, you can use g instead of _, but it won't work as well, as it will then not process anything that ends in a g.  This however could end up being a file you want processed.  Instead, I'd do a '_g' if you still want the g.  To do this, simply change all instances of _ to _g in my code. (even the one in line 6).

I'm glad you got it working though.
Quote from: Clutch Cargo on April 20, 2015, 11:27:34 AM
Hey, I am back.  Got tied up with a few other pressing issues.  Yes, I did post this issue at a few different forums.  Looking for options.

Those of us that recall how to use the T word, and why giving feedback to your question is important, simply shake their head.

Maybe the younger people think all this is typed by AI bots and there isn't a real person answering at all.

HI foxidrive,

Not sure I understand your last?  Did I do something incorrect here?  What is the "T" word?Hi Lemonilla,

An update.  I removed the "echo" as you instructed.  It would not process.  So I added "python" in front of the gdalcopyproj.py and there it appears it tried to process but got the following error message:

<'Unable to open', 'ALBQ_T20_.tif', 'for writing'>     then it said

'ALBQ_T20_BM_.tif' does not exist in the file system.     It REPEATED that message for the _LM and _SH file as well.  It sounds like the bat is trying to match up a one-to-one filename to process where the _BM, _LM, and _SH should be matching up only to the ALBQ_T20.tif which has the geo info I need transferred. 

Hope that makes sense.

ClutchThe error you are getting is a python code error, and it is running on the _SH, _BM, and _LM files because I didn't know they were to be excluded.  Change this line:
for /f "delims=" %%a in ('dir /a-d /b *.tif ^| find /v "_." ') do (
to this:
for /f "delims=" %%a in ('dir /a-d /b *.tif ^| find /v "_SH." ^| find /v "_BM." ^| find /v "_LM." ') do (
to EXCLUDE files ending in those characters.


To fix your python error, try changing this line:
dataset = gdal.Open( input )
to this:
dataset = gdal.Open( input.replace("\"","") )
Make sure that you don't mess up the indentation, as that is how python interprets blocks of code.

Or what might be the problem is that it is reading the arguments wrong.  You can also try changing any instance of sys.argv
  • to sys.argv[#-1]




Ok, tired the latest.  What I got was:

<'Unable to open', 'ALBQ_T20_.tif', 'for writing'>

Sounds like to me it is still trying to find a  file that does not exist in the list?.  Also, it sounds maybe the bat file is becoming too literal in the sense of only excluding/including certain filenames.  I fear my range of filenames that can vary from "XX_XX.tif" to "XXXXX_XXXX.tiff" for the files with geo info, to "XX_XX_XX.tiff" to "XXXXXX_XXXX_XXXX.tif" for files that need info is making this quite cumbersome.  The only constant character is that second "_" for files that would need geo info inserted.

Since the first bat file I posted in my very first post now works, would it be easier on your part to just modify that one to allow me the option to add text of my choice (for example, like a "_" or a"g" or whatever), just before the ".tif"?   I just don't want to have you continue to have to work on this while I am sure others are waiting for your expertise.

So for example, if I have a file with geo called CA_T20.tif and the file I want to add geo is called CA_T20_LM, I would have the option to call the processed file CA_T20_LMg.  It would not create a new file but just rename the file after being processe

I really do appreciate you being so patient with me on this and you have put so much work already into this... that's why I'm thinking just modify the first.  What do you think?I believe the isssue is somewhere between passing info from the batch file to the python script. Would it be possable for you to post the python acrtipt (in code brackets) along with any dependancies and test files so that i can do some teating on my end.OK,.... if you really want to do this 

Sorry for my ignorance but when you said in brackets I wasn't sure if you mean literally just put the code in brackets "[]".  The python script is actually in my first post at the top.  I have also attached the file as well and just gave it a txt suffix so I could upload it if that's easier for you.

I have created some very-very small sample files for you to test with.  Actual files we use run anywhere from 327MB to 4GB in size ( take awhile to upload!).  Here is a list.  As you can see the filenames that need geo can be quite different looking but the basic format convention is the same:

SOCAL_DD66.tif
SOCAL_DD66_BM3.tif
SOCAL_DD66_LM.tif
SOCAL_DD66_WM1.tif
SOCAL_DD66_aSCC.tif

1. Any file that has only one underscore "_" would be the file that contains the geo information.
2. Any file that has a second underscore needs geo info.

I guess if I had my "ultimate" bat file it would be able to drop a bunch of files into a folder like so:

CA_A1.tif
CA_A1_LM.tif
CA_A1_BM.tif
CA_A1_WM.tif
CA_A1_aSSC.tif
NV_AA3.tif
NV_AA3_LM1.tif
NV_AA3_BM2.tif
NV_AA3_WM2a.tif
NV_AA3_ATCC.tif
SOCAL_DD66.tif
SOCAL_DD66_BM3.tif
SOCAL_DD66_LM.tif
SOCAL_DD66_WM1.tif
SOCAL_DD66_aSCC.tif

From there I could just drop the folder onto the batch file and it would process automatically and results would be in the same directory.  The bat file would allow me the option to add a single character or even text at the end of the processed file or to just leave the filename as is.  Again, for example going from SOCAL_DD66_aSCC.tif to SOCAL_DD66_aSCCg.tif if I wish.

The program I use OSGeo4W, is really just a collection of geographic tools for processing data.  It is a free download.  It can be a rather large download and I am really only using the Python portion of the toolset.   You can choose which tools you wish to install during the install if you choose "advanced" if (I remember correctly), rather than an "auto" install.  So that can make it a lot smaller and quicker to install should you care to give it a try. 

The link is:  http://trac.osgeo.org/osgeo4w/ or just google OSGeo4W.   I downloaded and installed the 32bit version.

I did try just installing Python itself from the python website but I can't get it the python script to work that way.  So I use OSGeo4W.  Just was thinking that could save time rather than installing the toolset.  Maybe not a big deal.

Because of the severe size limitiations and types I am making several posts with attachments.  Named them all TXT so they would upload.

[attachment deleted by admin to conserve space]
1015.

Solve : Bat file to change group policy?

Answer» BAT file to change group policy-Administrative Templates\Network\QoS Packet Scheduler\Limit reservable bandwith-change value to 0Batches are not the best method of EDITING group policy settings. I have never seen anyone use a batch to pull it off to know if it COULD even be done. This might help, but i would ADVISE to edit group policy settings via the normal method vs a batch hack method if you find a way at this site path.

https://social.technet.microsoft.com/Forums/en-US/db7ebb86-6f93-4def-9d26-59f885b785af/editing-group-policy-with-bat-files?forum=smallbusinessserverSendkeys to emulate keyboard input, in a VBS script wrapped in a batch file can be used.
1016.

Solve : Can the BIOS admin reset the user accounts passwords??

Answer»

If I knew the BIOS administrator password for my COMPUTER could I RESET, change, or interact at all with the user accounts administrator password?No...
BIOS PASSWORDS and Win passwords are 2 different animals completely...

1017.

Solve : A .bat file to delete a particular registry key?

Answer»

This is the string i want to delete:
HKCU\Software\Microsoft\Terminal Server Client\Default" /v "MRU0" /t REG_SZ /v 173.219.91.228

In fact just want to delete this THINGS:
this : MRU0" /t REG_SZ /v 173.219.91.228
this: MRU1" /t REG_SZ /v 173.219.78.00
this: MRU0" /t REG_SZ /v 173.2.0.0Why do you need a .bat file to do this?

Have you tried using the help commands for information?

REG /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

reg delete /?

REG DELETE KeyName [/v ValueName | /ve | /va] [/f]

  KeyName    [\\Machine\]FullKey
    Machine  Name of remote machine - omitting defaults to the current machine.
             Only HKLM and HKU are available on remote machines.
    FullKey  ROOTKEY\SubKey
    ROOTKEY  [ HKLM | HKCU | HKCR | HKU | HKCC ]
    SubKey   The full name of a registry key under the selected ROOTKEY.

  ValueName  The VALUE name, under the selected Key, to delete.
             When omitted, all subkeys and values under the Key are deleted.

  /ve        delete the value of empty value name (Default).

  /va        delete all values under this key.

  /f         Forces the DELETION without prompt.

Examples:

  REG DELETE HKLM\Software\MyCo\MyApp\Timeout
    Deletes the registry key Timeout and its all subkeys and values

  REG DELETE \\ZODIAC\HKLM\Software\MyCo /v MTU
    Deletes the registry value MTU under MyCo on ZODIAC

1018.

Solve : batch for searching string?

Answer»

I have maded batch which search strings and if it finds it in txt file then it delete some other txt file.

Now problem si because I don't know how search that in subfolders and delete that files there.

for exmple.

there is a file bkpXXXX.txt
in folder e:\uporabniki\mike\documents\logs\bkpXXXX.txt
and when script find words "Na disku ni dovolj prostora"
it delete files e:\uporabniki\mike\documents\logs\XXdateXX.txt

every user have folder with his NAME so I can not put in script one path
like
e:\uporabniki\mike\documents\logs
e:\uporabniki\john\documents\logs
e:\uporabniki\george\documents\logs
e:\uporabniki\anna\documents\logs

and in all folders logs must be date*.txt deleted if script finds strings "Na disku ni dovolj prostora"

here is script but it work only in current folder.

Code: [Select]
findstr /m "Na disku ni dovolj prostora" bkp*.txt
if %errorlevel%==1 (goto B) else (goto A)

:A
del /q *date*.txt

:B
exit
Did you try using the /S option?

del /s /q e:\uporabniki\*date*.txt Quote from: Squashman on April 20, 2015, 06:42:58 AM

Did you try using the /S option?

del /s /q e:\uporabniki\*date*.txt

thanks, but things are more complicated

if I use S option under e:\uporabniki
it will delete all date.txt under e:\uporabniki

but that must not happend.

In bkpXXXX.txt is log what is backuped and if there is a string in it "disk is full" than it is full just for one user not for all, because of quotas.
So file date.txt must be deleted only under that user which have in backup log "disk is full"
because if that file mising from users log I get message that somethig is wrong with that user.

for EXAMPLE

e:\uporabniki\mike\documents\logs
e:\uporabniki\john\documents\logs
e:\uporabniki\george\documents\logs
e:\uporabniki\anna\documents\logs

 script recognise in
e:\uporabniki\anna\documents\logs
is file e:\uporabniki\anna\documents\logs\bkpXXXX.txt
is string "disk is full"
and script msut than delete only this file
e:\uporabniki\anna\documents\logs\XXdateXX.txt

all other must leave alone
e:\uporabniki\mike\documents\logs\XXdateXX.txt
e:\uporabniki\john\documents\logs\XXdateXX.txt
e:\uporabniki\george\documents\logs\XXdateXX.txtdel /s /q e:\uporabniki\%user%\*date*.txt

Set user to the username of the one it finds has a full disk.this way script must be runned by user, I intent to do it on server with admin.
I will CHECK this how it worksI am confused.  You know what user you need to delete it from, because that is what the log file is telling you.  PULL the name out of the log file. Quote from: Squashman on April 20, 2015, 12:15:06 PM
I am confused.  You know what user you need to delete it from, because that is what the log file is telling you.  Pull the name out of the log file.

Ok that is possible, I have a txt file with name of user in log folder like this John114S-HPTT.txt
So how can I pull that name and use it in my script?Isn't the log file you want to delete at e:\uporabniki\\documents\logs?
Just do this to the path:
Code: [Select]for /f "tokens=3 delims=\" %%A in (<path>) do set user=%%A
Quote from: Lemonilla on April 20, 2015, 04:30:24 PM
Isn't the log file you want to delete at e:\uporabniki\<SomeUser>\documents\logs?
Just do this to the path:
Code: [Select]for /f "tokens=3 delims=\" %%A in (<path>) do set user=%%A

yes but just one log of many and that is only this one *date*.txtCan you post an exact tree of the files and which ones you are searching through and which ones need deleting?

EDIT: If you could also post the actual file you are looping through, we might be able to help you more.here are two users from 50.
script search it in file
bkpA_desktop.txt
bkpA_documents.txt
bkpA_cpi_documents.txt
bkpA_cpi_desktop.txt
bkpAHP_desktop.txt
bkpAHP_documents.txt

If script FOUND text disk is full "Na disku ni dovolj prostora."

Than it must delete all files *datet.txt
for example these files

14.04.2015--datet.txt
13.04.2015--datet.txt
10.04.2015--datet.txt
09.04.2015--datet.txt
08.04.2015--datet.txt


and that is for all 50 users

other log files must stay as they are in folder log.



[attachment deleted by admin to conserve space]this can't be done? is it impossible?  Quote from: Blisk on May 04, 2015, 12:35:06 AM
this can't be done? is it impossible? 

Your question is impossible for me to understand.

Quote from: Blisk on April 20, 2015, 02:42:42 AM
which search strings and if it finds it in txt file then it delete some other txt file.

there is a file bkpXXXX.txt
in folder e:\uporabniki\mike\documents\logs\bkpXXXX.txt
and when script find words "Na disku ni dovolj prostora"
it delete files e:\uporabniki\mike\documents\logs\XXdateXX.txt

X X X and X are not really showing the relationship of the match.

I think the task is really really hard to understand from what you have written and shown. 
Actual real life examples are useful, along with the description of the task.I did that two posts above and the tree of folders is also thereCouldn't you break this into steps and solve that way?

Step 1:
Collect full users
Code: [Select]for /f "delims=" %%A in ('dir /b e:\uporabniki') do (
  findstr /m "Na disku ni dovolj prostora" e:\uporabniki\%%A\documents\logs\bkp*.txt
  if not %errorlevel%==1 (
    echo %%A >> e:\temp\userlog.txt
  )
)
Step 2:
Delete files
Code: [Select]for /f "delims=" %%D in (e:\temp\userlog.txt) do (del /q e:\uporabniki\%%D\documents\logs\*date*.txt)
Or combine them into one script and call it a day.
Code: [Select]echo off
for /f "delims=" %%A in ('dir /b e:\uporabniki') do (
  findstr /m "Na disku ni dovolj prostora" e:\uporabniki\%%A\documents\logs\bkp*.txt
  if not %errorlevel%==1 (
    echo %%A >> e:\temp\userlog.txt
  )
)
for /f "delims=" %%D in (e:\temp\userlog.txt) do (del /q e:\uporabniki\%%D\documents\logs\*date*.txt)
del /q e:\temp\userlog.txt

EDIT:

I just thought on this, it would cause issues as the errorlevel would continue to rise with each loop, therefore not giving a proper reading. You would need to set the errorlevel after each run, but we don't want to do that because errorlevels don't work that way. So we have to try something different.

Code: [Select]echo off
setlocal enabledelayedexpansion
set errorlev=%errorlevel%
for /f "delims=" %%A in ('dir /b e:\uporabniki') do (
  findstr /m "Na disku ni dovolj prostora" e:\uporabniki\%%A\documents\logs\bkp*.txt
  if !errorlevel!==!errorlev! (
    echo %%A >> e:\temp\userlog.txt
  )
  set errorlev=!errorlevel!
)
for /f "delims=" %%D in (e:\temp\userlog.txt) do (del /q e:\uporabniki\%%D\documents\logs\*date*.txt)
del /q e:\temp\userlog.txt
Give that a shot. I would change the del command to an echo del command for your first run to make sure you are deleting what you want to delete. Then you can remove the echo and run the script.
1019.

Solve : how many cmd lines i can use in 1 batch file??

Answer»

how many cmd lines i can use in 1 batch file?

for example 30 COMMANDS for diferrent registry blah blah....
can i use all 30 comnands in 1 single  batch file?Batches execution is 1 command or line at a time, and then it moves onto the next line. The only way to do more than 1 thing at the same time would be to create other instances triggered off the first instance in which say to use START THIS, START THAT, and START this other thing, otherwise it hangs at the first command instruction until it is complete before moving on to the next and so if you are launching say notepad.exe from within the batch file without a start command before it, it will wait for the Notepad.exe program to close before it moves on to the next command.

Not sure if this helps any.... what are you trying to achieve with batch that your concerned over limitations like this?

I have created very lengthy batches before and haven't reached a limit yet. One of which had over 1000 lines that was calling to a MySQL server to perform tasks.If he is asking how many consecutive lines can be included in one batch file, for sequential execution, Microsoft says there is no size limit for a batch script except those imposed by the file system and/or disk size. As for individual lines, I believe that no line should exceed 8192 characters, this figure including expanded variables. you can execute as many commands as you wish but in order , 2nd command wont INITIALIZE until 1ST has finished
If you want to do 2 things at once you can use CALL to run another batch file to do 2nd command simultaneously Quote from: JoeKkerr on May 10, 2015, 05:17:26 AM

If you want to do 2 things at once you can use CALL to run another batch file to do 2nd command simultaneously
This is not so; CALL just starts an EXTERNAL batch script and returns only after it has finished.
You can use unlimited commands in a batch file.

  Quote from: LeonardKonrad on May 10, 2015, 06:02:56 AM
You can use unlimited commands in a batch file.
We had already ESTABLISHED that.
1020.

Solve : Batch File To Extract String Of Characters From Txt-File?

Answer»

Hi,

I hope someone here can help me--it would be greatly appreciated. 

I have a folder with a bunch of text files. I'm looking for a batch-file that extracts a string of exactly 5000 characters from all of these and puts them in a seperate file (1 for each). The place within each txt-file that the 5000 characters are taken from should be random (ie. if I run it a couple of times on the same original file, the extracted bit would be different). Afterwards, the original file should no longer contain this string.

So I have:
filename_1.txt
filename_2.txt
filename_3.txt
...

And I want:
filename_1.txt and filename_1_5000.txt
filename_2.txt and filename_2_5000.txt
filename_3.txt and filename_3_5000.txt
...

etc.
Does that make sense? Can anyone help me with this?

Thanks!  It does help if you can give a reason why.
Why 5000 characters?
There already are utilities that will truncate a file after a definite number of characters. People WRITE these things either in C or a  script languages.
Of course, you can USE DOS utilities and batch, if you want. Quote from: Geek-9pm on May 05, 2015, 10:39:02 PM

There already are utilities that will truncate a file after a definite number of characters.

The questions seems to say: take 5000 characters from a random place in a file, remove it and put it in another file.

He's not trying to truncate files as I understand it.

Quote from: Stefan on May 05, 2015, 09:42:22 PM
Does that make sense? Can anyone help me with this?

  • Will the 5000 characters go over different lines?
  • Does the character count include carriage return and linefeed characters?
Thanks you two,

yes that's what I'm trying to do, foxidrive. So the general idea is that I have a bunch of texts and want to run tests on even-sized chunks of those to see if I can identify the author. (I would do strings of 4000, 3000, 2000, 1000 and 500 next).

So the texts I have do not have line-breaks in them... but I'm not entirely sure how that would be different from "carriage return and linefeed characters" (I'm really new to this--sorry).

Thanks!  OK, now it is clear.
Some texts have both the CR and the LF controls. Others have just one of the two.
But now that we see what you want, the CR LF is not important. However, a CR might be used to  end a paragraph.

Foxdrive might help do this in batch.
Myself, I would have to use Q Basic, an old MS program.


Thanks!

Anything would be fine with me. This will help me write a paper--and should it get published, I'll thank you two in it!

What about white space? Is thi some kind of word frequency or vocabulary profile analysis? I have read posts by David Graves who has analysed works by JANE Austen, but I don't know what his software is like (he wrote some himself). You can get lots of books in text format at Project Gutenberg, and you could load one into a good editor which has word and character count (e.g. MS Word) and select blocks of the right length. Here are 5000 characters (not counting spaces) from "The Sleeper Wakes" by HG Wells. I would be inclined to use a more capable language than batch (Visual Basic Script for example)

CHAPTER II. THE TRANCE

The state of cataleptic rigour into which this man had fallen, lasted
for an unprecedented length of time, and then he passed slowly to the
flaccid state, to a lax attitude suggestive of profound repose. Then it
was his eyes could be closed.

He was removed from the hotel to the Boscastle surgery, and from the
surgery, after some weeks, to London. But he still resisted every
attempt at reanimation. After a time, for reasons that will appear
later, these attempts were discontinued. For a great space he lay in
that STRANGE condition, inert and still neither dead nor living but, as
it were, suspended, hanging midway between nothingness and existence.
His was a darkness unbroken by a ray of thought or sensation, a
dreamless inanition, a vast space of peace. The tumult of his mind had
swelled and risen to an abrupt climax of silence. Where was the man?
Where is any man when insensibility takes hold of him?

"It seems only yesterday," said Isbister. "I remember it all as
though it happened yesterday--clearer perhaps, than if it had happened
yesterday."

It was the Isbister of the last chapter, but he was no longer a
young man. The hair that had been brown and a trifle in excess of the
fashionable length, was iron grey and clipped close, and the face that
had been pink and white was buff and ruddy. He had a pointed beard shot
with grey. He talked to an elderly man who wore a summer suit of drill
(the summer of that year was unusually hot). This was Warming, a London
solicitor and next of kin to Graham, the man who had fallen into the
trance. And the two men stood side by side in a room in a house in
London regarding his recumbent figure.

It was a yellow figure lying lax upon a water-bed and clad in a flowing
shirt, a figure with a shrunken face and a stubby beard, lean limbs and
lank nails, and about it was a case of thin glass. This glass seemed
to mark off the sleeper from the reality of life about him, he was a
thing apart, a strange, isolated abnormality. The two men stood close to
the glass, peering in.

"The thing gave me a shock," said Isbister "I feel a queer sort of
surprise even now when I think of his white eyes. They were white, you
know, rolled up. Coming here again brings it all back to me.

"Have you never seen him since that time?" asked Warming.

"Often wanted to come," said Isbister; "but business nowadays is too
serious a thing for much holiday keeping. I've been in America most of
the time."

"If I remember rightly," said Warming, "you were an artist?"

"Was. And then I became a married man. I saw it was all up with black
and white, very soon--at least for a mediocre man, and I jumped on to
process. Those posters on the Cliffs at Dover are by my people."

"Good posters," admitted the solicitor, "though I was sorry to see them
there."

"Last as long as the cliffs, if necessary," exclaimed Isbister with
satisfaction. "The world changes. When he fell asleep, twenty years
ago, I was down at Boscastle with a box of water-colours and a noble,
old-fashioned ambition. I didn't expect that some day my pigments would
glorify the whole blessed coast of England, from Land's End round again
to the Lizard. Luck comes to a man very often when he's not looking."

Warming seemed to doubt the quality of the luck. "I just missed seeing
you, if I recollect aright."

"You came back by the trap that took me to Camelford railway station.
It was close on the Jubilee, Victoria's Jubilee, because I remember the
seats and flags in Westminster, and the row with the cabman at Chelsea."

"The Diamond Jubilee, it was," said Warming; "the second one."

"Ah, yes! At the proper Jubilee--the Fifty Year affair--I was down at
Wookey--a boy. I missed all that.... What a fuss we had with him! My
landlady wouldn't take him in, wouldn't let him stay--he looked so queer
when he was rigid. We had to carry him in a chair up to the hotel. And
the Boscastle doctor--it wasn't the present chap, but the G.P. before
him--was at him until nearly two, with, me and the landlord holding
lights and so forth."

"It was a cataleptic rigour at first, wasn't it?"

"Stiff!--wherever you bent him he stuck. You might have stood him on
his head and he'd have stopped. I never saw such stiffness. Of course
this"--he indicated the prostrate figure by a movement of his head--"is
quite different. And, of course, the little doctor--what was his name?"

"Smithers?"

"Smithers it was--was quite wrong in trying to fetch him round too soon,
according to all accounts. The things he did. Even now it makes me feel
all--ugh! Mustard, snuff, pricking. And one of those beastly little
things, not dynamos--"

"Induction coils."

"Yes. You could see his muscles throb and jump, and he twisted about.
There was just two flaring yellow candles, and all the shadows were
shivering, and the little doctor nervous and putting on side, and
him--stark and squirming in the most unnatural ways. Well, it made me
dream."

Pause.

"It's a strange state," said Warming.

"It's a sort of complete absence," said Isbister.

"Here's the body, empty. Not dead a bit, and yet not alive. It's like a
seat vacant and marked 'engaged.' No feeling, no digestion, no beating
of the HEART--not a flutter. _That_ doesn't make me feel as if there was
a man present. In a sense it's more dead than death, for these doctors
tell me that even the hair has stopped growing. Now with the proper
dead, the hair will go on growing--"

"I know," said Warming, with a flash of pain in his expression.

They peered through the glass again. Graham was indeed in a strange
state, in the flaccid phase of a trance, but a trance unprecedented in
medical history. Trances had lasted for as much as a year before--but at
the end of that time it had ever been waking or a death; sometimes first
one and then the other. Isbister noted the marks the physicians had
made in injecting nourishment, for that device had been resorted to to
postpone collapse; he pointed them out to Warming, who had been trying
not to see them.

"And while he has been lying here," said Isbister, with the zest of a
life freely spent, "I have changed


Hi,

thanks, Salmon Trout--yes that was my plan (and I'm using r for that). I've been doing the text-selecting manually so far but it's just an impossible work-load. I have fifty texts, would like to get strings of 5000, 4000, 3000, 2000 1000 and 500 for each and run it 100 times with chaning lists of most frequent words--so that would be impossible to do this way.

And I've been taking out paragraphing so far--but it looks like it doesn't make a difference for the r-plugin I'm using (same results with or without paragraphs and additional spaces).

But thanks for the tip! Quote from: Stefan on May 06, 2015, 09:12:23 AM
So the texts I have do not have line-breaks in them... but I'm not entirely sure how that would be different from "carriage return and linefeed characters"

In a Windows text file at the end of each line are two invisible characters - the CR/LF pair.
Viewing the file in a hex editer/viewer will show you the characters. 

Linux and Mac native text files have only one character ending each line. 
Linux has LF and Mac has CR if I recall correctly.

Quote from: Salmon Trout on May 06, 2015, 01:19:04 PM
I would be inclined to use a more capable language than batch (Visual Basic Script for example)

This is a sensible option to do it in, with native VBS in Windows, and it is still scriptable in a batch file.
1021.

Solve : I want to change group policy value with a VBS script,Help?

Answer»

I want to change group policy-Administrative Templates\Network\QoS Packet Scheduler\LIMIT reservable bandwith-change value to 0You are asking about something that most of us never do.
If needed, it is more often doing by hand. It is not the sort of thing you would be bumping up and down on a REGULAR basis.
Have you already read this:
Limit Reservable Bandwidth Setting In Windows
It applies to Windows 8.1 and would normally impact only the LOCAL network.
Setting it to zero may not be what you want.
maybe works fine too, with REMOTE CONTROL :SERVER 2008, w7,w8

1022.

Solve : batch file to go directely here??

Answer»

I want to create a BATCH FILE go directely here:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\EnableConnectionRateLimiting

Thanks

This might help...

HTTP://www.tomshardware.com/answers/id-2301882/batch-file-edit-registry.htmlmany thanks........

1023.

Solve : Embedded variables not setting?

Answer»

Hello,

Haven't been on in a while, but ran into a problem today and must be hitting a mental block or something, because I can't see what I'm doing WRONG.

The following code is trying to populate a csv file with some names and statuses. For whatever reason, the embedded variables do not set like they should. What am I doing wrong?

Code: [Select]echo off
cls
setlocal enabledelayedexpansion

for /f "tokens=1,2*" %%A in (Alpha.txt) do (
  call :subAlpha %%A %%B
)
goto :eof


:subAlpha
set lname=%1
set lname=%lname:,=%
for /f "tokens=*" %%i in ('trim.bat %lname%') do set lname=%%i
set fname=%2
set fname=%fname:-=%
for /f "tokens=*" %%j in ('trim.bat %fname%') do set fname=%%j
set a43check=-
set d75check=-
for /f "tokens=1,2*" %%E in (A43.txt) do (
  call :sub43 %%E %%F
)
for /f "tokens=1,2*" %%J in (D75.txt) do (
  call :sub75 %%J %%K
)
echo fname = %fname%
echo lname = %lname%
echo a43fname = %a43fname%
echo a43lname = %a43lname%
echo d75fname = %d75fname%
echo d75lname = %d75lname%
pause
echo "%lname%, %fname%", %a43check%, %d75check% >> revalidate.csv
goto :eof

:sub43
set a43lname=%1
set a43lname=%a43lname:,=%
for /f "tokens=*" %%k in ('trim.bat %%a43lname%%') do set a43lname=%%k
set a43fname=%2
set a43fname=%a43fname:-=%
for /f "tokens=*" %%l in ('trim.bat %a43fname%') do set a43fname=%%l
if "%lname%"=="%a43lname%" (
  if "%fname%"=="%a43fname%" (
    set a43check=X
  )
)
goto :eof

:sub75
set d75lname=%1
set d75lname=%d75lname:,=%
for /f "tokens=*" %%m in ('trim.bat %d75lname%') do set d75lname=%%m
set d75fname=%2
set d75fname=%d75fname:-=%
for /f "tokens=*" %%n in ('trim.bat %d75fname%') do set d75fname=%%n
if "%lname%"=="%d75lname%" (
  if "%fname%"=="%d75fname%" (
    set d75check=X
  )
)
goto :eoftrim.bat
Code: [Select]echo off
set trim=%1
:backloop
if "%trim:~-1,1%"==" " (
  set trim=%trim:~0,-1%
  goto backloop
)
:frontloop
if "%trim:~0,1%"==" " (
  set trim=%trim:~1%
  goto frontloop
)
echo %trim%A little more explanation of the aim, the problem, and the error or result, would be handy. Yeah that would probably be helpful

So when I run this script (with the echos in there) I receive the following output on the screen:
fname = Bob
lname = Smith
a43fname =
a43lname =
d75fname =
d75lname =


So the first variables are setting, but the embedded ones are not setting. What I am trying to accomplish is COMPARING the list in Alpha, which is a list of over 500 names, with the names in the other two files (about 300 a piece) and see which ones are in all three, only two, or only in the Alpha list.

I haven't tried breaking embedded calls into their own files yet, but I realize that could be a working option. Is there any way to get this to work in the single file as it is set up now?He should reconsider his use of goto :eof
Quote from: Geek-9pm on April 30, 2015, 06:51:09 PM

He should reconsider his use of goto :eof
Why? Quote from: Raven19528 on April 30, 2015, 05:39:32 PM
Yeah that would probably be helpful

So when I run this script (with the echos in there) I receive the following output on the screen:
fname = Bob
lname = Smith
a43fname =
a43lname =
d75fname =
d75lname =


Without the needed input file(s) - we'd go crazier than we are, trying to work out what you are doing.
Give us some data in input file(s) in the correct formats...

The variables aren't being set because of the way you are setting them - maybe within a loop. 
So this is some SAMPLE text from the input files:

Alpha.txt

SMITH, BOB J
JONES, JANE A
WILLIAMS, ANDREW G
...


A43.txt

SMITH, BOB A43.PDF
WILLAMS, ANDREW A43.PDF
WHITE, JIM A43.PDF
...


D75.txt

SMITH, BOB D75.PDF
HOBBS, JACOB D75.PDF
GREEN, NORM D75.PDF
...


Why am I not able to set those variables within a loop? I don't recall that ever being a problem before. Is it something where maybe I should use a call set command to set the variables? Quote from: Squashman on April 30, 2015, 08:16:57 PM
Why?
Because the feature is for advanced users.
Because one who can not write a few lines of batch code and not know how to debug it not use goto : eof

Each part of the code should be in a separate file with echo left on. He would verify wash file;'s behavior separately. Only after getting it to work right would he combine the files and user the goto : eof thing. This is the proven method for novices. BEGINNERS should not use that feature until they can write 100 lines of code sand get it right the first  time.
In other words, he did not use a debugging method suitable for his skill level.
Not that being a beginner is a crime. But one should not use code that is to hard to debug.Okay, ran this through manually, after breaking out all the calls into separate files. Found that the additional text files weren't processing for some reason. Changed the command to for /f "tokens=1,2" %%E in ('type A43.txt') do (

Works like it should now. Run time is a little long, but it's reading these files over and over, and honestly, its doing the job for me so I don't have to, so I'm happy with that.

Thank you Geek. While I'm sure I have some rust, I was doing regular batch scripts for a while, and now getting back into it for some more mundane tasks, I'm sure there is plenty I need to relearn.I am glad that worked for you and glad your replied.
Having a program that works is more important than speed. Inmost cases.
Batch files, by nature, are not well suited for speed optimization.
If  you have a need to write lots of batch files,  you might consider using The Microsoft recommended advancement: PowerShell
http://en.wikipedia.org/wiki/Windows_PowerShell
Also see:
Jump Start PowerShell Video
Have fun !   


Quote from: Raven19528 on May 01, 2015, 08:14:09 AM
So this is some sample text from the input files:

It's nice of you to provide some sample data.

I know you have a solution but a comment I have from looking briefly at your code is that trim.bat will do nothing at any stage with any variable - because the data you are passing will never have leading or trailing spaces due to the way the data is passed in the call statements.

Another issue is that the %2 term will always lose part of the second term in the call statements.

I didn't analyse it past noting those problems - it would be really helpful to discuss what the batch script is SUPPOSED to be doing, with some examples, when you ask your question.

The input data is essential of course - kudo's to you for providing some (Often, instead of input data we get an argument about how we don't need any).

If you want to optimise your code for speed then give us all the info and someone may be able to offer some ideas.
1024.

Solve : batch file multiple instances?

Answer»

Hey everyone. I need help with something.
I have a batch file batch.bat that runs after a torrent finishes performing some standardized routines.

Sometimes it happens, while batch file is still running, that another torrent finishes and batch.bat is triggered again, messing everything up. What is want it to check if batch.bat is still running, then wait to FINISH and continue with the new instance of batch.bat

Can we do something like this?

Thanks for the help!!If running multiple instances of same batch, its best to have say if your running 4 downloads at the same time a file called batch1, batch2, batch3, and batch4. So that the naming of one of the same code batches doesnt conflict with the other. I use this name_numbering all the time when running automation that looks for instances open or closed etc as WELL as taskkill routines where you want to specifically kill a process, but the PID is random and you need to kill it by name.

batch1.bat
batch2.bat
batch3.bat
batch4.bat

should fix thisI thought of that. Problem though is that utorrent in this case has the "Run Program" option to Run this program when a torrent finishes allowing only 1 file, so the naming scheme you suggest cannot work hereOk... you could install other copies of uTorrent to custom install locations and run MULTIPLES of it with single download each instance, and each instance has its own unique batch file name. Reference:
Running multiple instances of a Batch file in windows simultaneously.
Code: [Select]start /b cmd /c %~0 2>nul 1>&2Assuming I haven't forgotten a crucial part, this will open a new instance of the saved batch file in the background of the current file.  They will share the same output console, and It's very complicated to stop them, but thats how you thread.  I would recommend going with the above answer and doing something like
Code: [Select]for %%A in (1,1,4) do start batch.bat
Which should open 4 separate instances of batch.bat.

Do a search for snake.bat on this site, (it's a link to a different forum) as an example of how it WORKS.

1025.

Solve : how to combine 2 or more file.txt?

Answer»
i want to combine text in file1.txt with text in file2.txt, combination in new file.txt

so far this is batch i create

Code: [Select]echo off

setlocal disableDelayedExpansion

for /f "delims=" %%A in ('type file1.txt') do call :starter1 "%%A"

:starter1
set "start=%%A"

echo %start%>> "new text.txt"

for /f "delims=" %%A in ('type file2.txt') do call :starter2 "%%A"

:starter2
set "start=%%A"

echo %start%>> "new text.txt"


any suggestion that could make this work?

i just a new guy who still learning from STUFF i try to do...
thank youThe main problem I can see is that once it is done the for loop, it moves onto the function :starter1,
Oh, also you are using the for argument inside the call function... Try this:

Code: [Select]echo.>"new text.txt"
for /f "delims=" %%A in ('type file1.txt') do call :print "%%A"

for /f "delims=" %%A in ('type file2.txt') do call :print "%%A"

:print
set start=%~1

echo %start%>> "new text.txt"
goto :eof

But the simpler way of doing this would be

Code: [Select]type fileA.txt > fileC.txt
type fileB.txt >> fileC.txt
thank you thank you thank you type fileA.txt > fileC.txt
type fileB.txt >> fileC.txt

how can i set a space between them? for example, when the 2 files combine looks like this:

FileA.txt
123
1234

FileB.txt
9876
987

combined looks like this:
123
12349876
987

So need a space
What about combine and remove duplicates at the same time?

type A.txt > C.txt
echo. >> C.txt
type B.txt >> C.txti combine 2 small files and i got this , i want no space between, please :
type A.txt > C.txt
echo. >> C.txt
type B.txt >> C.txt

1kallo1209:guacharaca1209
2ivanmanoel98:manoel
3karolmelendez:970519190597
 
4romeucastro:hilda102030
5franciellyfep:dream2008
6lethiciamarfil:94071800The simple way to combine text files would be:

copy file1.txt + file2.txt file3.txt

You can also use wildcards.

See this MS info: https://support.microsoft.com/en-us/kb/69575

The reason why some files combine with the last line of file1 and the first line of file2 combined has to do with WHETHER the first file has a CR/LF at
the end of the last line or not.  It would be difficult to write a batch file that could determine if the last line has a CR/LF and add it if not.  The easiest way would be to SIMPLY add a CR/LF to every file.  This could result in 2 blank lines between some files.

You could create a file named crlf.txt using notepad.  Open that file and press the Enter key once then SAVE the file.  If you WISH to add a CR/LF to the end of a file you can simply use:

copy file1.txt + crlf.txt file2.txt

I don't know of a way to remove the CR/LF from the end of a file via a batch file.

He's not the OP...3rd Topic he's horned in...

Message sent...still not working,result:


1kallo1209:guacharaca1209
2ivanmanoel98:manoel
3karolmelendez:9705191905974romeucastro:hilda102030
5franciellyfep:dream2008
6lethiciamarfil:94071800 Quote from: siriguk on May 12, 2015, 08:04:45 AM
uhh the result is,still not working:
1kallo1209:guacharaca1209
2ivanmanoel98:manoel
3karolmelendez:9705191905974romeucastro:hilda102030
5franciellyfep:dream2008
6lethiciamarfil:94071800

You need to start your own Topics as mentioned...instead of piggybacking on existing ones...

Thank You.ok Patio i apologies , u right
1026.

Solve : combne 2 or more file.txt?

Answer»

how to combine 2 or more file.txt

i used this:
TYPE A.txt > C.txt
echo. >> C.txt
type B.txt >> C.txt

and this:
copy file1.txt + file2.txt file3.txt

and i got this:

1kallo1209:guacharaca1209
2ivanmanoel98:manoel
3karolmelendez:9705191905974romeucastro:hilda102030
5franciellyfep:dream2008
6lethiciamarfil:94071800


I want to look like this:

1kallo1209:guacharaca1209
2ivanmanoel98:manoel
3karolmelendez:970519190597
4romeucastro:hilda102030
5franciellyfep:dream2008
6lethiciamarfil:94071800

You should probably go BACK to the program that created your input and figure out why it is not ending the last line with a CR\LF pair.

Otherwise you will have to use a FOR /F command and echo the token variable to a new file.no IDEA man , i am noob thanks anyway Quote from: siriguk on May 12, 2015, 12:51:54 PM

how to combine 2 or more file.txt

i used this:
type A.txt > C.txt
echo. >> C.txt
type B.txt >> C.txt

and this:
copy file1.txt + file2.txt file3.txt

and i got this:

1kallo1209:guacharaca1209
2ivanmanoel98:manoel
3karolmelendez:9705191905974romeucastro:hilda102030
5franciellyfep:dream2008
6lethiciamarfil:94071800


I want to look like this:

1kallo1209:guacharaca1209
2ivanmanoel98:manoel
3karolmelendez:970519190597
4romeucastro:hilda102030
5franciellyfep:dream2008
6lethiciamarfil:94071800

You could create a file NAMED crlf.txt using notepad.  OPEN that file and press the Enter key once then save the file.  If you wish to add a CR/LF to the end of a file you can simply use:

In your example, if you do

copy file1.txt + crlf.txt + file2.txt file3.txt

it should do what you want.is working, thanks
1027.

Solve : cmd to change RDP-TCP/Session/Override User Settings?

Answer»

I want to STOP AUTO-LOGG-OFF after i disconnect
For this RDP doesn't WORK even if i have ADMINISTRATORS rights
For my other 2 RDP's working fine this reg keys:

REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v "KeepAliveTimeout" /t REG_DWORD /d 0 /f
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v "MaxConnectionTime" /t REG_DWORD /d 0 /f
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v "MaxDisconnectionTime" /t REG_DWORD /d 0 /f
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v "MaxIdleTime" /t REG_DWORD /d 0 /f

When i make this CHANGES in registry i notice that '' RDP-TCP/Session/Override User Settings changes to NEVER'' and works fine  but for this RDP the values doesn't CHANGE, any solution?
thanks

1028.

Solve : i need to search for a file on c partition and delete it using a dos batch?

Answer»

Hi alli need to search for a file on c PARTITION and delete it using a dos batch

so far i got untill

echo off
DIR filetodelete/S >test1


thanks alot

also is it possible to compile it to binary / exeIts ALREADY been covered here... the first batch shows how to rename, but in comments you will see the dangerous delete instruction that you can use instead of rename.

http://stackoverflow.com/questions/15689510/batch-find-file-and-rename-it-find-file-and-delete-it




Quote

Oh, it's great to have some good-loking programmers! Most programmers I know are UGLY.

for /f "delims=" %%i in ('dir /s /b /a-d "text.txt"') do (ren "%%i" text2.txt)

Should do the rename task. You should prepend the drive and starting DIRECTORY to the filename THOUGH, or it will rename ALL the text.txt files in ALL subdirectories. Hence ...dir /s/b "c:\users\kaster\text.txt"... will process "c:\users\kaster\" and all of the directories below and rename ALL of the files named text.txt to the NEW name.

It works by performing a DIRscan in /b basic mode (ie filenames only) /s including subdirectories /a-d ignoring matching directory names for files named "text.txt" - and the full filename is assigned to %%i. The delims clause makes sure that any spaces are not interpreted as delimiters.

See

`FOR ?`

from the prompt for documentation.

ANd if you are executing this directly from the prompt, change each %% to %

The second command is substantially easire

del /s "image1.jpg"

Again, prepend the starting path, and be VERY, VERY careful. This will delete ALL filenames matching "image1.jpg" in and under the specified directory.

Throughout, quoting the filenames ensures that spaces in file or directorynames are correctly processed.
1029.

Solve : desktop locker for desktop using batch cmd.??

Answer»

i want something like this for my RDP DESKTOP, i want lock it, is possible to use some batch command and not a software? (many are full of viruses)

This is the second time you have asked this question.  Do not start two topics about the same thing.

A quick and easy Google SEARCH found this.
http://www.idsecuritysuite.com/blog/how-to-lock-down-the-computer-via-a-shortcutuseless for my RDP,THANKS anywayWell I am not sure why you consider it useless.  Maybe you  are not EXPLAINING your problem clearly.yes BECOUSE i am noob and i writte like *censored*...i apologies and thanks to be so patient with me..You have still yet to explain what your whole PLAN for this "RDP Project" is.  Why would you want to use a 3rd party lock anyway? None will be properly secure! Windows has built in screen locking!

Explain exactly what you want to do for the entire project and then people will try to help you, creating a bunch of random threads all over the place will not work.ok thanks for ur advice

1030.

Solve : Passwords must meet complexity requirements regedit cmd??

Answer»

Password must meet complexity requirements

I want to configure local password policy for a stand-alone computer as below:
ENFORCE password history: net accounts /uniquepw:XXX
Maximum password age: net accounts /maxpwage:XXX
Minimum password age: net accounts /minpwage:XXX
Minimum password length: net accounts /minpwlen:XXX

 
But for complexity and encryption type I didn't find a command-line solution on registry settings. How can I configure password settings LISTED as below:The only way I know of to do this in a BATCH file is to use SECEDIT to export the current security configuration to a file, then edit the file and then use SECEDIT again to import it. I have no idea what version of Windows you are using.  It may not be available on Windows XP or even Home VERSIONS of any Windows operating system.I've asked him 3 times which ver. of XP he's runnin...good luck with that.sp2 baby Quote from: patio on May 13, 2015, 07:14:07 AM

I've asked him 3 times which ver. of XP he's runnin...good luck with that.
And we still have not gotten the correct answer.***sigh***...see ?Okay, clearly he doesn't understand what it is you are asking.

siriguk, are you running XP Home or XP Pro? Thank you.Alln dear i RUN XP proIf this is just a single stand alone computer, just change it with Group Policy Editor.i can't becouse of this: http://i61.tinypic.com/14wrklf.jpg

the other commands,like: net accounts /uniquepw:XXX      blah blah  take effect

Well at least you aren't afraid to reveal you are a spammer.What are you trying to post a picture of? I clicked the link and did not see anything computer related.Ok, I see it now.  Just getting blocked by our firewall.  If that is grayed out I would assume you do not have rights to change those settings on your computer.  You positive the user you are logged in with is an administrator?yes manAnd the computer is not attached to a domain?  As far as I know, that would be the only reason why it would be grayed out.
1031.

Solve : cmd to start automatically all my .exe programs?

Answer»

So after i INSTALL windows i OPEN my USB loc:  H:\Windows Programs to run after windows xp installation

and then i must to install every program. one by one, my question:is there any .bat cmd which  run all programs with 1 click?
ThanksIf you list all the programs like this it will START them, but you will manually have to take it from there.

start
start

1032.

Solve : is possible to set a password to a registry key?or block acces??

Answer»

is possible to set a password to a registry key?or block acces only for that key?do not let that no ONE can edit or deleteIf anyone has access to the C: drive of the system, they have access to the registry.

If your fully patched and running a good antivirus and have a good firewall then you have nothing to worry about.

With NTFS partition and correct security measures you should be all set. If your computer use places you at high risk for infection etc, you should implement a image backup of your system so that when infected or think your infected you can restore back to KNOWN clean state.

Also if you lower your previleges by creating a USER account that does not have Administrator privileges you can limit how easily you could get infected. Most Windows users are running as system admin all teh time and so this puts them at risk of infection etc. On my systems I make a profile / user account that is bare minimum access which blocks scripts from trying to install junk BEHIND the scenes etc.I found this:

HKEY_USERS\Foo\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer  NoViewOnDrive  to disable a drive or NoDrives to hide the drives
what about this?A Linux boot disk or custom BartPE boot disc would defeat this in seconds. That's why I stated.

Quote

If anyone has access to the C: drive of the system, they have access to the registry.

If your trying to keep someone out of your computer who has physical access to it, you will need to block the physical access by making the computer unable to be accessed, or install a removable hard drive bay and remove the drive and put in in a safe when your done using computer so that its useless for others ( OR ) if others need access and you want to only have 1 computer, go the route of removable hard drives and have an Main Drive and a User Drive, and label them with a sharpie marker etc, and plug in the Main Drive when you want to use the 1 and only computer, and remove this drive and insert the User Drive when others need to use the computer but of which you don't want anyone to have access to altering your system, since after all... the your data is on the hard drive or SSD and so, swapping out drives you can have 1 computer that acts like 2 DIFFERENT systems. One for you to have and keep clean and another for the kids to use for example and infect their own data.

I have done this setup for some clients who have kids that like to download everything and anything and their system kept getting infected. $100 for a $50 hard drive and 2 x $25 removable hard drive bays was the fix. They swap in their hard drive in place of their kids when they need to pay bills etc, and they swap the kids drive back in when they are using the 1 and only computer for regular web surfing or their kids are gaming etc.

Its one way to give a single computer 2 completely ISOLATED profiles. Assuming that its a desktop computer that is. Laptops require a BIOS password to lock and this can be dangerous if you forget the password. This BIOS password wouldn't work for if others need to use the system.
1033.

Solve : How To Delete Folders/Subfolders With Files Using Batch File?

Answer»

I am new to batch scripting.

I have a ROOT folder called "Names"..It has subfolders ,these subfolders contains FILES. I will be giving the names of subfolders to be deleted in TEXT FILE Ex..
John
Tom
Rambo.
I will be reading the folder names from text file & delete only those folders with files inside the folder also .

Please provide me the code for it..
Also posted here:
http://www.dostips.com/forum/viewtopic.php?f=3&t=6451

1034.

Solve : copying last X lines to new file?

Answer»

I have a log and I need to copy last 50 lines from logfile.txt to lastlines.txt
below script works only if there is more than 50 lines in logfile.txt
if there is les than 50 lines in logfile.txt it MAKES empty file but that is wrong.
script must copy last 50 lines to new file if there is less than 50 lines than it copy what it is in logfile.txt to new file
lastlines.txt
Can SOMEONE help me fix this script?
Code: [Select] for /f %%i in ('find /v /c "" ^&LT; LogFile.txt') do set /a lines=%%i
set /a startLine=%lines% - 50
more /e +%startLine% LogFile.txt > lastLines.txtok I MANAGE to solve this by myself

Code: [Select]for /f %%i in ('find /v /c "" ^< LogFile.txt') do set /a lines=%%i
set /a startLine=%lines% - 50
more /e +%startLine% LogFile.txt > lastLines.txt
for %%x in (lastLines.txt) do if not %%~zx==0  (GOTO End) else (goto A)
:A
xcopy /Y LogFile.txt lastLines.txt
:End

1035.

Solve : can i lock a remote dekstop with bat without running any program??

Answer»

can i lock a REMOTE dekstop with bat without running any program?program like:Desktop Locker and many others...?Perhaps you might ask the QUESTION another way.
In some business places there can be an administrator who has the authority lock every desktop computer in the COMPANY. He has special software that SENDS the command over the local network to stop anybody from using an idle desktop.
 Is that the kind of thing you  NEED to do?
I sense a nefarious goal in all this...

Topic Temporarily Closed.

Any questions...PM me.

1036.

Solve : Batch job that send out email and deletes previous backup?

Answer»

I have written a working batch file to back up some folders/application

echo off

echo call batch job

CALL PCSDEV.bat  (This is where the backup get executed)


echo return from backup to the current calling batch file
REM Change directory back to the location where the file is archived
d:
REM cd ..

cd D:\IIS_ETL_BK

set HR=%time:~0,2%
set HR=%Hr: =0%
set HR=%HR: =%
ren Test.out.isx Test.out-%date:~10,4%%date:~7,2%%date:~4,2%_%HR%%time:~3,2%.isx


cd /istoolbk

My question is:

1. I want to send out email NOTIFICATION after the backup is completed=> before the last command
2. I want to check for previous 15 backup(an example), if there are 16(an example) I want to delete the first backup. In essence keeping 15 sequential backups at a time
Quote from: Great! on June 10, 2015, 05:18:55 PM

1. I want to send out email notification after the backup is completed=> before the last command
2. I want to check for previous 15 backup(an example), if there are 16(an example) I want to delete the first backup. In essence keeping 15 sequential backups at a time

There are more reliable ways to get a date and time string which do not depend on the user locale and/or MACHINE and which sort naturally in a batch script.

Some questions you'd need to answer are:

  • What is the filename FORMAT of the backup files?
  • Are there any other files in the folder with the backup files?
  • What is the NAME of the backup folder location
  • Do you have admin permissions
  • What tool do you want to send the email with?
  • What is the actual NUMBER of files being kept - a range of the actual number would be nice. 10 to 200 for example.
    What is the filename format of the backup files?
     -----
     The filename format is an application based format that ends with . A typical example is this Test.out-20151206_0953.isx

    Are there any other files in the folder with the backup files?
-----
   There will be other files from previous backup in this directory reading different timestamp

    What is the name of the backup folder location
----
   The name of the backup location is a subfolder under the folder where the script is located. SO if my script is in D:\Istool.   My backup will be D:\istool\Backup

    Do you have admin permissions
-----
 Yes

    What tool do you want to send the email with?
----
 Pure MSDOS batch command. No third party tool

    What is the actual number of files being kept - a range of the actual number would be nice. 10 to 200 for example.
---
30 meaning one backup per day Quote from: Great! on June 12, 2015, 12:53:45 PM
    What is the filename format of the backup files?
     -----
     The filename format is an application based format that ends with <FileName-TimeAdded.isx>. A typical example is this Test.out-20151206_0953.isx

You use YYYYDDMM format ? 

Quote from: Great! on June 12, 2015, 12:53:45 PM
    Are there any other files in the folder with the backup files?
-----
   There will be other files from previous backup in this directory reading different timestamp

Are there only .isx files in the backup folder?  One per backup?


Quote
    What tool do you want to send the email with?
----
 Pure MSDOS batch command. No third party tool

There's a problem there.  No pure MSDOS batch command exists, to send an email."You use YYYYDDMM format "? 

-Yes appended to the file


"Are there only .isx files in the backup folder?  One per backup?"

-Yes Only .isx file

"What tool do you want to send the email with?"

-What options available here
Here's a snippet that will keep the 30 newest files in the backup folder that is in the current folder.

Remove the echo after testing.  It will simply echo the delete commands to the console at the moment.

Code: [Select]echo off
for /f "skip=30 delims=" %%a in ('dir backup /b /o-d /a-d') do echo del "backup\%%a"
pause

A VBS script has the ability to send email
sendmail, blat, and others are free email sending tools.

1037.

Solve : I want to create batch program with the script bellow. Please help me.?

Answer»

Hello everybody,

I have some file *.txt created in folder A. I want move them to folder B.

Condition:

+ If any filename.txt created from folder A, namesake filename.txt already EXISTS on the folder B.  It will display a warning: "Filename already exists, can not move"

+ If folder A is empty. It will display a warning: "Do not have a .txt file in the folder A"

Please help me.

Is this homework or a school assignment?
Is that one question or two, Salmon Trout? 



My question: I wonder if the OP wants to use copy and delete as the FUNCTIONAL commands? One, really, I wasn't sure if every English-speaking country uses the word 'homework' for work assigned to a student to be done at home.
Dear foxidrive and Salmon Trout,

This is not homework? This is the job I assigned.

I can only write the simple command:

Code: [Select]MOVE D:\Data\Desk\*.txt \\server01\user\mkt\Work
But I can not write the command line satisfying the following conditions:

+ If any filename.txt created from folder "Desk", namesake filename.txt already exists on the folder "Work" => echo Filename already exists, can not move
+ If folder "Desk" is empty => echo Do not have a .txt file in the folder Desk

Please help me.

Thank you very much
Quote from: Salmon Trout on June 11, 2015, 10:23:47 AM

One, really

I didn't mean it as more than a rhetorical question.  I should have said so.

Quote from: tomycao on June 11, 2015, 07:51:04 PM
This is not homework? This is the job I assigned.

I don't mean to make mountains out of molehills either but how come you have this job and don't have the knowledge to solve it?

I would still consider this a trivial question set by a school.

To Mods:  Should we avoid commenting on things in this way, when the task seems like they are avoiding learning what should have been discussed in class already?

I'd hate for the good name of the forum to be devalued by my fairly irrelevant comments - I can simply ignore such threads if that is preferable.

It would seem the OP has a job that requires him to you the one-line batch command to move a file. But he finds that operation throws an error.
In many real world jobs the issue is to fix errors, not write programs.

Maybe this outline represents what he wants to do.

Fetch a file name from souse list.
If  target directory does not have  that file
  Begin
    If source file not busy, move it to target
    Else complain
  end.
If more in list, repeat.

The above is NOT batch code. It is a way of humans expressing a possible solution.

Some IT PROS find that need to  spend as much time on an outline as the actual code.

OP, does this represent your problem?

This may help.

Code: [Select]echo off

set folderA=Put Name Of Source Folder Here
set folderB=Put Name Of Target Folder Here

for /f "delims=*" %%i in ('dir /b %folderA%\*.txt 2^>^&1') do (
if /i "%%i" EQU "File Not Found" (
echo No .txt Files In Folder A
goto :eof
)

if not exist %folderB%\%%i (
  move "%folderA%\%%i" "%folderB%" > nul
  echo %%i Moved To %folderB%
) else (
echo %%i Exists In %folderB%
)
)


Save the script with a .bat extension and run from the NT command prompt. Be sure to put valid paths in the two set statements at the top of the script.

  Quote
This is not homework? This is the job I assigned.

We don't help you do your job either... Quote from: patio on June 12, 2015, 04:11:19 PM
We don't help you do your job either...
Exactly. We do it for nothing, in our spare time and the OP who got a job by lying at the interview about their IT skills gets a. the CREDIT b. gets paid for our work and the worst part: c. probably doesn't understand why we object, just like the students who think that "research" includes posting "write my code for me" on forums.

Now that sidewinder has raised the bar and gone to the effort of providing code,
it's fun to give it a go in a different way.

Code: [Select]
echo off

set "folderA=c:\folder"
set "folderB=d:\folder"

if not exist "%folderA%\*.txt" echo Give me my money back, there are no txt files here&goto :EOF

for %%a in ("%folderA%\*.txt") do (
     if exist "%folderB%\%%~nxa" (
            echo "Filename already exists, can not move"
      ) else (
            move "%%~a" "%folderB%"
      )
)
I just thought... maybe I'm a hypocrite (see my post above) because when I am stuck for a bit of code I will happily search Stack Exchange... Quote from: Salmon Trout on June 13, 2015, 04:52:29 AM
when I am stuck for a bit of code I will happily search Stack Exchange...

There's no hypocritical comment or shame in that - you're a capable coder and saving time
instead of reinventing the wheel. 

Those people, and I shouldn't point the finger at the OP here, but there are so many bods
who ask for code about elementary tasks that are quite likely to be coursework, and they
aren't learning the skills to create code for themselves in the first place.

Can you imagine what software of the future will look like when so many people copy and
paste code that *might* do the job together, but they don't really follow what is going on
and - bug city will be the new normal.

Maybe it won't be quite that pronounced, and maybe the people asking are doing a course
which just NEEDS this coding as a requirement, and will never code again.

It's still lazy IMO and too often there is no thank you, or the same question is pasted
onto 23 forums and there is still no followup.

Oh, BTW, have I run out of rant-time yet?

Quote from: foxidrive on June 13, 2015, 08:57:13 AM

Oh, BTW, have I run out of rant-time yet?
No, you have roll-over from last month.  Dear Geek-9pm,

Thank you for your explanation.

I'm not a programmer, so my problem has description is not good .

Best regards


Quote from: Geek-9pm on June 12, 2015, 10:06:45 AM
It would seem the OP has a job that requires him to you the one-line batch command to move a file. But he finds that operation throws an error.
In many real world jobs the issue is to fix errors, not write programs.

Maybe this outline represents what he wants to do.

Fetch a file name from souse list.
If  target directory does not have  that file
  Begin
    If source file not busy, move it to target
    Else complain
  end.
If more in list, repeat.

The above is NOT batch code. It is a way of humans expressing a possible solution.

Some IT pros find that need to  spend as much time on an outline as the actual code.

OP, does this represent your problem?
1038.

Solve : batch program + Find and replace :(?

Answer»

I have file which has some lines.. e.g.

line no 20    # Every Vagrant virtual environment requires a box to build off of.
line no 21         config.vm.box = "test_15_4"
line no 22    # The url from where the 'config.vm.box' box will be fetched if it
line no 23    config.vm.box_url = "file:\\d:\\images\\test.box"

I have set a variable "replace = test_15_5".. and "Search = config.vm.box"

I need a batch code which will search "config.vm.box" in file and replace next string "test_15_4"  with %replace%.. Code should replace every occurrence in file.

Need this urgently... please help me...

Quote from: pawantlor on June 03, 2015, 03:54:51 AM

I need a batch code which will search "config.vm.box" in file and replace next string "test_15_4"  with %replace%.. This should replace string on only line number 21.

What restrictions on tools do you have?  Any tool available in Windows 7 home+ for example?I did not understand your qs.

I have one batfile which does something. I want to include new code in this bat file only. What new code should do is , to go to some file(name i will provide) , find config.vm.box and replace certain string from the same line. Quote from: pawantlor on June 03, 2015, 04:37:56 AM
I did not understand your qs.

I have one batfile which does something. I want to include new code in this bat file only. What new code should do is , to go to some file(name i will provide) , find config.vm.box and replace certain string from the same line.

This task can be done a number of different ways: some ways will fail when non-latin or 'poison' characters or unicode characters are in the file, or the filepath/name to be processed, and some ways are very robust or require less code.

So my question was to find out which version of windows you are using (I should have been clearer there) and also if you can use windows scripting host or other standard tools that comes with Windows.

I asked because there are times that people ask for a solution, and then they decide that they want a pure vanilla and basic script solution, when someone has already used their time to write some code.
My system is windows 7 professional.

I understood ur concern. File may not have Latin characters but can have all characters which can be typed using SIMPLE keyboard. And yes file has some file paths.

Example I gave has few chars and path, so give me code like that. Let me know if you need more info, I can provide you file if required.I locked your other thread. Please do not ask the same question more than once. Thank you.Anyone for solution?As was mentioned, many tools do not allow chars outside of the normal ASCII range and even some ASCII chars can not be used.
A very generic find and replace program would have to be written in C or some language that allows a low-level substitution.

But as mentioned, your Windows 7 pro already has some tools available. Notably Powershell is now provided in most version of Windows to give administrators a tool that can be used at the command kine. Sort of a batch extension.
There are so many variations, it is hard-to give a short simple example.
Here is one that might work:
http://weblogs.asp.net/efrancobisi/a-simple-powershell-script-to-find-and-replace-using-regular-expressions-in-multiple-files
Or maybe this:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/03/21/use-powershell-to-replace-text-in-strings.aspx
From these examples you can see that some kind of explanation has to be given about the objective.
If there are no forbidden  chars, one can use a simple batch file.
http://www.dostips.com/?t=batch.findandreplace
And there is an utility called SED that has been imported from UNIX to  MS Windows. See link below.
http://www.grymoire.com/Unix/Sed.html

The problem is that most tools require some kind of escape char to delimit the text you want to find and replace. Which means you would have to know ahead of time which chars would not be in the file. Even a utility that allows your to SPECIFY the escape char, you still have to know ahead of time if that char is not in the file.

Honest. nobody wants to confuse you.  The issue is to outline a clear, concise objective and identify potential issues. 





THANKS geek for your detailed explanation.

I know that there are different tool which will Have easy way to do this.. But problem is I am 90% done with my utility in batch, so I cannot move back and change tool. I am just remaining with this stuff..
If you have simple solution to this in bat irrespective of chars to parse.. Please provide.

I will try to remove all special characters/paths from the Input file in which I need to replace string and keep input file simple.Did not mean to say you have to abandon you rcode.
A batch file can call another program and then return to where it left off.
As you already know, the %variable% trick can be used in batch file to pass something on to another batch or program.

The quick way, for me, is to put one line of SED into your batch.
Code: [Select]SED 's/regexp/replacement/g' inputFileName > outputFileNameHere is a simple explanation of SED.
Quote
sed (stream editor) is a Unix utility that parses and transforms text, using a simple, compact programming language. sed was developed from 1973 to 1974 by Lee E. McMahon of Bell Labs, and is available today for most operating systems.
http://en.wikipedia.org/wiki/Sed
I would write another batch that invokes SED and then returns to the caller.

SEDJOB.BAT
Code: [Select]sed 's/%find%/%replace%/%input_file% >output.tmp
SED does no do an output file, so you have to have the redirect to do it.
The find and replace are the variables you made earlier. Likewise with input_file
You will have to copy the output to the original file.

Find a suitable version of SED here:
http://sourceforge.net/projects/gnuwin32/
That is the best I can do now. I have to go finish mopping the floor before the wife comes home. 
If anybody sees I made a mistake, please correct me. I have to go now.How to resolve with SED?

Any idea?
Wow... Quote from: pawantlor on June 03, 2015, 12:01:05 PM
Any idea?

Some person wrote this - it applies to you in this situation too:


Quote
The paragraphs below outline ways to get a script that works, and quickly.

When writing your request for help: be aware that providing accurate details makes it easy
for the people to write you a script that will work in your specific situation, and
they will often add extra code to handle situations that you may not have thought of.

If you do this then the very next reply is likely to be a script that will work.


On the other side of the coin: when details are hidden in made-up names and paths and file information
then nobody knows if you are using non-latin characters, or Unicode, or using poison characters for
batch scripts and so we can't include the appropriate code to handle your special situations -
and so the script you are given may fail.

If you have sensitive data then type over those parts.

Be aware that Batch files are often written around patterns in the data, text and
paths\filenames being processed, so the format and layout of the information is important -
so you can type over the sensitive parts but don't change the layout.


=================================================================

What happens with incorrect or POOR details is that a script is written based upon the limited information
that was given - and the next post is often from the question-writer saying "It doesn't work!"

That is usually followed by a very long series of posts where we try to ascertain what the problem is,
what the real details of the task are, and how it fails. 

The script that was supplied then has to be changed or rewritten:
and this wastes the  time of the volunteers who are giving FREE support, and is frustrating and
unsatisfying for the volunteers to have to write a script for the same task again.


Please be respectful to the people who give their free time to provide you with code,
please come back and tell them if the code helped,
and don't forget to say thank you after you receive some help. 

Be polite - social lubrication works on the Internet too.
foxdrive.. I did not understand you.. What do you have to say I am not respectful..
I am just a beginner.. I don't have much knowledge about stuff.. But what I know is I don't hurt anyone with just asking question.

I have replied to geeks reply, as he suggested to use sed. And I don't know sed, so I asked how to solve with sed..

I appreciate each one of you as you guys are the one who can solve my problem.. That is the reason I asked my qs to people who are mastermind..

I hope you understand and provide me solution.. i tried this way
but some issue i guess..

for /F "USEBACKQ delims=" %%j in ("%textfile%") do (
  set row=%%j
  IF "!row:config.vm.box=!"=="%%j" ( echo %%j>>"%outputFile%") ELSE ( echo %%j>>Nul  && ECHO config.vm.box = "%BoxName%">>"%outputFile%")
  PAUSE
)
1039.

Solve : Bat file to extract first row from several txt files?

Answer»

Hello.

I have SEVERAL .TXT files in the same directory (about 3,000) and I'd need to get a new txt file with 2 data of them. The txt file I need should have 2 columns: the FIRST one with the txt file name and the SECOND one with the first line of every file.

For example:

File: 1.txt
   Peter
   Germany
   Medical

File: 2.txt
  Mary
  Canada
  Teacher

File: 3.txt
  John
  USA
  Engineer

.....

And the file I need should be SOMETHING like:
1       Peter
2       Mary
3       John



Can this be done with MS-DOS?

 
Thanks in advance.Thanks but I've found the way you do it.

Regards.Yep. Pretty easy to do with a single FOR command and an echo command.Nice of him to let us know how he fixed it....

1040.

Solve : findstr search specific file types?

Answer»

I am trying to search for a specific string in certain type of files.  The problem is that below CODE is also showing me files that contains names like aaa.bat_new, aaa.cmd_20150512, etc.  How do I tell it to only search files ending in .bat and .cmd?
 
Code: [Select]findstr /S /I d\^: *.bat *.cmdI don't see a search string there, also what does d\^: do?I am search for anything that contains d: which is my d-drive.  The \^ sign is required to search for the colon.  I am getting what I WANT EXCEPT it is returning filenames that does not end in .bat nor .cmd.What string are you searching for in the files?
I am searching for the string "d:" only in files that have an extension of .bat or .cmd. 

The problem is that there are files which have a hard-coded path for programs which may not be in the expected location when upgrading the OS from Win 2003 to Win 2008.  I just want to MAKE sure nothing has been missed. Quote from: et_phonehome_2 on May 27, 2015, 01:16:26 PM

I am searching for the string "d:" only in files that have an extension of .bat or .cmd. 

Try this.

findstr /s "d:" *.bat *.cmd

 If you want to find d: and also D: then place an /i switch before the QUOTED string like this

findstr /s /i "d:" *.bat *.cmdThanks alot, that worked.....
1041.

Solve : help to create a file batch for tracert?

Answer»

Hello, my name is matteo. I want to create a file BATCH for tracert. On a text file I have a list of IP addresses that do tracert. I would LIKE to create a batch file that executes the tracert ip of these, providing input in this txt file and GETTING output a txt file with the LOG of the tracert. Can you help me? I have no idea how to do !!! please it's very important for me.


thanks so muchHow many IP addresses are going to be traced and would these ever change?

Are you looking for a problem with a DNS route? Quote from: Aknort on June 19, 2015, 08:17:36 AM

Hello, my name is matteo. I want to create a file batch for tracert
I would like to create a batch file that executes the tracert ip of these

Welcome to the forum matteo.

We can help you create a batch file - but you will have to tell us what you want in the log file.
Do you want the entire tracert output, and that is all?

A for /f loop will let you read the list of IP addresses in the text file.thanks for the answers. In the log file I want the entire tracert output. In my .txt IP addresses are a variable number, and remain the same in each simulation, but between different simulations change in the number and type.
I need to perform a command similar to:

C: \ User \ DESKTOP \ Work \ tracertscript.bat Source IP.txt

where tracertscript.bat is  is the script that I want to create and SourceIP.txt is the list of IP (the input script).

not having the basics of programming I desperately need your help, thanks so much

Matteo


This may help - test it on your end:

Code: [Select]echo off
for /f "usebackq delims=" %%a in ("c:\folder\file.txt") do tracert %%a >>file.log
 greeeaaaat 

tnx
1042.

Solve : Creating A Dos Batch File - to do the impossible :)?

Answer»

Hey Guys,

Im looking to use an MS-Dos batch file to register a load of .dll files with regsvr32.exe

Within my job, when I install our custom application, we sometimes have to manually register nearly 50 .dll files on anything between 1 and 50 desktops, so creating a batch file would save a lot of time and hassle.

Is this possible?

Any help would be much appreciated!

Thanks in advancep.s. I'm not a complete n00b 

p.s.s if a batch file isn't able to do the job.... any recomendations?

  Thanks  I expect that it is possible.

If you can register a single dll with

start "regsvr32.exe c:\temp\mydll.dll"
or whatever your dll is called

Then you could create a whole list of them ... if they all lived in one directory, you could even automate that by using a FOR loop to pick them all up

Good luck
GrahamAhhh, makes sense.

would the FOR loop be simple?

When it comes to the FOR command I have a lil trouble understanding it! 

A bit of example code to get me on track would help.. anyone? 

p.s. they all would be in a single directory.

p.s.s feel free to use example1.dll and example2.dll

again all help is appreciated! 

ok, really simple example, replace the path in the brackets with the actual path

RegAll.bat
=======

for %%a in (c:\winnt\*.dll) do start "regsvr32.exe %%a"

=======

The %%a holds the value of the dll name in each iteration (one for ever *.dll found)

This one liner is supposed to be in a batch file, if you paste it directly on to the command line, the %%a should be replaced by %a (thats just 1 % symbol)

Cheers
Grahamok let me give that a try....

Thanks Graham  So, if this was a batch file, then RAN within the c:\Program Files\workfolder\  this would register all .dll files within the directory the batch file was ran?

=======

echo off
%%a in (c:\Program Files\workfolder\*.dll) do start "regsvr32.exe %%a"
pause

=======

Any help would be great! (graham... nudge nudge)  Thats the theory ... I confess I havent ACTUALLY used the start command very much.

Try running it -- but make the first line
Echo On
You will be able to watch it progress - and see what went wrong if it failed.

Oh, the next line starts with 'For' -
for %%a in ("c:\Program Files\workfolder\*.dll") do start "regsvr32.exe %%a"

Ive put quotes around the c:\program files ........ *.dll, because it contains a space, it wouldnt work otherwise

Good luck
Graham
ok one last question.

As we are putting the directory within the code, can the batch file be ran anywhere?

The reason I ask = multi directory. So I could have the code below within the batch file, run the batch on my desktop, and the code below would register all .dll files within the directorys specified?

================

echo on
for %%a in (c:\Program Files\workfolder\*.dll) do start "regsvr32.exe %%a"
pause
for %%a in (c:\Program Files\workfolder\data\*.dll) do start "regsvr32.exe %%a"
pause

================

Thanks again for any help received!  You could (but you omitted the quotes !!) - even better would be this

================

Code: [Select]echo on
for %%a in ("c:\Program Files\workfolder\*.dll" "c:\Program Files\workfolder\data\*.dll") do start "regsvr32.exe %%a"
pause================

unless you particularly wanted the break between processing the 2 directories
Grahamrock and roll thanks Graham.

You a legend

  ok slight problem with our lil code..... 

When the Batch file is executed I get a ton of CMD popups. One for every .dll file that it registers....

Anybody know any code that will either:

1. Keep EVERYTHING in one window?

or

2. not open a seperate window for every .dll file.

============================================================
echo on
for %%a in ("c:\Program Files\workfolder\*.dll" "c:\Program Files\workfolder\data*.dll") do start "regsvr32.exe %%a"
pause
============================================================
p.s. its not because "echo" is on...  Just checked the syntax for Start, the /B param MEANS keep everything in 1 window - thus

============================================================
Code: [Select]echo on
for %%a in ("c:\Program Files\workfolder\*.dll" "c:\Program Files\workfolder\data*.dll") do start /B "regsvr32.exe %%a"
pause
============================================================

Give this a whirl
GrahamFantastic Graham, it works!

As what is shown seems like mumbo jumbo (doesn't state WETHER or not the .dll's are actually being registered)  but after counting the amount of lines it did produce, twas equal to the amount of .dll's in each folder. Im just going to have to wait to test it when I have a machine to test it upon.

Thankyou again Grahami have to register a dll using batch file but the dll must be register as a administrator.

example i want to register xceedzip.dll with command prompt open as a administrator and register the dll

1043.

Solve : .bat question answer guide help me please?

Answer»

Hello Guys , i am a hardware technician i needed a software to keep my serials cracks LICENSE safe , but i don't trust any of them .

so i needed to make .bat FILE  , i write something and it reply for me the answer i need.

example : avg SERIAL
              : ***************
if someone have the code please share it with me and mark please where i can put the QUESTIONS and answers 

thank you so MUCH guys ([email protected])

1044.

Solve : Creating a game in DOS - Saving game to a file??

Answer»

Hi guys, just for the *censored* of it i WANT to make a text-based adventure game in MSDOS, I was wondering, is there a way I can save the users game progress to a file?

For example:
I have a piece of code which asks the user to pick a Class, so how could I now save this to a file and then call upon it later?

Thank you! save the variables to a file
Code: [Select]>>savedgame.txt echo CLASS=%CLASS%
reload the variables from the file
Code: [Select]FOR /F "delims=" %%G in (savedgame.txt) do SET %%GThis caught my interest... not hijacking this thread, but just wanted to inquire for additional info on this which might help Tomwatts with his game design.

When dealing with multiple variables written for a single file to write to, what is the best method of reading back the data in batch?

Such as if you had:

Class = Human
Level = 3
Gold = 2400
WeaponMinDamage= 5
WeaponMaxDamage= 10
Armor = 23
XLocation = 6
YLocation = 84


and had a file appended such as SavedGame.log with

Quote

Human
3
2400
5
10
23
6
84

Would it be better to be dealing with delimited data such as
Quote
Human,3,2400,5,10,23,6,84

In which you know that the whole of the data contained between comma delimiters should be used so that you don't have to read in an unknown length of characters?

And if the best method is to use a delimited data file, could an example be given on how to best implement this? As well as if just appended data is best to have each variables VALUE on a separate line and it doesnt matter of length because of character line isolation from the following lines in which there is an instruction to read an entire line to end of line such as maximum allowed character length per line, an example of implementing that?

If you are going to use delimited data then you need to make sure all separated values also have quotes because the FOR command will drop empty tokens.
I prefer the method I used above.  MAKES it REAL easy to define the variable.

But you could also do a flat file with one line for each variable and redirect the file into a code block.

Code: [Select]< savedgame.txt (
set /p class=
set /p level=
set /p gold=
set /p weapondamage=
)Thank you so much for that! That's worked a treat!

Another thing - How could I create some field validation for the character selection page?

set /p input=
if %input% == 1 goto Warrior
if %input% == 2 goto Hunter

so at the bottom i'd have something like..

if %input% == 3> echo Invalid Selection

Any ideas? Or am i thinking into this too much?And thank you very much guys!Use the CHOICE command if you are using the batch file on Windows versions greater than XP.  Windows XP did not have the choice command.  The choice command will not continue until you enter in a valid choice.Hello!

Firstly my APOLOGIES for the rubbish reply, been so busy with work the past few days!

The CHOICE command works perfectly, such a nice solution to the problem I was having! I'll be implementing this!

It's great having a community to talk to about this, i'm sure when i'm done you'd like a copy? If so, i'll make you get one.

The next thing I am going to do is implement a data file so I can have an 'Inventory' of sorts too!

I'm not using Windows XP btw, i'm using Win 7, but for some reason my profile says Win XP, i need to change this.

Regards,
Tom

1045.

Solve : AST premium 386 tower circ late 80's?

Answer»

Hi I am new to this forum and hope someone can help.

I am still using this tower running Cadd6 but my battery failed so lost Bios settings....I have managed to re-config everything from the manuals but my setup has a parallel card installed that needs the ASTSETUP disc to assign this as LPT1 so that i can use my plotter.

Computer working back to normal drawing fine but wont plot..

Can you help ?

Kind regards

Steven King (UK)

Did you replace the battery ? ?
if so did you re-install the drivers for the LPT device ? ?At a loss as to why a battery would have lost your settings for LPT1 config. The config.sys and autoexec.bat files should not have been tampered with, and so driver setting for software config should not have changed as a result of this. The LPT1 port in the bios should have been the default address etc with nothing special I am guessing. Do you have the installation manual for the plotter that might indicate any special LPT1 config?

Did you format the drive and rebuild clean and lose your prior config? Quote from: DaveLembke on July 10, 2015, 08:54:46 PM

The LPT1 port in the bios should have been the default address etc with nothing special I am guessing.

Good point.  The LPT1 port may have been set to a non-standard address, or using EPP/ECP vs SPP

A 386 PC is very old. Very, very old.
Quote
At a loss as to why a battery would have lost
 your settings for LPT1 config.
On some old systems the LPT could be set to one of three ADDRESSES. This would be in the BIOS. The default setting may have been different that what the OP had.

Current articles on  LPT do not have this detail. You need to look in the original documentation for that old motherboard.
Quote
Most PC-compatible systems in the 1980s and 1990s had one to three ports, with communication interfaces defined like this:

    Logical parallel port 1: I/O port 0x3BC, IRQ 7 (usually in monochrome graphics adapters)
    Logical parallel port 2: I/O port 0x378, IRQ 7 (dedicated IO cards or using a controller built into the mainboard)
    Logical parallel port 3: I/O port 0x278, IRQ 5 (dedicated IO cards or using a controller built into the mainboard)

If no PRINTER port is present at 0x3BC, the second port in the row (0x378) becomes logical parallel port 1 and 0x278 becomes logical parallel port 2 for the BIOS. Sometimes, printer ports are jumpered to share an interrupt despite having their own IO addresses
https://en.wikipedia.org/wiki/Parallel_port
Hi Thanks for all your replies thus far......
I have been working HARD on my building site and just run out of steam.....I will gather all the information and the course of events leading upto and beyond the problem and reply and post text from AST manuals. I have some DRAWINGS to do so eager to get plotting On older 386's a duff battery would lose the settings as it's BIOS CONTROLLED...
1046.

Solve : Running another batch job inside an already executed window?

Answer»

Hi guys,

I am creating a game in DOS, and i'd like to SPLIT the game files up for easier editting, is there any chance I am ABLE to execute another batch job WITHIN one i am already running?

Example:
ECHO Welcome to game
echo Press 1 for Warrior class
echo Press 2 for Mage class
choice /c 12 /n
if ERRORLEVEL 1 goto Warrior
if ERRORLEVEL 2 goto Mage
:Warrior
Run Warrior.bat

Then the Warrior.bat would start up but in the same window for the user, is this possible?

Or any other suggestions are greatly appreciated, thanksYou WANT the call keyword.

Type help call at a cmd prompt.
Oh that's fantastic! I knew it'd be easy! Haha, thank you sir

1047.

Solve : Automaticly create users and assign to groups batch script?

Answer»

For my GCSE Computing I need to find out how to automate the task of creating users and assigning them to groups. I will be using COMMAND prompt running on Windows XP (running through virtual box on windows 7).
I would like help with how to create, edit, save and run a windows batch script in cmd please.

The code should be mainly inside a loop which ALLOWS the user to repeat the process of creating and naming a user and assigning them to an existing group or a new group.

Any help/advice is much appreciated Quote from: thmoses on June 29, 2015, 01:25:52 AM

For my GCSE Computing I need to find out

It would help you to read about the subject, and try to automate some tasks - then come and
ask specific questions about THINGS you find difficult.

Here is the Linux task I need to change to work on MS-DOS:

"13. Linux enables tasks which are regularly carried out to be automated through the use of shell scripts. Plan write and test a shell script that could automate the task of creating new users and assigning them to groups."

This is the task I am currently on:

"14. Discuss how some of these tasks could have been done in a computer system running Windows or another operating system."
For this task I need to do some primary research, which is why I am here.

Here is the pseudo code for the task that I wrote:

Repeat = 1 #This initializes the repeat variable
Counter = 0 #This initializes the COUNT variable
WHILE repeat = 1 #This starts an iteration of something while the repeat variable is 1
   OUTPUT “Please enter the username for the new user”
   INPUT = username
   Add the user username
   Counter = counter + 1
   WHILE repeat = 1
      OUTPUT “Please enter the name of the group for the new user”
      INPUT = group
      IF the group ALREADY exists THEN
         Add username to group
         Repeat = 0
      ELSE
         OUTPUT “The group group does not exist.”
OUTPUT “Do you want to create it as a new group (Y)”
OUTPUT “Or enter another group to add the user username to (N)?”
         IF INPUT = Y THEN
            Create group called group
            Add username to group
            Repeat = 0
         ENDIF
      ENDIF
   ENDWHILE
OUTPUT “username has been added to the group group”
OUTPUT “Do you want to create another user? Y or N”
IF INPUT = N THEN
      Repeat = 0
ELSE
   Repeat = 1
ENDIF
ENDWHILE
OUTPUT “You have successfully created counter more users and added them all to groups.”


Here is the linux code:




----------------------

I would like to know some starting tips on how to write something like this using the MS-DOS please. The thread may be closed if you want someone to do your course work for you.

Asking specific questions is probably fine.Sorry, we won't do your homework for you.
1048.

Solve : Loging error in TXT file - Please help?

Answer» HI,

Here is my code :

echo off
for /f "tokens=2 delims=:." %%x in ('chcp') do set cp=%%x
chcp 1252>nul
mkdir "HIL02 - Hôtel XYZ Montréal\03 - Hôtel XYZMontréal - Banquet + Pâtisserie">>Logfile.txt 2>&1
chcp %cp%>nul

The error type will be recorded in the logfile.txt.  This works great.  The thing is that my actual file has over 11,000 entry to process.  Out of these, I have only 7 that doesn't work.  I get the error message just fine in the logfile, but I need to know which lines are the problem.

Is there a way to get that information somehow? In my logfile, for each error, I would like the problematic path name to be copied.

I already made research for characters such as ? / () # and these are taken out.  I have no clue where the problem lies.  I also check for path length (max 260 allowed) and I'm way under the limit even including the sub-folders created.

ThanksWhat is this code supposed to do?
It creates a bunch of folders and subfolders based on a list.  Each customer has a folder.  Then each each of their folders there is standard sub-folders.  This code, generates it all automatically.

There must be one in the bunch that has a bad character or something in it but I can't find it.  The logtxt file, logs it as a wrong path name, but I can't find which one because I have over 11000 lines to look at.What's with all the chcp stuff?It ALLOWS me to use french character such as é à You mean there are 11,000 lines like this?

mkdir "HIL02 - Hôtel XYZ Montréal\03 - Hôtel XYZMontréal - Banquet + Pâtisserie">>Logfile.txt 2>&1

Yes but with different information according to each customer.  It worked for them all except one.  So basically I need to find out which line cause the error.  This code tells me the error, but do not tell me which line doesn't work though.Why have you got the directory names in the batch file itself? Having 1000 lines makes it very cumbersome. Why don't you have them in a text file and read the lines using FOR /F? That way you have each line in a variable and you can isolate the problem lines.

Honestly, I'm building this as I go along by reading forums and multiple information posted.  I never programmed DOS before.  There is probably other solution, simpler maybe, but the problem remains that I need a log that explicitly says which line doesn't work.

Do you think that having the paths in another file will work?  Surely I will still need a line of code or something that program the batch file to export in a log file the information? Quote
mkdir "HIL02 - Hôtel XYZ Montréal\03 - Hôtel XYZMontréal - Banquet + Pâtisserie">>Logfile.txt 2>&1
Heck I want to know how much time you spent typing this out 11,000 times.  The problem may be a folder name with a character that isn't valid in your codepage.

Put all your folder names in a "c:\folder\file.txt" file and try the code below in an empty folder:

It may also SHOW folders that contain a character that is translated by the code page, so you may have
other folders in the errorlog.txt file.  You can manually check to see if those folders exist, if there are not too many of them.

At least that's how I understand codepages issues, as I don't often use non-latin characters.

Code: [Select]echo off
chcp 1252
(
   for /f "usebackq delims=" %%a in ("c:\folder\file.txt") do (
      md "%%a"
      if not exist "%%a\" echo error in line "%%a"
   )
)>"c:\folder\errorlog.txt"
echo done
pause
Quote from: Squashman on July 15, 2015, 02:53:44 PM
Heck I want to know how much time you spent typing this out 11,000 times.

Excel baby!  The information was exported from our ERP system in an excel file.  All I had to do is concatenate the cells to have what i wanted.  No typing to do at all.  Just copy/paste Quote from: foxidrive on July 16, 2015, 01:33:57 AM
The problem may be a folder name with a character that isn't valid in your codepage.

Put all your folder names in a "c:\folder\file.txt" file and try the code below in an empty folder:

It may also show folders that contain a character that is translated by the code page, so you may have
other folders in the errorlog.txt file.  You can manually check to see if those folders exist, if there are not too many of them.

At least that's how I understand codepages issues, as I don't often use non-latin characters.

Code: [Select]
echo off
chcp 1252
(
   for /f "usebackq delims=" %%a in ("c:\folder\file.txt") do (
      md "%%a"
      if not exist "%%a\" echo error in line "%%a"
   )
)>"c:\folder\errorlog.txt"
echo done
pause

This is very close.  The only problem is that it doesn't follow the folder structure requested; it creates folders for each word and characters instead.  I tried your code with mkdir and I get the same problem.

There is a minor tweaking to do i'm GUESSING to make it work.

*** Update : I found my mistake.  In my file with the information to create folders, all paths were between "".  I removed it.  Also I had to change md to mkdir.  Works like a charm!  It showed me the exact 7 lines that had a problem.  I fixed it and now I have 14178 folders & subfolders or subfolders created automatically in about 30 seconds!

Thank you so much for your help!I'm pleased to hear it helped you.

Just adding here that md and mkdir do exactly the same thing in Windows.


Try these two:

Code: [Select]md "123"
mkdir "456"
1049.

Solve : Preliminary research for creating users in MS-DOS?

Answer»

This is for the preliminary research section in my CA, i need to compare linux and windows. At the moment i am using debian compared to MS-DOS, is there any tips that you can give me on how to go about creating shell scripts in MS-DOS to AUTOMATE the creation of users and assigning them to groups.

Thanks
WillNET USER
NET GROUPThanks for that help, is there any way in which I can repeat the process 10 times Yes.


FOR /?what text editors can i use to write the script in because i can not find one

thanks
will
  Notepad has been included in Windows since the very first version.  Has to be on your computer.

Regardless of that I prefer to use Notepad++ because it highlights keywords and has other useful features that help with writing many different TYPES of scripting languages. Quote

what text editors can i use to write the script in because i can not find one
If in strictly DOS you could use EDIT such as EDIT ThisText.txt which will create ThisText.txt and WHATEVER you type into it is saved  in the end if you save it etc. There were some other text editors for DOS many many years ago, but I mainly used EDIT.

If you are in Debian instead of MSDOS you could use a Linux editor such as VIM https://wiki.debian.org/vim

However I havent created any content for MSDOS from a Linux environment before and all my editing in linux is for Linux application.

Looks like it should work ACCORDING to here: http://www.howtogeek.com/199687/how-to-quickly-create-a-text-file-using-the-command-line-in-linux/
1050.

Solve : Batch process to record load times of applications/programs etc?

Answer»

In the past I have written some batch log scripts that I rename the actual EXE of a program to be monitored, I then create a simple batch that starts the program under its different file name identity and records when the program was run appended to a log, and this batch file I would compile to a EXE with a BAT to EXE compiler so that the OS continued to run as if nothing ever happened with same paths etc. Such as the following, and in this example I will use notepad.exe

Batch File is compiled with Bat 2 EXE as Notepad.exe and placed into C:\windows\system32\ with the following instruction
Quote

echo. Notepad Run on %date% at %time%>>c:\systemlog\notepad.log
START c:\windows\system32\notepad1.exe

I used this mainly to get statistical info on how often and when specific programs were being launched by users when I use to work in IT at a prior job.

Question I have now is that I want to record how long it takes for an application to get from its start to run condition to its fully loaded state.

Sure you could take a stop watch with you and test between clicking on a program and when you visually see that the program is fully up and ready for input to then stop the stop watch, but I am checking in here to see if there is a method to do this with batch or vbscript or combination etc.

I KNOW that with tasklist I could have it test for when a windowtitle becomes active, however that would not show the actual completion time in which the program loaded, it would just show the INSTANCE in which tasklist detected it as a valid window title name.

Maybe this cant be done because looking at it from a programming standpoint, the easiest method would be to have the program such as notepad1.exe which is being started have a routine at the end that states that its fully loaded in which the program to run itself responds back, however this is not a valid method for programs that are compiled and illegal to decompile to add features like a response back 

If this cant be done in a batch file maybe a screen parser might work to look for a trigger characteristic on the users display in which only when the program is fully loaded would it trigger a positive for such as File to be displayed in the top left corner of a window for notepad etc.

The biggest problem with going the complex route to parse and OCR a screen is that its going to use a lot of processing power to parse, test the capture, and refresh the results until a positive hit is detected. There is info here on how to do it with screen captures, but a live display to constantly monitor for a trigger and then log would just cripple a system I feel. http://stackoverflow.com/questions/2986486/parse-text-from-a-screen-grab

My assumption is that I would need to basically still go with the same method as I have done in the past with renaming the actual EXE and creating a batch file as that same EXE's name that calls to the alternate named EXE in which the start time is easy to record and append to a file, but from there on to test for when the program is fully loaded I am at a loss as to how to pull it off without pulling too many resources that would skew the data. 

Its my understanding that

Quote
echo. Notepad Started on %date% at %time%>>c:\systemlog\notepad.log
START c:\windows\system32\notepad1.exe
echo. Notepad Loaded Fully on %date% at %time%>>c:\systemlog\notepad.log

Is not a valid way to measure loadtime of applications because the START instruction starts the program and once the program is started the batch moves on to the next instruction vs waiting for the program to be in its completely full open state of operation for user input. Otherwise this would be easy.  Not sure if this will suit your needs...

See Here...Thanks Patio

This site you linked had this info:
Quote
FYI - I don't think timeit works on Windows 7 64-bit. You get the error "Unable to query system performance data (c0000004). Instead, use PowerShell's "Measure-Command" like Casey.K suggests:

I guess I will be checking into powershell's Measure-Command since the OS would be a non-server OS such as XP, Vista, 7, 8, 8.1, or 10Yeah...there's a few other hand authored solutions there as well....Hope it helps.Just read down to this interesting batch there that you call the batch file followed by the application to launch and it records how long the application was active for. Going to save this batch for someday when I need to keep track of application use lengths. I could have used this way back when we were looking at use frequency as a better measurement of what programs are used and for how long even if just running idle.


Code: [Select]echo off
setlocal

set start=%time%

:: runs your command
cmd /c %*

set end=%time%
set options="tokens=1-4 delims=:."
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100

set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if %hours% lss 0 set /a hours = 24%hours%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if 1%ms% lss 100 set ms=0%ms%

:: mission accomplished
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo command took %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)
For a program that runs and at completion closes on its own this would work perfect for if you dont have access to the source code to just add a logger to the program internally. Very Cool. I think I am going to play with powershell and see where that leads.

If the only option this way is to find when the programs ended vs got to a ready to run state, then maybe I could pull off a CPU monitoring trick some how. Where say you know the CPU is idle at 3% with nothing else going on, and you launch the program to start and the CPU is going to use greater than 3%, and sense when the CPU drops back to an idle value with the application running, so say the program loads and the cpu bounces between 40 and 100% and finally comes to rest at 6%. You could have a process run that doesnt eat up too much processing power itself to then trigger when CPU goes equal to or less than 6%. However this  would require so much fine tuning that it would probably be easier to have a person stop watch it. And every system that would run this would have to be custom tweaked for trigger point of CPU activity back to idle with application running
Couldn't you just include a basic app task in the batch which would tell you when it get's to the usable point and time that ? ?
What you are trying to do is likely impossible. And I tend to avoid using that word. But it is impossible in the sense that it is effectively a variant of a computer problem that nobody has ever found a solution to, the halting problem.

Furthermore, It's not even as well-defined. The halting problem is effectively the problem if creating a program/algorithm to determine if another program will halt (hang), without hanging itself. What it means for an application to be "Ready" is going to be application-specific, and the method of determining it is in that state is going to be equally specific.

As you mentioned, could just check and wait for the application to become idle (use less than, say, 10% of CPU for some time frame, such as 5 seconds) but that will probably trigger for splash screens (Which sometimes incorporate a full on sleep for a few seconds to make sure the splash screen actually displays), and if you set the delay longer to compensate, you'll detect the program is "ready" sometime after it actually becomes ready. The actual CPU Utilization might be hardware dependent as well. Even while starting Word doesn't seem to use more than 3% for me, for example.

The taskbar icon is useless as you noted. You also cannot test to see if the Application's Main Window has started to respond, because Splash screens will count as the Main Window. OCR doesn't make it any easier because you still won't necessarily know what you are looking for. And if you use "OCR" than you'll have to adjust based on the selected theme and if the system is using some sort of skin or different colour palette, not to mention dealing with System DPI settings.


Also, re your 'auditing' tool that records programs that were launched- One limitation is that you need to create "alternate" executables for every program you want to watch. However it would probably be useful to know when people run unauthorized software somehow, not to mention nice to not have to deploy a bunch of new copied files when you change software around, so being able to record any executable would be nice. It would be possible to write a service that intercepts Windows WMI Events and detect when applications launch and exit. I do that for my company's Updater program for the purpose of "watching" which of our programs launch and terminate, but ended up abandoning the idea mainly because the updater would not be running very often or long enough for that information to be very useful. (And the original idea of showing different icons in the updater for running and not running programs seemed excessive) I expect it would be possible to use from VBScript, as WMI is sort of intended for VBScript. Effectively WMI allows you to create queries and one feature allows you to receive an event notification when the results of a query change. I was going to paste the code here but C# probably wouldn't be very useful.


Thanks BC for the well in depth info on this matter. As well as in regards to:

Quote
Effectively WMI allows you to create queries and one feature allows you to receive an event notification when the results of a query change. I was going to paste the code here but C# probably wouldn't be very useful.

This sounds very interesting. So you could run a query save the info temporarily, and then run a query again and compare for changes, and then when differences are detected report on the differences essentially.

Also I dabble in C# so if you want to share C# here, please feel free to do so as for I would probably learn from your code example etc.

Quote
What you are trying to do is likely impossible. And I tend to avoid using that word. But it is impossible in the sense that it is effectively a variant of a computer problem that nobody has ever found a solution to, the halting problem.

I was thinking it might be impossible, however I had to share here to see if there was a method that goes beyond my technical means of carrying this out. I think the biggest problem is that a system monitoring itself is going to offset factual information of how long it really takes to get a program from launch to halt condition in which its ready for user input.

As far as the CPU monitoring method for idle after launch of a program you mentioned it would trigger splash screens. What do you mean by this? Is this related to parsing the screen looking for CPU usage vs using another method for detecting CPU utilization status? After I walked away from the computer before when I posted and suggested a method might be to detect CPU usage, I realized in deeper thought that there might be a race condition with this, that the program itself that is looking for an idle state might not be able to ever detect an idle state as it happens as for the minute the program triggers even if after a sleep condition its going to use the CPU and cause a spike of activity until it goes back into its rest/sleep state, so it might never actually detect less than 10% etc. However if a service was created that read in the CPU for say 2 seconds and then stopped monitoring when called by the other program which creates a spike of CPU activity, it wouldnt be reading the live data direct from CPU that it itself created a spike to affect itself, but instead it would get the average for 2 seconds from the service. But that again assumes that the service isnt CPU intensive.

I guess I will leave this with the understanding that others have been where I intended to go and there is no good solution for this.

If there was a solution it could have been coded in any script or programming language to pull it off, didnt need to be specifically in batch, however the most lightweight processing could be achieved through batch and thats why I decided to post this here even though it might really be geared towards the programming or other section.

Thanks for all input on this. 



I'm officially outta my league on this one...sorry... Quote from: DaveLembke on July 25, 2015, 12:28:38 PM

This sounds very interesting. So you could run a query save the info temporarily, and then run a query again and compare for changes, and then when differences are detected report on the differences essentially.
I'm not sure how it works inside of WMI. You merely register for the event- it will notify when something changes. I had it set to watch SELECT * FROM Win32_ProcessStartTrace and SELECT * FROM Win32_ProcessStopTrace which would detect when a program starts and closes respectively. I think internally WMI is actually polling.

Quote
Also I dabble in C# so if you want to share C# here, please feel free to do so as for I would probably learn from your code example etc.
I tried to separate it into a "sample" type program but it doesn't seem to work properly, or it may not work on Windows 8 or something (I know it works though since the debug logs from customers definitely have the info!) It also looks like it may take up to 5 seconds to actually get the notification, so it probably wouldn't work (beyond actual logging that programs launch/exit). At any rate, here it is. Really it's just a class that get's used elsewhere:

Code: [Select]using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace ProcessWatcher
{
   
        public class ProcessEventArgs : EventArgs
        {
            public ProcessEventArgs(Process pProcess)
            {
                ForProcess = pProcess;
            }

            public Process ForProcess { get; private set; }
        }

        public class ProcessLaunchEventArgs : ProcessEventArgs
        {
            public ProcessLaunchEventArgs(Process pProcess)
                : base(pProcess)
            {
            }
        }

        public class ProcessExitEventArgs : ProcessEventArgs
        {
            public ProcessExitEventArgs(Process pProcess)
                : base(pProcess)
            {
            }
        }
        /// <summary>
        /// I got the idea for the Updater to display which programs were already running. The main issue was that
        /// it would have needed polling. Thankfully, there are WMI classes that can be used to actually receive event notifications
        /// for launched applications. From that we can create a Process object (or at least defer creation) and then
        /// handle the Exited() event to detect when a process exits.
        /// This class basically wraps both to allow for hooking of two static events which will be fired automatically.
        ///
        /// </summary>
        public class ProcessEvents
        {
            private static ManagementEventWatcher startWatch;
            private static ManagementEventWatcher stopWatch;

            static ProcessEvents()
            {
                //this will work in Win XP, but not Vista or 7 or 8 if the process is not elevated.
                //it will work on XP as-is, and as long as we ignore the error we should be fine.
                //Arguably we could take a really weird Polling approach, but that would be less than pleasant.
                try
                {
                    startWatch = new ManagementEventWatcher
                        (
                        new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
                    startWatch.EventArrived += startWatch_EventArrived;
                    startWatch.Start();
                    stopWatch = new ManagementEventWatcher
                        (
                        new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
                    stopWatch.EventArrived += stopWatch_EventArrived;
                    stopWatch.Start();
                }
                catch (Exception exx)
                {
                    Debug.Print("Exception trying to start WMI Process Watcher:" + exx);
                }
            }

            public static event EventHandler<ProcessLaunchEventArgs> LaunchEvent;
            public static event EventHandler<ProcessExitEventArgs> ExitEvent;

            private static void InvokeLaunch(ProcessLaunchEventArgs ev)
            {
                var copied = LaunchEvent;
                if (copied != null)
                {
                    copied(null, ev);
                }
            }
            private static void InvokeExit(ProcessExitEventArgs ev)
            {
                var copied = ExitEvent;
                if (copied != null)
                {
                    copied(null, ev);
                }
            }

            public static void Cleanup()
            {
                if (startWatch != null) startWatch.Stop();
                if (stopWatch != null) stopWatch.Stop();
            }
            private static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e)
            {
                try
                {
                    int ProcessID = int.Parse(e.NewEvent.Properties["ProcessID"].Value.ToString());
                    Process ForProcess = null;
                    try
                    {
                        ForProcess = Process.GetProcessById(ProcessID);
                    }
                    catch (Exception)
                    {
                        ForProcess=null;
                    }
                    InvokeLaunch(new ProcessLaunchEventArgs(ForProcess));
                    Debug.Print("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value);
                }
                catch (Exception)
                {
                }
            }
            private static void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
            {
                try
                {
                    int ProcessID = int.Parse(e.NewEvent.Properties["ProcessID"].Value.ToString());
                    InvokeExit(new ProcessExitEventArgs(Process.GetProcessById(ProcessID)));
                    Debug.Print("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value);
                }
                catch (Exception)
                {
                }
            }
        }
    }


Then it would be used by hooking the events, something like this:

Code: [Select]using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProcessWatcher
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            ProcessEvents.LaunchEvent += ProcessEvents_LaunchEvent;
            ProcessEvents.ExitEvent += ProcessEvents_ExitEvent;
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new frmProcessWatcher());
        }

        static void ProcessEvents_ExitEvent(object sender, ProcessExitEventArgs e)
        {
            Console.WriteLine(e.ForProcess.ProcessName + " Exited.");
        }

        static void ProcessEvents_LaunchEvent(object sender, ProcessLaunchEventArgs e)
        {
            Console.WriteLine(e.ForProcess.ProcessName + " Launched.");
        }
    }
}

Quote
As far as the CPU monitoring method for idle after launch of a program you mentioned it would trigger splash screens. What do you mean by this? Is this related to parsing the screen looking for CPU usage vs using another method for detecting CPU utilization status?

Each process has process utilization that can be inspected- I'm referring to the Process's CPU utilization, not the CPU utilization in general. If we try to detect when the program has finished loading based on when it's utilization drops off, it will think it is done when a splash screen is shown, because most splash screens include a purposeful "sleep" where they do nothing and don't use any processor time.

Adding to what I mentioned, I discovered the inconsistency. it appears i was mistaken, it still works on Windows 8.1 the same way as on XP/Vista/7. However, it seems like it only works properly with very high level privileges, in this case it seems the logs I am seeing that show a trace of programs that launched is coming from the scheduled updates which run via the task scheduler under the ServiceProfile account, but running it manually doesn't trigger the events.

I suppose that makes sense. It does have a lot of caveats and by this point it's become something of a tangent.

Anyway, my thought regarding that was that assuming it all WORKED you'd be abl to "profile" any program that started.

For example you'd handle an event when notepad.exe is launched. You'd record that the program launched, then spin off another thread to keep an eye on that process as it starts up. in C# Processes are represented with the Process object which maps pretty much directly to the Process Handle information that is part of the Win32 API. In my mind it would be done like so

Code: [Select]//This dictionary would be a member-level variable
private Dictionary<Process,Thread> ProcessAttendants = new Dictionary<Process,Thread>();

// This would be in the start event handler... spin off a new thread to watch this process. EventProcess would be the Process that was given as part of the event arguments.
Thread Attendant = new Thread(AttendantHandler);
ProcessAttendants.Add(EventProcess,Attendant);
Attendant.Start(EventProcess);

And then you would have the AttendantHandler be a routine that basically sits and 'watches' a process:

Code: [Select]private void AttendantHandler(Object ProcessItem)
{
    Process AttendProcess = ProcessItem as Process;
    while(!AttendProcess.Exited)
    {
        Thread.Sleep(50);
        //Determine if process has "started" completely here, somehow
    }

}

Also, looking closer, getting Processor % for a process isn't directly part of the Process, but is retrieved with a Performance COUNTER. It might be possible to test the TotalProcessorTime each iteration and "trigger" that it has finished after the Delta drops to some specific value.Thanks for SHARING the C# source on this and explaining it all, and clarifying the prior info. Hopefully this info shared is beneficial to other future site visitors as it has been for myself. 

Was looking at C# methods to get CPU info and found a feature in Windows that I wasnt aware of typeperf as seen here. The interesting thing is that Google pooled this in with a C# search maybe because of the CS of the site name  http://www.csarchive.net/2013/06/view-cpu-usage-using-typeperf.html

Here is what it showed for system that I tested it on:


Code: [Select]C:\test123>typeperf  "\Processor(_Total)\% Processor Time"

"(PDH-CSV 4.0)","\\ATHLON4450B\Processor(_Total)\% Processor Time"
"07/25/2015 23:40:15.797","21.376747"
"07/25/2015 23:40:16.798","22.077423"
"07/25/2015 23:40:17.799","18.181289"
"07/25/2015 23:40:18.800","11.168262"
"07/25/2015 23:40:19.801","24.415105"
"07/25/2015 23:40:20.802","15.927605"
"07/25/2015 23:40:21.804","19.819840"
"07/25/2015 23:40:22.807","11.256916"
"07/25/2015 23:40:23.808","25.973556"
"07/25/2015 23:40:24.810","24.490529"
"07/25/2015 23:40:25.811","16.622847"
"07/25/2015 23:40:26.812","11.947483"
"07/25/2015 23:40:27.813","16.622847"
"07/25/2015 23:40:28.817","17.648875"
"07/25/2015 23:40:29.824","19.443376"
"07/25/2015 23:40:30.825","23.635874"
"07/25/2015 23:40:31.829","24.640946"
"07/25/2015 23:40:32.831","19.041397"
"07/25/2015 23:40:33.832","41.616397"
"07/25/2015 23:40:34.834","66.493287"
"07/25/2015 23:40:35.847","77.670148"
"07/25/2015 23:40:36.848","74.285544"
"07/25/2015 23:40:37.852","72.808596"
"07/25/2015 23:40:38.853","75.089661"
"07/25/2015 23:40:39.855","69.610190"
"07/25/2015 23:40:40.856","54.025684"
"07/25/2015 23:40:41.857","25.194326"
"07/25/2015 23:40:42.858","18.181289"
"07/25/2015 23:40:43.859","11.947493"
"07/25/2015 23:40:44.860","17.402068"
"07/25/2015 23:40:45.861","15.064386"
"07/25/2015 23:40:46.862","22.856653"
"07/25/2015 23:40:47.863","13.505934"
"07/25/2015 23:40:48.864","17.402068"


Note:
  In order to use typeperf, you must either be a member of the local
  Performance Log Users group, or the command must be executed from an
  elevated command window.

C:\test123>
Here is additional info on typeperf usage:


Code: [Select]Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.


C:\test123>typeperf/?

Microsoft r TypePerf.exe (6.1.7601.18869)

Typeperf writes performance data to the command window or to a log file. To
stop Typeperf, press CTRL+C.

Usage:
typeperf { <counter [counter ...]> | -cf <filename> | -q [object]
                                | -qx [object] } [options]

Parameters:
  <counter [counter ...]>       Performance counters to monitor.

Options:
  -?                            Displays context sensitive help.
  -f <CSV|TSV|BIN|SQL>          Output file format. Default is CSV.
  -cf <filename>                File containing performance counters to
                                monitor, one per line.
  -si <[[hh:]mm:]ss>            Time between samples. Default is 1 second.
  -o <filename>                 Path of output file or SQL database. Default
                                is STDOUT.
  -q [object]                   List installed counters (no instances). To
                                list counters for one object, include the
                                object name, such as Processor.
  -qx [object]                  List installed counters with instances. To
                                list counters for one object, include the
                                object name, such as Processor.
  -sc <samples>                 Number of samples to collect. Default is to
                                sample until CTRL+C.
  -config <filename>            Settings file containing command options.
  -s <computer_name>            Server to monitor if no server is specified
                                in the counter path.
  -y                            Answer yes to all questions without prompting.

Note:
  Counter is the full name of a performance counter in
  "\\<Computer>\<Object>(<Instance>)\<Counter>" format,
  such as "\\Server1\Processor(0)\% User Time".

Examples:
  typeperf "\Processor(_Total)\% Processor Time"
  typeperf -cf counters.txt -si 5 -sc 50 -f TSV -o domain2.tsv
  typeperf -qx PhysicalDisk -o counters.txt

C:\test123

Tested this out on my Windows XP system in addition to this Windows 7 system that I am on to see if it goes back that far... sure enough its there so typeperf works on XP and 7 and likely Vista as well.

Quote from: patio on July 25, 2015, 01:12:34 PM
I'm officially outta my league on this one...sorry...

I'm on the sidelines too.Interesting find on the Typeperf. I was able to have it display the processor usage of a specific process. In this case, I chose my text editor. While it was sampling I grabbed the window and moved it around a bit:

Code: [Select]C:\Windows\system32>typeperf "\Process(EditPadPro7)\% Processor Time"

"(PDH-CSV 4.0)","\\PETATRON\Process(EditPadPro7)\% Processor Time"
"07/26/2015 04:14:52.908","0.000000"
"07/26/2015 04:14:53.910","0.000000"
"07/26/2015 04:14:54.912","0.000000"
"07/26/2015 04:14:55.916","6.234487"
"07/26/2015 04:14:56.920","12.450440"
"07/26/2015 04:14:57.924","28.014915"
"07/26/2015 04:14:58.927","24.926027"
"07/26/2015 04:14:59.928","3.117450"
"07/26/2015 04:15:00.931","0.000000"

The command completed successfully.

One could imagine that you could use the -sc 1 parameter to only get a single sample, which gives us:

Code: [Select]
"(PDH-CSV 4.0)","\\PETATRON\Process(EditPadPro7)\% Processor Time"
"07/26/2015 04:17:42.395","0.000000"

The command completed successfully.

Which I'm sure could be parsed via the command prompt to grab the actual % and used for logging or what-have-you.
Code: [Select]"(PDH-CSV 4.0)","\\PETATRON\Process(EditPadPro7)\% Processor Time"
"07/26/2015 04:17:42.395","0.000000"

The command completed successfully.

Quote
Which I'm sure could be parsed via the command prompt to grab the actual % and used for logging or what-have-you.

Yes this was my thought exactly, being able to take the output and parse it. I ended up running out of time last night to check into its ability for measurement of a specific process. Thanks for sharing your results on this. I tried to do this with notepad last night and got an error message and it was late, so I just posted what I had to share and crashed for the evening. Very cool that it worked.

Looking back at what I attempted, I now realize what I did wrong when awake at the 18th hour of the day. I ran
typeperf -cf notepad.exe "\Processor(_Total)\% Processor Time"   but the -cf is not to be used for the file to monitor, its use " Specifies a file containing a list of performance counters to monitor, with one counter per line. "

Another cool fact from finding this is that typeperf's output could be used with a batch process to parse the data that is redirected to a file as well and report back with info.

So such as with your data here:

Quote
"07/26/2015 04:14:52.908","0.000000"
"07/26/2015 04:14:53.910","0.000000"
"07/26/2015 04:14:54.912","0.000000"
"07/26/2015 04:14:55.916","6.234487"
"07/26/2015 04:14:56.920","12.450440"
"07/26/2015 04:14:57.924","28.014915"
"07/26/2015 04:14:58.927","24.926027"
"07/26/2015 04:14:59.928","3.117450"
"07/26/2015 04:15:00.931","0.000000"

You could parse it to get data after the comma delimiter on each line, and clean it up to remove the " " so that the output could be read in as a value to a script

Quote
0.000000
0.000000
0.000000
6.234487
12.450440
28.014915
24.926027
3.117450
0.000000

Then the script looks for greater than 0.0000 as a starting point for the application/program, and a point in which it comes back to rest at 0.0000 and the data within is essentially the load time data. Using this in conjunction back with the original data that has the time stamp of each sample, you then could get

Program started on = 07/26/2015 04:14:55.916
Program idle at        = 07/26/2015 04:15:00.931


And you can then go further and have it perform the load time math and report back with

07/26/2015 Total Load time for this application = 00:00:04.985


This is assuming that the last sample of "07/26/2015 04:15:00.931","0.000000" was with the EditPadPro7 at rest in its halt state and that this measurement wasnt taken after this application was closed.

There might be an even better method of extracting and creating the final output, but this is what I thought up on the fly after reading your post back to this.