Recent Entries 10
- pattern minor 112d agoConways Game of Life in cmd batch fileJust for fun I have written a Conway's Game of Life in cmd batch file. I like writing in batch - its restrictions and limits are its appeal. However - it is slow, very slow on a large grid. Any tips to speed it up? I think the slowest part is the function `GETNCOUNT` - this gets the count of the neighbouring 'live' cells so it is called once per cell. ``` @ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION IF "%3"=="" GOTO HELP SET WIDTH=%1 SET HEIGHT=%2 SET DENSITY=%3 SET LIFECYCLE=0 :::::::::::::::::::: :: Generate Grid 'A' :: Also for safety, delete any Grid 'B' cells that might be in memory FOR /L %%h IN (1, 1, %HEIGHT%) DO ( FOR /L %%w IN (1, 1, %WIDTH%) DO ( SET /A RAND=!RANDOM!*100/32768 SET /A RAND=!RAND!+1 IF !DENSITY! GEQ !RAND! ( SET A[%%w][%%h]=@ ) ELSE ( SET "A[%%w][%%h]= " ) SET B[%%w][%%h]= ) ) :::::::::::::::::::::::::::::: :: TOP OF MAIN PROCESSING LOOP :: :: Loop through all the Grid 'A' cells :: - Count number of neighbours :: - Check if alive or not :: - If required assign new alive/dead status in Grid 'B' :: :PROCESS SET /A LIFECYCLE=%LIFECYCLE%+1 CLS ECHO Conway's Game of Life. CALL :DISPLAY ECHO Current lifecycle: %LIFECYCLE% FOR /L %%h IN (1, 1, %HEIGHT%) DO ( FOR /L %%w IN (1, 1, %WIDTH%) DO ( CALL :GETNCOUNT %%w %%h IF "!A[%%w][%%h]!"=="@" (SET ALIVE=Y) ELSE (SET ALIVE=N) IF "!ALIVE!"=="Y" ( IF !NCOUNT! LSS 2 ( SET "B[%%w][%%h]= " ) IF !NCOUNT! EQU 2 ( SET B[%%w][%%h]=@ ) IF !NCOUNT! EQU 3 ( SET B[%%w][%%h]=@ ) IF !NCOUNT! GTR 3 ( SET "B[%%w][%%h]= " ) ) IF "!ALIVE!"=="N" ( IF !NCOUNT! EQU 3 ( SET B[%%w][%
- pattern minor 112d agoLogin System In BatchHere I made a program in batch that detects all files with the .user extension. Then it allows the user to pick a username by entering the number associated with that username. The code is messy, so I will explain. ``` @echo off setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION :login_menu cls set x=1 set users= cd "users" for %%A in (*.user) do ( echo !x!. %%~nA set users=%%~nA:!x!,!users! set /a x=!x!+1 ) echo. set /p ch=Select User: if "%ch%" == "" (goto login_menu) for %%B in (%users%) do ( for /f "tokens=1,2 delims=:" %%C in ("%%B") do ( set userNumber=%%D set userN=%%C if !ch! == %%D goto password echo BDEV: %%B pause ) ) echo. echo That user doesn't exist! pause goto login_menu :password cls cd "users" for /f "tokens=1,2 delims=:" %%E in (!userN!.user) do (set password=%%F) echo Enter your password, !userN! echo. set /p password1=Password: if %password1% == %password% goto menu echo. echo That password is invalid! pause goto password :menu echo Hey! You're logged in as !userN! pause ``` The variable `x` is going to be the number which the username will be associated with. The variable `users` Makes sort of a 'map' to usernames to the number associated with that username In the first `for` loop, it gets all the files in the folder users. It `echo`'s out all the usernames that the user can pick. The second `for` loop goes into the variable `users` and separates the usernames with their respective numbers. For example: if I have the usernames `admin:4,steve:3,john:2,jane:1` it will separate them into `admin:4` and `steve:3` and `john:2` and `jane:1`. The third `for` loop (which is in the second `for` loop) separates each username to number into separate variables. For example, if we have the username Collins with the number 3, it will put the username Collins in the `userN` variable and the number 3 into the variable `userNumber`. It then checks what number the user selected. The final `for` loop goes into the user file tha
- pattern minor 112d agoBatch file to backup and update SQL Server DBsThis is my first windows batch file. The script basically goes through this basic flow of tasks, in order to update some specific SQL Server DBs to a new DB version: - Backup all SQL server DBs that will be upgraded. - Upgrade to the latest version and apply any last-minute patches to those DBs. - Error handling is done when the process fails at any point, rolling back all DBs to their initial version (before the update). I would appreciate your feedback on: - What parts of the code could be improved in general (fix some bad practices, improve brittle code, etc). - How to better organize (comments, separation of sub-sections, etc) the code and make it clearer (for easy maintenance). - Any other aspect you think needs to be improved, specially regarding batch coding style and standarization. Here is the full code: ``` :: MAIN SCRIPT OPTIONS @echo off setlocal EnableDelayedExpansion :: ------------------------------------------------------------------------------------------------ :: PARAMETERS (ADJUST TO SPECIFIC ENVIRONMENT) :: SQL Server: instance holding the DBs set serverName=SERVER\SQLEXPRESS :: SQL Server: user name and user password for performing the upgrade set sqlUser=%1 set sqlPwd=%2 :: SQL Server: comma separated list of DBs in this server instance that should be upgraded set sqlDBs=DB1,DB2 :: DB version: current version to be upgraded set currentVersion=4.3.0 :: DB version: target version to upgrade to set targetVersion=4.4.0 :: DB version: scripts (if multiple, quote and separate with commas) to run before applying the upgrade (leave blank if none is needed) set prePatchScripts= :: DB version: scripts (if multiple, quote and separate with commas) to run after applying the upgrade (leave blank if none is needed) set postPatchScripts="Script1.sql,Script2.sql" :: ------------------------------------------------------------------------------------------------ :: CALCULATED VARIABLES (DO NOT MODIFY) :: Folders: scripts working directory
- pattern minor 112d agoDOS batch script to open file explorerI wrote a script that you can use to open the file explorer from command line like `e db` --> opens my Dropbox folder (`e.cmd` is the name of the script) `e bin` --> opens my script folder (Iām not very happy with the way I define the relationship mnemonic folder.) Remarks, anyone? ``` @ECHO OFF SET "target=%~1" if "%target%" EQU "" ( ECHO No target specified. EXIT /B ) SET folder="" CALL :set_folder_%target% 2> nul if %folder% EQU "" ( ECHO Invalid target %target%. EXIT /B ) explorer %folder% EXIT /B :set_folder_db SET folder="D:\Alex\Dropbox" & EXIT /B :set_folder_bin SET folder="D:\Alex\Scripts\Bin" & EXIT /B ... ```
- pattern minor 112d agoBatch script to make folders hiddenI just wrote a simple script cmd to hide private folders by combining several scripts from the Internet. Can anyone give me suggestions for improvement? This batch file uses a password hidden by powershell script. Then I create a shortcut and run `attrib -s -h`, so it is not easy to find. It works just gave `attrib -s -h` on the desired folder. Location folder can only be changed by editing the file. Also passwords can only be changed by editing the batch file. The last two things are quite cumbersome. ``` @echo off title Privat Locker set _folder="E:\Private" dir /a:h %_folder%>nul 2>nul if %errorlevel%==0 goto PASS1 dir /a:s %_folder%>nul 2>nul if %errorlevel%==0 goto PASS1 :CONFIRM echo Do you want to lock the Private Folder?! [Y/N] set/p "cho=>" if %cho%==Y goto LOCK if %cho%==y goto LOCK if %cho%==n goto end if %cho%==N goto end echo Error! Wrong answer, please type [Y/N] goto CONFIRM :LOCK attrib +h +s %_folder% echo The folder sucsessfully locked... pause goto end :PASS1 set "psCommand=powershell -Command "$pword = read-host 'Masukkan PIN!' -AsSecureString ; ^ $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^ [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"" for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p if NOT "%password%"=="YOURPINHERE" goto FAIL1 attrib -s -h %_folder% goto EXP :PASS2 set "psCommand=powershell -Command "$pword = read-host 'Masukkan PIN!' -AsSecureString ; ^ $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^ [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)"" for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p if NOT "%password%"=="YOURPINHERE" goto FAIL2 attrib -s -h %_folder% goto EXP :PASS3 set "psCommand=powershell -Command "$pword = read-host 'Masukkan PIN!' -AsSecureString ; ^ $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
- pattern minor 112d agoBatch/PowerShell script that toggles the minimized state of a windowI wrote this script for a user who wants to toggle the minimized state of a window that minimizes to the tray. The user required a .bat script, so I wrote a bat + PowerShell hybrid script in order to import functions from user32.dll. `" >NUL || goto usage set /P "=Toggling the minimized state of %prog%... " Add-Type user32_dll @' [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, IntPtr lclassName, string windowTitle); '@ -namespace System $hwnd = (ps $env:prog)[0].MainWindowHandle if ($hwnd -eq 0) { tasklist /v /fi "imagename eq $env:prog*" /fo list | %{ $title = $_ -replace '^[^:]+:\s+' } $zero = [IntPtr]::Zero $hwnd = [user32_dll]::FindWindowEx($zero, $zero, $zero, $title) } $state = [user32_dll]::GetWindowLong($hwnd, -16) # mask of 0x20000000 = minimized; 2 = minimize; 4 = restore if ($state -band 0x20000000) { $action = 4 } else { $action = 2 } if ([user32_dll]::ShowWindowAsync($hwnd, $action)) { write-host "Success" -f green } else { write-host "Fail" -f red } ` Questions: - Neither the `get-process` cmdlet nor `gwmi win32_process` nor `[diagnostics.process]::getProcessByName()` would show me either the window title or the HWND of a window that's minimized to the tray (uTorrent, for example). Is there an API method I missed, or is `tasklist.exe` the correct hack here? - Is there any situation where `FindWindowEx()` would not be able to find a window that could be found with `FindWindow()`? Should I import and use `FindWindow()` as well? Suggested improvements and other comments (not including "Why not just write the whole thing in PowerShell?") are welcome, of course!
- pattern minor 112d agoMake pinging faster while looking for a Windows PCThis code pings 1 time every IP while using TTL to identify if it's a Windows PC. If so, it outputs it. It's very slow, so is there any way to make it go faster (1-255 in 12 min)? ``` @echo off echo running, it will take a long time to scan ( FOR /L %%N in (1 1 254) DO ( FOR /f "tokens=1,3 delims=: " %%A IN ('ping -n 1 192.168.250.%%N ^| find "TTL=128"') DO ECHO %%B ) ) >ip.txt echo done get_info.bat ```
- pattern minor 112d agoCopying files into Dropbox folder from command lineI made the following code. Since it is a Batch, any kind of problems can appear. Please review it and point any problems when copying files into Dropbox! Its intent is that you will copy a file into an Dropbox folder. Its syntax is `dropbox `. ``` @echo off set dropbox=%userprofile%\dropbox if exist %dropbox% (if not exist %dropbox%\%2 mkdir %dropbox%\%2) else (echo Get Dropbox for PC before using this!) if exist %dropbox%\%2 copy %1 %dropbox%\%2 @echo on ``` It would have been cool to use the `dropbox` tag as well, right?
- pattern minor 112d agoWiFi adapter settingsYesterday I have found that I can't use the wireless network at some spots in my house. I used another modem as a WiFi booster and I managed to cover these spots. The problem is that when I go to these dead spots I need to use static IP and change my primary DNS servers, or I get limited connection. Also, I still want to use DHCP when I'm not in these spots. I have written two Batch files and a Python script to define the wireless adapter settings. I would like someone to take a look and suggest how to improve it. Batch Files (I'm using shortcuts because of the option to run them as administrator) - DeadSpots.bat.ink ``` netsh interface ip set address "Wi-Fi" static 192.168.x.x 255.255.255.0 192.168.x.x netsh interface ip set dns "Wi-Fi" static 192.168.x.x primary # This is the second modem netsh interface ip add dns "Wi-Fi" ISP.dns.IP index=2 ``` - Regular.bat.ink ``` netsh interface ip set address "Wi-Fi" dhcp netsh interface ip set dnsservers "Wi-Fi" source=dhcp ``` Python code ``` import subprocess as sub def WiFi(): filepath1 = Path_To_DeadSpots.bat.ink filepath2 = Path_To_Regular.bat.ink loc = input("Please choose your location: 1-Rooms, 2-Rest \n") while(loc != "1" and loc != "2"): print("Wrong input, please choose again") loc = input("Please choose your location: 1-Rooms, 2-Rest \n") if loc == "1": p = sub.Popen(filepath1,shell=True,stdout=sub.PIPE) else: p = sub.Popen(filepath2,shell=True,stdout=sub.PIPE) WiFi() ```
- pattern minor 112d agoBatch file command looperJust a fun batch file I have made. I wanted an easy way to loop any arbitrary command several times: loopme.bat ``` @echo off SETLOCAL echo LoopMe v1.0 IF "%~1"=="/?" (GOTO HELP) IF "%~1"=="" (GOTO HELP) IF "%2"=="" (SET TIMEOUT=1) ELSE (SET TIMEOUT=%2) SET COMMAND=%~1 SET COUNTER=0 :RUN SET /A COUNTER=%COUNTER% + 1 CMD /C "%COMMAND%" echo. echo Command : "%COMMAND%" echo Times run: %COUNTER% CHOICE /C QC /N /T %TIMEOUT% /D C /M "Press Q to quit, otherwise wait %TIMEOUT% second(s) to run again." IF "%ERRORLEVEL%"=="1" (GOTO EOF) ELSE (GOTO RUN) :HELP echo Perform the same command in a loop. echo Commands containing ^& or ^| must be escaped with ^^ echo Commands containing variables must be escaped with ^^ in the varible name echo Optionally specify loop time. Default is 1 second. echo. echo Usage: loopme dir 2 echo [run dir in current, loop 2 seconds] echo. echo loopme "cls ^& netstat -an ^| find ".109"" echo [clear screen then run netstat with find filter, loop 1 second] echo. echo loopme "echo %%^time%%" echo [display the time, loop 1 second] echo echo. :EOF ``` Any improvements or suggestions? p.s this is my new way to annoy colleagues who leave their workstation unlocked: ``` loopme "color %^time:~9,2% ^&echo. ^& echo. ^&echo. ^& echo YOU HAVE BEEN HACKED!! ^& echo. ^&echo." ```