The Issue: Group policies don;t allow me to change the lock screen to slideshow or spotlight but i am local admin on the pc and by replacing C:\Windows\Web\Screen\Screen.jpg i can change the lock screen picture.
Solution: create a batch/CMD/PS script that runs every xx minutes and copies a random picture from a source folder to replace C:\Windows\Web\Screen\Screen.jpg
i found a possible script in this article that could work but how do i modify it for my purpose and if i schedule it in task scheduler to run every 30 minutes would a Batch file run in the background without interference or would a CMD script or Powershell script be a better solutions?
see code below:
#echo off & setlocal
set "workDir=C:\source\folder"
::Read the %random%, two times is'nt a mistake! Why? Ask Bill.
::In fact at the first time %random% is nearly the same.
#set /a "rdm=%random%"
set /a "rdm=%random%"
::Push to your path.
pushd "%workDir%"
::Count all files in your path. (dir with /b shows only the filenames)
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do call :sub1
::This function gives a value from 1 to upper bound of files
set /a "rdNum=(%rdm%*%counter%/32767)+1"
::Start a random file
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do set "fileName=%%i" &call :sub2
::Pop back from your path.
popd "%workDir%"
goto :eof
:: end of main
:: start of sub1
:sub1
::For each found file set counter + 1.
set /a "counter+=1"
goto :eof
:: end of sub1
:: start of sub2
:sub2
::1st: count again,
::2nd: if counted number equals random number then start the file.
set /a "counter+=1"
if %counter%==%rdNum% (
:: OUTPUT ALERT BOX with FILENAME
MSG * "%fileName%"
)
goto :eof
:: end of sub2
IMO PowerShell is by far superior to batch in this case
dir C:\source\folder\*.jpg |Get-Random|Copy -Dest C:\Windows\Web\Screen\Screen.jpg -Force
You might wrap it in a batch/cmd line
powershell -Nop -C "dir C:\source\folder\*.jpg |Get-Random|Copy -Dest C:\Windows\Web\Screen\Screen.jpg -Force"
Related
I have quite a few exe files, I want to run them with a single batch file. As far as I understand, these two codes work for me;
for %%a in ("\*.exe") do start "" "%%\~fa"
for %%i in (\*.exe) do start "" /b "%%i"
But that cmd screen closes when all files are run. What I want is this: That cmd screen will not close when the process is finished and will show me the result (counting if possible), a code that can count how many of these .exe files work and how many fail.
So for example;
87 files blocked
13 files could not be blocked
Something like this? Is this possible?
Maybe you can get an inspiration from this batch below. It works through program exit code. It spawns all executable, wait for their completion, then count how much failed / succeeded.
It should also work with well-designed GUI program, not only command-line based ones.
It's a rough/basic answer, you may need to refine it according to your exact needs.
#echo off
setlocal enableextensions enabledelayedexpansion
REM Use marker files for getting results.
set OK_EXT=.SUCCESS
set FAIL_EXT=.FAILURE
REM Purge all possible marker files.
del /q *!OK_EXT! *!FAIL_EXT! > NUL 2>&1
set /a count=0
REM Parse all executables
for %%E in (*.exe) do (
echo Launching: %%~nxE
REM Create two marker files for each executable.
echo.>%%~nE!OK_EXT!
echo.>%%~nE!FAIL_EXT!
REM Start the executable, delete the WRONG marker.
REM I would have prefered to use "touch" to create the good one instead, but not standard on Windows.
start %comspec% /C "%%~nxE && ( del /q %%~nE!FAIL_EXT! ) || ( del /q %%~nE!OK_EXT! )"
set /a count +=1
)
REM Now, "count" contains the number of executables launched.
echo All processes launched.
echo.
:loop
echo Waiting for results...
set /a curr=0
REM Simply count the number of marker files. Must be equal to "count" when everything is finished.
for /F "usebackq tokens=*" %%C in (`dir /b *!OK_EXT! *!FAIL_EXT!`) do (
set /A curr+=1
)
if !curr! GTR !count! (
set /a curr-=!count!
echo Still !curr! processes running...
timeout /t 2
goto :loop
)
echo All results found.
echo.
echo Parsing results...
set /a ok_exe=0
set ok_exe_list=
set /a fail_exe=0
set fail_exe_list=
REM Parse all marker files.
for /F "usebackq tokens=*" %%C in (`dir /b *!OK_EXT! *!FAIL_EXT!`) do (
REM And set counters + list according to the marker file type (OK or FAILED).
if /I "%%~xC"=="!OK_EXT!" (
set /A ok_exe+=1
set ok_exe_list=!ok_exe_list! %%~nC
) else (
set /A fail_exe+=1
set fail_exe_list=!fail_exe_list! %%~nC
)
)
REM Simple display.
echo Programs without error: !ok_exe!/!count!
echo !ok_exe_list!
echo.
echo Programs with error: !fail_exe!/!count!
echo !fail_exe_list!
echo.
goto :eof
I'm an artist who is learning programming and I wanted to create a batch file that will select a random picture file from my references folder. The goal being to get a random picture to work on and study. I've looked around and the replies I see are hard to understand and are often linked with other features and functions I don't need. Simply put, how do I make a batch file that opens a random picture file from a folder (and subfolders)? Do I need to index every picture and then have a selector from that or can I just use %random% to open it?
Thank you for your help.
This is the basic batch file structure you'll need:
#Echo Off
Set "SrcDir=C:\Users\Jiosen\references"
Set "ExtLst=*.jpeg *.png *.tiff"
Set "i=0"
For /F "Delims=" %%A In ('Where /R "%SrcDir%" %ExtLst%') Do (Set /A i+=1
Call Set "$[%%i%%]=%%A")
Set /A #=(%Random%%%i)+1
Call Start "" "%%$[%#%]%%"
You may need to adjust lines 2 and 3 as necessary, (but do not remove or add any doublequotes).
PowerShell is more efficient in selecting files in a tree and getting a random file so why not use it from the batch.
Taking Compos batch as a template:
:: Q:\Test\2018\07\24\SO_51487674.cmd
#Echo Off
PushD "C:\Users\Jiosen\references"
Set "ExtLst=*.jpg,*.jpeg,*.png,*.tiff"
For /F "Delims=" %%A In ('
powershell -Nop -C "(Get-ChildItem * -R -File -Incl %ExtLst%|Get-Random).FullName"
') Do Start "" "%%A"
Get-ChildItem parameters -File,?-Include and Get-Random require at least PowerShell Version 3.0
According to the table in this link you need to upgrade Window 7 PowerShell v2 to at least V3, Windows 8 or higher should run the script without problem.
But I'd recommend to upgrade to 5.1 and possibly install PowerShell 6.0 (core) in parallel.
#SETLOCAL ENABLEDELAYEDEXPANSION
rem #CD C:\newfolder
#set count=0
#For /f "delims=" %%A in ('dir C:\users\*.* /ad /s /b') Do (
# set /a count=!count!+1
#rem If !Count! gtr 1 echo Num of folders
)
#Set /a num=%random% %% %Count% + 1
Echo %num% / %count%
For /f "skip=%num% delims=" %%A in ('dir C:\users\*.* /ad /s /b') Do (
Echo this is nth random folder
Echo Copy "%~dpnx0" "%%A"
rem Exit /b
)
pause
%Random% gives us a random number from 0 to 32K. #Set /a num=%random% %% %Count% + 1 uses modulo division (ie the remainder from a division) of 32K divided by how many will give us a random number in the range 0 to count. Then add 1 to make it 1 to count +1 (the number of folders). Then skip=%num% skips the first how ever many folders, reads the next, then exits the loop.
This is limited to 32K folders. See Dir /? for how to list files and files in subfolders. Every command above plus /? for help. See http://stackoverflow.com/questions/41030190/command-to-run-a-bat-file/41049135#41049135 for a CMD cheat sheet.
(TLDR see last paragraph)
Below code I have cobbled together with information from other threads in this forum and others. I am very new to this code/language so I don't have a clue how to optimize this.
Here is what I am trying to achieve with this code.
script outputs to a .log instead of command window
:top
script searches for a .dat file in "M:\AnalysisDrop\"
if a .dat file is detected (
script automatically creates a subfolder "M:\AnalysisDrop\title_date_time"
file is moved into the folder
file is opened with the program C:\Analysis\Analysis.exe
)
wait 5 seconds
goto top (repeat forever)
this script will continuously repeat for what I hope to be a very long time. Will I run into issues with too many "set" commands? I ran into some issue with doing "SETLOCAL EnableDelayedExpansion" and SETLOCAL DisableDelayedExpansion
#Echo off
echo Script 1 Initiated
#echo on
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set datetime1=%datetime:~0,8%_%datetime:~8,6%
SETLOCAL EnableDelayedExpansion
SET LOGFILE=Script1_LOG_%datetime1%.log
call :top >> %LOGFILE%
exit /b 0
:top
for %%f in (*.dat) do (
set datetime1=%datetime:~0,8%_%datetime:~8,6%
set foldername=%%~nf_%datetime1%
md "!foldername!"
move "M:\AnalysisDrop\%%~nf*.dat*" "M:\AnalysisDrop\%%~nf_%datetime1%\"
pushd M:\AnalysisDrop\%%~nf_%datetime1%\
C:\Analysis\Analysis.exe '%%~nf.dat'
popd
)
timeout /t 5 /nobreak
goto top
exit /b 0
I honestly dont need the "for" loop but i'm not sure how to do otherwise (tried to replace "for" with "if", no success. Also, the "datetime1" variable wont update, so if I try to run multiple .dat files of the same name, it writes over the previous one in the same subfolder, which I can live with but prefer not to have.
So to clarify my questions:
1. How do i do this without the "for" loop? I understand this may be causing my issue of the datetime variable not updating.
2. I used the "goto" command to continuously loop this script, should I use something different?
Answer to my question, with help from #compo. I wasn't aware that I needed the for \f... statement in the loop as well as the set datetime2. I needed to change %datetime...% to !datetime...! throughout the for loop. See below for fixed code.
In response to #Gerhard Barnard, %time% and %date% is not in a format that I can name directories with unfortunately.
#Echo off
echo Script 2 Initiated
#echo on
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set datetime2=%datetime:~0,8%_%datetime:~8,6%
SETLOCAL EnableDelayedExpansion
SET LOGFILE=Script2_LOG_%datetime2%.log
call :top >> %LOGFILE%
:top
for %%f in (*.dat) do (
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set datetime2=!datetime:~0,8!_!datetime:~8,6!
set foldername=%%~nf_!datetime2!
md "!foldername!"
move "M:\AnalysisDrop\%%~nf*.dat*" "M:\AnalysisDrop\!foldername!\"
pushd M:\AnalysisDrop\!foldername!\
C:\Analysis\Analysis.exe '%%~nf.dat'
popd
)
timeout /t 5 /nobreak
goto top
exit /b 0
I hope this, based upon your original code, helps you with structuring your script:
#Echo Off
Rem Enabling delayed expansion
SetLocal EnableDelayedExpansion
Rem Setting current directory
If /I Not "%CD%"=="M:\AnalysisDrop" (CD /D "M:\AnalysisDrop" 2>Nul||Exit/B)
Rem Setting date and time variable for log file name
Call :GetLDT
Rem Call Main section outputting to log file
Call :Main>>"Script1_LOG_%LDT%.log"
Rem Exit script
Exit/B
Rem Main section
:Main
Rem Loop over each matching file in the current directory
For %%A In (*.dat) Do (
Rem Setting date and time variable for destination directory name
Call :GetLDT
Rem Create directory if it does not exist
If Not Exist "%%~nA_!LDT!\" MD "%%~nA_!LDT!"
Rem Move file to directory
Move "%%~A" "%%~nA_!LDT!"
Rem Run analysis against file in destination
Start "" /D "%%~nA_!LDT!" /W "C:\Analysis\Analysis.exe" '%%~A'
)
Rem Create a delay
Timeout 5 /NoBreak>Nul
Rem Re-run Main section in loop
GoTo Main
Rem GetLDT section
:GetLDT
Rem Setting date and time string
For /F "EOL=L" %%A In ('WMIC OS GET LocalDateTime') Do For %%B In (%%~nA
) Do Set "LDT=%%B"
Rem Formatting string as required
Set "LDT=%LDT:~,8%_%LDT:~-6%"
Rem Return to point after Call
GoTo :EOF
Your command using '%%~A' looks wrong with single quotes, but I'll leave that to you to decide.
I have searched and searched to find a solution to (what feels like) a unique problem. Many
answers here have been quite helpful and have gotten me a long way, but the last bit has me stumped.
My batch file needs to open an executable in a folder with a variable name
This folder may be in one of two directories
This is what I originally had and it works
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET DIR1="%USERPROFILE%\AppData\Local\Application Workspace\Profiles"
SET DIR2=C:\Application\SRW\Profiles
IF NOT EXIST %DIR1% (
GOTO PROFILE_2
) ELSE (
GOTO PROFILE_1
)
:PROFILE_1
for /f "delims=" %%A in ('dir %DIR1% /ad /b') do (
set foldername=%%~nxA
)
SET DIR1=%DIR1:"=%
SET DIR=%DIR1%\%foldername%\app.exe
GOTO START_APP
:PROFILE_2
for /f "delims=" %%A in ('dir %DIR2% /ad /b') do (
set foldername=%%~nxA
)
SET DIR=%DIR2%\%foldername%\app.exe
GOTO START_APP
:START_APP
START "" /b "%DIR%"
:EOF
ENDLOCAL
EXIT
Then I was thrown a curveball when I discovered that some users may have multiple profiles in the variable profile folder and they need to be able to select which one to use for that given task. Now I have a variable profile folder and either one or multiple variable profiles within that folder.
I have found code to list the folder names and display them in the command window for selection.
#echo off
cls
setlocal EnableDelayedExpansion
set /a count=0
for /d %%d in (*) do (
set /a count+=1
#echo !count!. %%d
)
setlocal DisableDelayedExpansion
set /P selection="select folder number:"
I also found this routine which allows the user to select a file from a list then it is supposed to translate that file name into a variable.
Batch Script Programming -- How to allow a user to select a file by number from a list of files in a folder?
Unfortunately, I cannot get the example in the link to work as is and I have no idea how to make it work with folder names as the folder name example and the file name example are close but not close enough for me to understand what to do. And even if it somehow does manage to work, how then can I make such a routine work within the original code posted above?
In addition, I really don't want the user to be forced to make a folder selection if there is only one folder. If only one folder exists, it should be placed into the folder name variable automatically and nothing displays to the user at all.
Is what I'm trying to do even possible at all?
Any help is most appreciated.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
::
:: Set count-of-targets and application name
::
SET /a targets=0
SET appname=app.exe
SET "dots=..."
::
:: clear all "$" variables
::
FOR /f "delims==" %%i IN ('set $ 2^>nul') DO SET "%%i="
::
:: look for app.exe in (1) userprofile... (2) \application\srw...
::
SET dir1="%USERPROFILE%\AppData\Local\Application Workspace\Profiles"
SET dir2="C:\Application\SRW\Profiles"
:: My testing - my directory names
SET dir1="c:\sourcedir"
SET dir2="C:\destdir\test dir"
FOR %%s IN (%dir1% %dir2%) DO (
FOR /f "delims=" %%i IN ('dir /s /b "%%~s\%appname%"') DO ( CALL :process "%%~dpi"
)
)
::
:: Now have TARGETS=#hits; $_n=full pathname; $n=directoryname
::
IF %targets%==1 SET mychoice=1&GOTO chosen
::
:: repeat a menu
::
:again
CLS
FOR /l %%i IN (1,1,%targets%) DO (
IF %%i lss 10 (ECHO(%%i%dots%%dots:~0,1%!$%%i!) ELSE (ECHO(%%i%dots%!$%%i!)
)
SET mychoice=
SET /p mychoice="Please choose 1..%targets% : "
IF NOT DEFINED $_%mychoice% GOTO again
:chosen
CALL SET application="%%$_%mychoice%%%%appname%"
ECHO START "" /b %application%
GOTO :EOF
::
:: Parameter is quoted-full-pathname
::
:process
SET /a targets+=1
SET $_%targets%=%~1
SET $=%~1
FOR %%n IN ("%$:~0,-1%") DO SET $%targets%=%%~nxn
GOTO :eof
From what you've said, this should work.
First steps are to set up. Set the number of targets found and the real application name and clear out any variablenames that start "$".
Next step is to specify the directories to use. I simply copied yours, then overrode those settings with settings to suit my machine - you'd need to delete those overriding lines, of course. Note that the names should be set quoted...
Next, scan from each of the directories for the application. Each time an instance is found, call :process passing the full -terminated pathname.
:process increments the count of targets found and sets the variable $_n to the full pathname passed (dequoted) It then sets $ to the dequoted-full-pathname and uses a syntax-trick to have FOR find the application's immediate directory. %$:~0,-1% is the full pathname minus the last character - the \ so the results looks like a filename. That "filename" is then assigned to $n
Once the directory-scans are finished, %targets% will contain the er, number of targets. If that's 1, then we have all we need - we can only select target number 1, so that's chosen for us.
Otherwise, clear the screen and display a number of lines - %targets% to be precise. The format isn...immediatedirname` and an extra dot is added if the number of targets is less than 10 so that a long list will line up nicely.
Then ask for a line number.
At this point, the only $_ variables that exist are $_1..$_%targets% so if $_%mychoice% exists, it must be a valid choice. If it's not defined, then repeat the question...
CALLing SET application="%%$_%mychoice%%%%appname%" first parses the command, then parses it again. After the first parse, the line becomes (if mychoice=3) SET application="%$_3%app.exe" so on the second occasion,application` is properly set to the full fulename of the application - and quoted.
There wasn't much point in my starting the app, since it doesn't exist, so I just echoed it.
Given the extended requirement:
You's probably be starting this from a shortcut. Suppose you run that shortcut minimised and insert after the SETLOCAL
SET "poweruser=%1"
Add, after
IF %targets%==1 SET mychoice=1&GOTO chosen
the line
IF NOT DEFINED poweruser START "%username% - poweruser" "%~dpnx0" poweruser&GOTO :EOF
And change the
GOTO :EOF
just prior to the label :process to
EXIT
So that if it wasn't run in poweruser mode (therefore poweruser is NOT defined) AND %targets% is NOT 1 (I'm presuming it won't be 0) Then this user hasn't been set as a poweruser in the shortcut, but does have more than one target, so the job is restarted in poweruser mode (ie. maximised.)
Note that it doesn't actually matter what the string is after the "~dpnx0" - so long as it's a string. I just used poweruser What it does is tell the batch that it's being run in a normal window, not minimised.
For powerusrs, you could if you like set the shortcut to normal window or maximised AND put a parameter in the command line after the batchname, which will marginally quicken the procedure. Leaving it without parameters and minimised would suit ALL users as it will auto-adjust if more than 1 target is found.
I have tried this. It worked for me.
I answered your question in two steps. In the first one I translated your original code into a more readable one. Here it is:
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET "DIR1=%USERPROFILE%\AppData\Local\Application Workspace\Profiles"
SET DIR2=C:\Application\SRW\Profiles
IF NOT EXIST "%DIR1%" (
for /f "delims=" %%A in ('dir %DIR2% /ad /b') do (
SET DIR=%DIR2%\%%~nxA\app.exe
)
) ELSE (
for /f "delims=" %%A in ('dir %DIR1% /ad /b') do (
SET DIR=%DIR1%\%%~nxA\app.exe
)
)
START "" /b "%DIR%"
ENDLOCAL
EXIT
You should check first that previous code is equivalent to your original one.
In the second step I added the profile selection to the previous code:
#ECHO OFF
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET "DIR1=%USERPROFILE%\AppData\Local\Application Workspace\Profiles"
SET DIR2=C:\Application\SRW\Profiles
IF NOT EXIST "%DIR1%" (
for /f "delims=" %%A in ('dir %DIR2% /ad /b') do (
SET DIR=%DIR2%\%%~nxA\app.exe
)
) ELSE (
call :SelectProfile
)
START "" /b "%DIR%"
ENDLOCAL
EXIT
:SelectProfile
rem Get a list of folders in User Profile dir
set count=0
for /f "delims=" %%A in ('dir %DIR1% /ad /b') do (
set /A count+=1
SET DIR[!count!]=%DIR1%\%%~nxA
)
rem Initialize the selected profile
set select=1
if %count% equ 1 goto endSelection
rem Show the profiles menu
cls
echo Available profiles:
echo/
for /L %%i in (1,1,%count%) do echo %%i- !DIR[%%i]!
echo/
rem Let's the user to select the profile
:select
set select=1
set /P "select=Enter number of desired profile [first one]: "
if not defined DIR[!select!] goto select
:endSelection
SET DIR=!DIR[%select%]!\app.exe
exit /B
Please note that previous code fail if the user enter spaces in the answer. This detail may be fixed, if needed.
I need a batch script to randomly select X number of files in a folder and move them to another folder. How do I write a windows batch script that can do this?
(I'm assuming that your X is known beforehand – represented by the variable $x in the following code).
Since you weren't adverse to a PowerShell solution:
Get-ChildItem SomeFolder | Get-Random -Count $x | Move-Item -Destination SomeOtherFolder
or shorter:
gci somefolder | random -c $x | mi -dest someotherfolder
The following Batch code will do it. Note that you will need to launch cmd using the following command line:
cmd /v:on
to enable delayed environment variable expansion. Note also that it will pick a random number of files from 0 to 32767 - you will probably want to modify this part to fit your requirements!
#ECHO OFF
SET SrcCount=0
SET SrcMax=%RANDOM%
FOR %F IN (C:\temp\source\*.*) DO IF !SrcCount! LSS %SrcMax% (
SET /A SrcCount += 1
ECHO !SrcCount! COPY %F C:\temp\output
COPY %F C:\temp\output
)
here is a CMD code, which outputs the random file name (customize it to your needs):
#echo off & setlocal
set "workDir=C:\source\folder"
::Read the %random%, two times is'nt a mistake! Why? Ask Bill.
::In fact at the first time %random% is nearly the same.
#set /a "rdm=%random%"
set /a "rdm=%random%"
::Push to your path.
pushd "%workDir%"
::Count all files in your path. (dir with /b shows only the filenames)
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do call :sub1
::This function gives a value from 1 to upper bound of files
set /a "rdNum=(%rdm%*%counter%/32767)+1"
::Start a random file
set /a "counter=0"
for /f "delims=" %%i in ('dir /b ^|find "."') do set "fileName=%%i" &call :sub2
::Pop back from your path.
popd "%workDir%"
goto :eof
:: end of main
:: start of sub1
:sub1
::For each found file set counter + 1.
set /a "counter+=1"
goto :eof
:: end of sub1
:: start of sub2
:sub2
::1st: count again,
::2nd: if counted number equals random number then start the file.
set /a "counter+=1"
if %counter%==%rdNum% (
:: OUTPUT ALERT BOX with FILENAME
MSG * "%fileName%"
)
goto :eof
:: end of sub2
#echo off
setlocal EnableDelayedExpansion
cd \particular\folder
set n=0
for %%f in (*.*) do (
set /A n+=1
set "file[!n!]=%%f"
)
set /A "rand=(n*%random%)/32768+1"
copy "!file[%rand%]!" \different\folder
from Need to create a batch file to select one random file from a folder and copy to another folder
A sample Powershell code that Moves 1000 Random files From C:\Test\A To C:\Test\B
$d = gci "C:\Test\A" | resolve-path | get-random -count 1000
Press Enter key and then execute below code
Move-Item $d -destination "C:\Test\B"
Don't forget to add " mark before and after the path of the folders