How can I use Explorer in Powershell to select a file to be processed within my Powershell script [duplicate] - powershell

Typically, asking the user to supply a file name to a batch script is a messy affair, requiring no misspellings, quotes around paths with spaces, and so forth. Unfortunately, users aren't well-known for accuracy. In situations where input file location is not known until runtime, using a GUI for file selection input reduces the likelihood of user error.
Is there a way to invoke a File... Open style gui file chooser or folder chooser from a Windows batch script?
If the script user has PowerShell or .NET installed, it is possible. See the answer below.
I'm also interested to see what other solutions anyone else can offer.

File Browser
Update 2016.3.20:
Since PowerShell is a native component of pretty much all modern Windows installations nowadays, I'm declaring the C# fallback as no longer necessary. If you still need it for Vista or XP compatibility, I moved it to a new answer. Starting with this edit, I'm rewriting the script as a Batch + PowerShell hybrid and incorporating the ability to perform multi-select. It's profoundly easier to read and to tweak as needed.
<# : chooser.bat
:: launches a File... Open sort of file chooser and outputs choice(s) to the console
:: https://stackoverflow.com/a/15885133/1683264
#echo off
setlocal
for /f "delims=" %%I in ('powershell -noprofile "iex (${%~f0} | out-string)"') do (
echo You chose %%~I
)
goto :EOF
: end Batch portion / begin PowerShell hybrid chimera #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $true
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
This results in a file chooser dialog.
The result of a selection outputs You chose C:\Users\me\Desktop\tmp.txt to the console. If you want to force single file selection, just change the $f.Multiselect property to $false.
(PowerShell command mercilessly leeched from the Just Tinkering Blog.) See the OpenFileDialog Class documentation for other properties you can set, such as Title and InitialDirectory.
Folder Browser
Update 2015.08.10:
Since there is already a COM method for invoking a folder chooser, it's pretty easy to build a PowerShell one-liner that can open the folder chooser and output the path.
:: fchooser.bat
:: launches a folder chooser and outputs choice to the console
:: https://stackoverflow.com/a/15885133/1683264
#echo off
setlocal
set "psCommand="(new-object -COM 'Shell.Application')^
.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"
setlocal enabledelayedexpansion
echo You chose !folder!
endlocal
In the BrowseForFolder() method, the fourth argument specifies the root of the hierarchy. See ShellSpecialFolderConstants for a list of valid values.
This results in a folder chooser dialog.
The result of a selection outputs You chose C:\Users\me\Desktop to the console.
See the FolderBrowserDialog class documentation for other properties you can set, such as RootFolder. My original .NET System.Windows.Forms PowerShell and C# solutions can be found in revision 4 of this answer if needed, but this COM method is much easier to read and maintain.

This should work from XP upwards and does'nt require an hibrid file, it just runs mshta with a long command line:
#echo off
set dialog="about:<input type=file id=FILE><script>FILE.click();new ActiveXObject
set dialog=%dialog%('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(FILE.value);
set dialog=%dialog%close();resizeTo(0,0);</script>"
for /f "tokens=* delims=" %%p in ('mshta.exe %dialog%') do set "file=%%p"
echo selected file is : "%file%"
pause

Windows Script Host
File Selection
Windows XP had a mysterious UserAccounts.CommonDialog WSH object which allowed VBScript and JScript to launch the file selection prompt. Apparently, that was deemed a security risk and removed in Vista.
Folder Selection
However, the WSH Shell.Application object BrowseForFolder method will still allow the creation of a folder selection dialog. Here's a hybrid batch + JScript example. Save it with a .bat extension.
#if (#a==#b) #end /*
:: fchooser2.bat
:: batch portion
#echo off
setlocal
for /f "delims=" %%I in ('cscript /nologo /e:jscript "%~f0"') do (
echo You chose %%I
)
goto :EOF
:: JScript portion */
var shl = new ActiveXObject("Shell.Application");
var folder = shl.BrowseForFolder(0, "Please choose a folder.", 0, 0x00);
WSH.Echo(folder ? folder.self.path : '');
In the BrowseForFolder() method, the fourth argument specifies the root of the hierarchy. See ShellSpecialFolderConstants for a list of valid values.

A file / folder selection may be done with pure Batch, as shown below. Of course, the feel and look is not as pleasant as a GUI, but it works very well and in my opinion it is easier to use than the GUI version. The selection method is based on CHOICE command, so it would require to download it in the Windows versions that don't include it and slightly modify its parameters. Of course, the code may be easily modified in order to use SET /P instead of CHOICE, but this change would eliminate the very simple and fast selection method that only requires one keypress to navigate and select.
#echo off
setlocal
rem Select a file or folder browsing a directory tree
rem Antonio Perez Ayala
rem Usage examples of SelectFileOrFolder subroutine:
call :SelectFileOrFolder file=
echo/
echo Selected file from *.* = "%file%"
pause
call :SelectFileOrFolder file=*.bat
echo/
echo Selected Batch file = "%file%"
pause
call :SelectFileOrFolder folder=/F
echo/
echo Selected folder = "%folder%"
pause
goto :EOF
:SelectFileOrFolder resultVar [ "list of wildcards" | /F ]
setlocal EnableDelayedExpansion
rem Process parameters
set "files=*.*"
if "%~2" neq "" (
if /I "%~2" equ "/F" (set "files=") else set "files=%~2"
)
rem Set the number of lines per page, max 34
set "pageSize=30"
set "char=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
rem Load current directory contents
set "name[1]=<DIR> .."
:ProcessThisDir
set "numNames=1"
for /D %%a in (*) do (
set /A numNames+=1
set "name[!numNames!]=<DIR> %%a"
)
for %%a in (%files%) do (
set /A numNames+=1
set "name[!numNames!]= %%a"
)
set /A numPages=(numNames-1)/pageSize+1
rem Show directory contents, one page at a time
set start=1
:ShowPage
set /A page=(start-1)/pageSize+1, end=start+pageSize-1
if %end% gtr %numNames% set end=%numNames%
cls
echo Page %page%/%numPages% of %CD%
echo/
if %start% equ 1 (set base=0) else set "base=1"
set /A lastOpt=pageSize+base, j=base
for /L %%i in (%start%,1,%end%) do (
for %%j in (!j!) do echo !char:~%%j,1! - !name[%%i]!
set /A j+=1
)
echo/
rem Assemble the get option message
if %start% equ 1 (set "mssg=: ") else (set "mssg= (0=Previous page")
if %end% lss %numNames% (
if "%mssg%" equ ": " (set "mssg= (") else set "mssg=%mssg%, "
set "mssg=!mssg!Z=Next page"
)
if "%mssg%" neq ": " set "mssg=%mssg%): "
:GetOption
choice /C "%char%" /N /M "Select desired item%mssg%"
if %errorlevel% equ 1 (
rem "0": Previous page or Parent directory
if %start% gtr 1 (
set /A start-=pageSize
goto ShowPage
) else (
cd ..
goto ProcessThisDir
)
)
if %errorlevel% equ 36 (
rem "Z": Next page, if any
if %end% lss %numNames% (
set /A start+=pageSize
goto ShowPage
) else (
goto GetOption
)
)
if %errorlevel% gtr %lastOpt% goto GetOption
set /A option=start+%errorlevel%-1-base
if %option% gtr %numNames% goto GetOption
if defined files (
if "!name[%option%]:~0,5!" neq "<DIR>" goto endSelect
) else (
choice /C OS /M "Open or Select '!name[%option%]:~7!' folder"
if errorlevel 2 goto endSelect
)
cd "!name[%option%]:~7!"
goto ProcessThisDir
:endSelect
rem Return selected file/folder
for %%a in ("!name[%option%]:~7!") do set "result=%%~Fa"
endlocal & set "%~1=%result%
exit /B

Other solution with direct run PowerShell command in Batch
rem preparation command
set pwshcmd=powershell -noprofile -command "&{[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null;$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog; $OpenFileDialog.ShowDialog()|out-null; $OpenFileDialog.FileName}"
rem exec commands powershell and get result in FileName variable
for /f "delims=" %%I in ('%pwshcmd%') do set "FileName=%%I"
echo %FileName%

Batch + PowerShell + C# polyglot solution
This is the same solution as the Batch + PowerShell hybrid, but with the C# fallback stuff re-added for XP and Vista compatibility. Multiple file selection has been added at xNightmare67x's request.
<# : chooser_XP_Vista.bat
:: // launches a File... Open sort of file chooser and outputs choice(s) to the console
:: // https://stackoverflow.com/a/36156326/1683264
#echo off
setlocal enabledelayedexpansion
rem // Does powershell.exe exist within %PATH%?
for %%I in ("powershell.exe") do if "%%~$PATH:I" neq "" (
set chooser=powershell -noprofile "iex (${%~f0} | out-string)"
) else (
rem // If not, compose and link C# application to open file browser dialog
set "chooser=%temp%\chooser.exe"
>"%temp%\c.cs" (
echo using System;
echo using System.Windows.Forms;
echo class dummy {
echo public static void Main^(^) {
echo OpenFileDialog f = new OpenFileDialog^(^);
echo f.InitialDirectory = Environment.CurrentDirectory;
echo f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
echo f.ShowHelp = true;
echo f.Multiselect = true;
echo f.ShowDialog^(^);
echo foreach ^(String filename in f.FileNames^) {
echo Console.WriteLine^(filename^);
echo }
echo }
echo }
)
for /f "delims=" %%I in ('dir /b /s "%windir%\microsoft.net\*csc.exe"') do (
if not exist "!chooser!" "%%I" /nologo /out:"!chooser!" "%temp%\c.cs" 2>NUL
)
del "%temp%\c.cs"
if not exist "!chooser!" (
echo Error: Please install .NET 2.0 or newer, or install PowerShell.
goto :EOF
)
)
rem // Do something with the chosen file(s)
for /f "delims=" %%I in ('%chooser%') do (
echo You chose %%~I
)
rem // comment this out to keep chooser.exe in %temp% for faster subsequent runs
del "%temp%\chooser.exe" >NUL 2>NUL
goto :EOF
:: // end Batch portion / begin PowerShell hybrid chimera #>
Add-Type -AssemblyName System.Windows.Forms
$f = new-object Windows.Forms.OpenFileDialog
$f.InitialDirectory = pwd
$f.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
$f.ShowHelp = $true
$f.Multiselect = $true
[void]$f.ShowDialog()
if ($f.Multiselect) { $f.FileNames } else { $f.FileName }
For a folder chooser for XP or Vista, use either the WSH solution or npocmaka's HTA solution.

Two more ways.
1.Using a hybrid .bat/hta (must be saved as a bat) script .It can use vbscript or javascript but the example is with javascrtipt.Does not create temp files.Selecting folder is not so easy and will require an external javascript libraries , but selecting file is easy
<!-- : starting html comment
:: FileSelector.bat
#echo off
for /f "tokens=* delims=" %%p in ('mshta.exe "%~f0"') do (
set "file=%%~fp"
)
echo/
if not "%file%" == "" (
echo selected file is : %file%
)
echo/
exit /b
-->
<Title>== FILE SELECTOR==</Title>
<body>
<script language='javascript'>
function pipeFile() {
var file=document.getElementById('file').value;
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
close(fso.Write(file));
}
</script>
<input type='file' name='file' size='30'>
</input><hr><button onclick='pipeFile()'>Submit</button>
</body>
1.1 - without submit form proposed by rojo (see comments):
<!-- : starting html comment
:: FileSelector.bat
#echo off
for /f "tokens=* delims=" %%p in ('mshta.exe "%~f0"') do (
set "file=%%~fp"
)
echo/
if not "%file%" == "" (
echo selected file is : "%file%"
)
echo/
exit /b
-->
<Title>== FILE SELECTOR==</Title>
<body>
<script language='javascript'>
function pipeFile() {
var file=document.getElementById('file').value;
var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
close(fso.Write(file));
}
</script>
<input id='file' type='file' name='file' size='30' onchange='pipeFile()' >
</input>
<hr>
<button onclick='pipeFile()'>Submit</button>
<script>document.getElementById('file').click();</script>
</body>
2.As you already using powershell/net you can create selfcompiled jscript.net hybrid.It will not require temp cs file for compilation and will directly use the built-in jscrript.net compiler.There's no need of powershell too and the code is far more readable:
#if (#X)==(#Y) #end /* JScript comment
#echo off
:: FolderSelectorJS.bat
setlocal
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
set "jsc=%%v"
)
if not exist "%~n0.exe" (
"%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)
for /f "tokens=* delims=" %%p in ('"%~n0.exe"') do (
set "folder=%%p"
)
if not "%folder%" == "" (
echo selected folder is %folder%
)
endlocal & exit /b %errorlevel%
*/
import System;
import System.Windows.Forms;
var f=new FolderBrowserDialog();
f.SelectedPath=System.Environment.CurrentDirectory;
f.Description="Please choose a folder.";
f.ShowNewFolderButton=true;
if( f.ShowDialog() == DialogResult.OK ){
Console.Write(f.SelectedPath);
}

I will leave an 'echo' even to verify that multiple choice works in this code
echo off
set cmd=Add-Type -AssemblyName System.Windows.Forms;$f=new-object Windows.Forms.OpenFileDialog;$f.InitialDirectory= [environment]::GetFolderPath('Desktop');$f.Filter='Text Files(*.txt)^|*.txt^|All Files(*.*)^|*.*';$f.Multiselect=$true;[void]$f.ShowDialog();if($f.Multiselect) {$f.FileNames}else{$f.FileName}
set pwshcmd=powershell -noprofile -command "&{%cmd%}"
for /f "tokens=* delims=" %%I in ('%pwshcmd%') do call :sum "%%I" ret
echo =========
echo --%ret%--
pause
exit /B
:sum [mud] [ret]
echo "%~1"
set FileName=%FileName% "%~1"
set ret=%FileName%
exit /B

I has been wrote my own portable solution:
https://github.com/andry81/contools/tree/HEAD/Utilities/src/_gui/wxFileDialog/
You can download executable from here:
https://github.com/andry81/contools/tree/HEAD/Utilities/bin/contools/wxFileDialog.exe
The utility has dependency on wxWidgets 3.1.x, so you can actually build it for other operating systems.

Related

How to execute a powershell file in batch repeatadly

I have a question. With my batch program I want to call a powershell program to replace words. I tried it with batch, but in my files are very often exclamation marks and yeah...batch don`t like these. So I take my batch strings and put them into powershell. This works perfectly fine. But I want to repeat this with other words and there is my problem.
set /a loop=0
:inta
set /a loop=%loop%+1
call:DoReplace "%Torsten%" "%Torsten:~0,-1%%loop%" cache\%KlausDieter:~0,-5%%loop%%Rainer% cache1\%KlausDieter:~0,-5%%loop%%Rainer%
exit /b
:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy remotesigned -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
GOTO :wer
:wer
set installel=%errorlevel%
if %loop%==%count% goto fall
if %installel%==0 goto inta
:fall
set /a loop=0
:intal
set /a loop=%loop%+1
call:DoReplaceL "%Horst%" "%Horst:~0,-1%%loop%" cache0\%Bruno:~0,-5%%loop%%Rainer% cache1\%Bruno:~0,-5%%loop%%Rainer%
exit /b
:DoReplaceL
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy remotesigned -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
GOTO :werl
:werl
set installel=%errorlevel%
if %loop%==%count% goto falll
if %installel%==0 goto intal
:falll
When I call it a second time there come a error with: Argument "Rep.ps1" isnt available. Isnt it possible to do such things?
I am from Germany so sorry for the bad english.
Thank you for your help
Markus
My batch-code for search and replace was this. Maybe you will find a mistake to get rid of problems with exclamation marks:
set /a loop=0
:inta
set /a loop=%loop%+1
SET "quell_datei=cache\%KlausDieter:~0,-5%%loop%.cin"
SET "ziel_datei=cache1\%KlausDieter:~0,-5%%loop%.cin"
SET "suchen_nach=%Torsten%1"
SET "ersetzen_durch=%Torsten%%loop%"
IF NOT DEFINED suchen_nach (ECHO. Fehler: Die Variable suchen_nach nicht definiert^^!&GOTO :eof)
del "%ziel_datei%" >nul 2>&1
FOR /f "tokens=1,* delims=:" %%a IN ('type "%quell_datei%" ^| FINDSTR /n "^"') DO (
CALL :ers "%%b"
)
GOTO :wer
:ers
set "zeile=%~1"
if defined zeile set "zeile=!zeile:%suchen_nach%=%ersetzen_durch%!"
>>"%ziel_datei%" echo.!zeile!
GOTO :eof
:wer
set installel=%errorlevel%
if %loop%==%count% goto fall
if %installel%==0 goto inta
:fall
echo.

Calling powershell function in batch script

Hoping someone can point me in the right direction. Have a working remote PC info scanning tool that collects computer name, serial number and model. Been trying to get the monitor info added for so time and found this Powershell script and have been trying to get intergraded without success.
Powershell function;
$Monitors = Get-WmiObject WmiMonitorID -Namespace root\wmi
$LogFile = ".\MonInfo.csv"
function Decode {
If ($args[0] -is [System.Array]) {
[System.Text.Encoding]::ASCII.GetString($args[0])
}
Else {
"Not Found"
}
}
ForEach ($Monitor in $Monitors) {
$Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
$Name = Decode $Monitor.UserFriendlyName -notmatch 0
$Serial = Decode $Monitor.SerialNumberID -notmatch 0
echo $Manufacturer, $Name, $Serial" >> $LogFile
}
Here's the network scan batch script I been using. (Basic info scan via ping and get info from remoter systems via WMI)
#echo off
cls
color 5f
setlocal EnableDelayedExpansion
net session >nul 2>&1
if %errorlevel% neq 0 set errormsg=This program must be run as Administrator& goto ERRORDISP
set "ip="
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| findstr /c:"IPv4 Address"') do set ip=%%a
if not defined ip (set errormsg=No IP address detected - check network cable& goto ERRORDISP)
set ip=%ip: =%
for /f "tokens=1,2,3,4 delims=." %%a in ("%ip%") do set oct1=%%a& set oct2=%%b& set oct3=%%c& set oct4=%%d
set subnet=%oct1%.%oct2%.%oct3%
set scan=0
set found=0
set foundsv=0
set ipstart=51
set ipend=170
:SCAN
set /a totalip=ipend-ipstart+1
set "_d=%date%"
set "_t=%time%"
set "log=scanLog%-d%-%_t%.csv"
echo IP,Name,Serial,Model > %log%
echo.
for /l %%a in (%ipstart%,1,%ipend%) do (
set "ip=%subnet%.%%a"
set /a scan=scan+1
set /a pct=scan*100/totalip
echo Scanning !ip!...
call :BAR !pct! 40 progbar
title Simple Scanner ^| !totalip!/!scan!/!found!/!foundsv! ^| [!progbar!] !pct!%%%
ping -n 1 -w 200 !ip! | find "TTL" >nul
if !errorlevel! equ 0 (
set "output="
set /a found=found+1
call :GETWMI !ip! "bios get serialnumber" serial
call :GETWMI !ip! "computersystem get model" model
call :GETWMI !ip! "computersystem get name" name
REM *** DO "SV WORKSTATION" THINGS HERE
set "output=!ip!,!name!,!serial!,!model! !MonSN!"
) else (
REM *** DO "NON-SV WORKSTATION" THINGS HERE
set "output=!ip!,!name!,!serial!,!model! !MonSN!"
)
echo !output! >> %log%
) else (
REM *** DO "WORKSTATION NOT DETECTED" THINGS HERE
)
)
:END
cls
color 2f
echo.
echo SCAN COMPLETE
echo ______________________________________________________________________
echo.
echo
echo Range: %subnet%.%ipstart% - %ipend%
echo Scanned: %scan%
echo Found total: %found%
echo Found SV: %foundsv%
echo ______________________________________________________________________
echo.
echo Opening log file %log%...
echo.
start /max %log%
echo
echo Press any key to exit...
pause>nul
exit
:GETWMI
set "_s="
set _r=%2
set _r=%_r:"=%
(for /f "tokens=2 delims==" %%b in ('wmic /failfast:on /node:%1 %_r% /value') do set _s=%%b) 2>nul
if not defined _s set "_s=ERROR"
set "%~3=%_s%"
goto :eof
:BAR
if not defined xbar call :initBAR %2
for /l %%b in (1,1,%2) do (
set /a bars=%2*%1/100
set /a spcs=%2-bars
set "obar="
for %%c in (!bars!) do set "obar=!obar!!xbar:~0,%%c!"
for %%c in (!spcs!) do set "obar=!obar!!xspc:~0,%%c!"
set %3=!obar!
)
goto :eof
:initBAR
set "xbar=" & for /l %%b in (1,1,%1) do set "xbar=!xbar!l"
set "xspc=" & for /l %%b in (1,1,%1) do set "xspc=!xspc! "
goto :eof
:ERRORDISP
cls
color cf
echo.
echo ^>^>^> ERROR ^<^<^<
echo.
echo %errormsg%
echo
echo Press any key to exit...
pause>nul
exit
I have also tried calling for the .ps1 yet the variables are always empty and the corp network requires Powershell scripts to have sign cert to run by them selves.
Long time ago I wrote the script to get monitor serial number from registry.
It takes only first monitor value. But you can change this script or convert to Powershell. Anyway you can see script logic: get EDID-number, then parse it.
#for /f %%i in ('#wmic path win32_desktopmonitor get pnpdeviceid ^|#find "DISPLAY"') do #set val="HKLM\SYSTEM\CurrentControlSet\Enum\%%i\Device Parameters"
#reg query %val% /v EDID>NUL
#if %errorlevel% GTR 0 #echo BAD EDID&EXIT
#for /f "skip=2 tokens=1,2,3*" %%a in ('#reg query %val% /v EDID') do #set edid=%%c
#set /A Y=%edid:~34,1%*16+%edid:~35,1%+1990
#echo.Manufactured: %Y%
#set id=%edid:000000FC00=#%
#for /f "tokens=1,2* delims=#" %%a in ("%id%") do #set id=%%b
#set id=%id:~0,22%
#setlocal enableextensions enabledelayedexpansion
#echo off
#for /L %%i in (0,2,20) do (
#set p=!id:~%%i,2!
#if !p!==0A #goto nxt
#set m=!m!0x!p!
)
#echo on
:nxt
#forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c #echo.Model : !m!"
#endlocal
#set edid=%edid:000000FF00=#%
#for /f "tokens=1,2* delims=#" %%a in ("%edid%") do #set id=%%b
#set id=%id:~0,20%
#setlocal enableextensions enabledelayedexpansion
#for /L %%i in (0,2,18) do #set sn=!sn!0x!id:~%%i,2!
#forfiles /p %windir%\system32 /m shell32.dll /c "cmd /c #echo.S.N. : !sn!"
#endlocal

How to delete this kind of file using a reserved name?

Hi for everyone in stackoverflow !
I'm looking for a workaround to how delete this kind of file using a reserved name such :
(nul, aux, com1, prn, etc...)
So, i get as output error :
The syntax of the file name, directory or volume incorrect.
#echo off
echo hello world>\\?\"%temp%\nul:nul"
pause
more<"%temp%\nul:nul"
pause
set /p MyVar=<"\\?\%temp%\nul:nul"
echo %MyVar%
Pause
Del "\\?\%temp%\nul:nul" /F
pause
I'm using this trick to store the password shown like in this code below
so, i can set the password into this file and also, read from it, but i can't delete it.
#echo off
Title %~n0 with colors by Hackoo
Mode 50,5 & Color 0E
Setlocal EnableDelayedExpansion
:CreatePassword
Call :InputPassword "Please choose your password" pass1
Call :InputPassword "Please confirm your password" pass2
If !pass1!==!pass2! ( Goto:Good ) Else ( Goto:Bad )
::***********************************
:InputPassword
Cls
echo.
echo.
set "psCommand=powershell -Command "$pword = read-host '%1' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set %2=%%p
Goto :eof
::***********************************
:Good
Cls
echo.
echo.
Call :Color 0B " Good password " 1
TimeOut /T 2 /NoBreak>nul
Call :Write_Info
Call :Collect_Info
echo Your password stored as : "!SavedPass!" without quotes
pause
Goto :Eof
::***********************************
:Bad
Cls
echo.
echo.
Call :Color 0C " Wrong password try again " 1
TimeOut /T 2 /NoBreak>nul
Goto :CreatePassword
::***********************************
:Color
for /F "delims=." %%a in ('"prompt $H. & for %%b in (1) do rem"') do set "BS=%%a"
set nL=%3
if not defined nL echo Requires third argument & Pause > nul & goto :Eof
if %3 == 0 (
<nul set /p ".=%BS%">%2 & Findstr /V /A:%1 /R "^$" %2 nul & Del %2 2>&1
goto :Eof
) else if %3 == 1 (
echo %BS%>%2 & Findstr /V /A:%1 /R "^$" %2 nul & Del %2 2>&1
goto :Eof
)
::***********************************
:Write_Info
(echo !Pass2!)>\\?\"%temp%\nul:nul"
Call :Color 0A " Your password is set sucessfuly" 1
::***********************************
:Collect_Info
(set /P SavedPass=)<"\\?\%temp%\nul:nul"
goto :eof
::***********************************
This worked for me:
del "\\.\%temp%\nul"
As Microsoft says in
https://support.microsoft.com/en-us/kb/120716,
you need to use a syntax which bypasses the check for reserved names.

Batch - Compare file date with actual date

I get the file date from a file:
for %%x in (%file_test%) do set file_date_test=%%~tx
And then I get the system date:
set year=%date:~-4%
set month=%date:~3,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
And then do an if statement with goto:
IF %file_date_test% LSS %system_date_test% goto SOME
How can I compare both dates? I would like to check if the file date has more than 24H.
Which is the best way to do that? Can I use forfiles to do it?
Edited forfiles command will not even look at the hour of the file, so the previous answer (at the bottom in case someone find it useful) will not work if the file has different date but less than 24h.
For an alternative
robocopy "c:\backup" "c:\backup" "test.bak" /l /nocopy /is /minage:1 > nul
if errorlevel 1 (
echo MATCH
) else (
echo NO_MATCH
)
At least in windows 7, the robocopy command look at the timestamp of the file to determine its age.
Previous answer
You can use forfiles checking the errorlevel of the operation
#echo off
setlocal enableextensions disabledelayedexpansion
set "file_test=c:\backups\test.bak"
for %%a in ("%file_test%") do (
forfiles /p "%%~dpa." /m "%%~nxa" /d -1 >nul 2>nul && echo MATCH || echo NO MATCH
)
Or
#echo off
setlocal enableextensions disabledelayedexpansion
forfiles /p "c:\backups" /m "test.bak" /d -1 >nul 2>nul
if errorlevel 1 (
echo NO_MATCH
) else (
echo MATCH
)

Copying a folder, but excluding specified sub-directories

I need help with copying a folder, but doesn't copy sub-folders with the names that are specified in a text file. The text file is located:
U:\Directory\Directory\Textfile.txt
I need to copy folders that are specified in the text file, but here's the catch, after
U:\Directory\Directory\ the folders have random names, which is why they are stored in the text file. Example of what the directory tree looks like:
U:\Directory\Directory\"12345"\Pickle <--- Pickle is the folder I want.
U:\Directory\Directory\"22345"\Pickle
^
|
This is a random name specified in the text file.
They all have the folder Pickle inside, which is what I'm after. Inside the text file are names of all the folders that are after: U:\Directory\Directory\. The text file looks like this:
1335232 <--- This is the name of the random folders.
1242334 <--- They all are located:
2342312 <--- U:\Directory\Directory\~HERE~
(etc...)
The folders should be copied from U:\Directory\Directory\"12345"\Pickle to U:\Output\
The names for all folders are numbers if this helps. Thank you Peter for trying to help me, I'm sorry if I was unclear. I hope this clears things up!
#ECHO OFF
SETLOCAL
SET relroot=u:\directory
SET subdir=randomsubfoldername
::
FOR /f %%i IN (
'dir /b /ad %relroot%\%subdir% ^|findstr /b /e /v /g:textfile.txt '
) DO ECHO %relroot%\%subdir%\%%i
The DIR command lists the directorynames (/ad) in basic form (.b) - that is, name-only. The findstr finds lines that do not (/v) begin (/b) and end (/e) with the lines in the file filename (/g:filename)
With the revised information, and noting that the original information clearly showed the penultimate directory name was the same and selection occurring on the leaf, and the single example now provided...
#ECHO OFF
SETLOCAL
ECHO Here is a test structure
ECHO -----------------------------
DIR /s /b /ad u:\directory
ECHO ------Here is the textfile---------
TYPE u:\directory\textfile.txt
ECHO ====Method 1==============
FOR /f %%i IN (u:\directory\textfile.txt) DO (
DIR /s /b /ad u:\directory | FINDSTR /r ".*\\%%i\\.*" | FINDSTR /v /r ".*\\%%i\\.*\\.*"
)
ECHO ====Method 2==============
FOR /f %%i IN (u:\directory\textfile.txt) DO (
FOR /f %%s IN (
'DIR /s /b /ad u:\directory ^| FINDSTR /r ".*\\%%i\\.*" ^| FINDSTR /v /r ".*\\%%i\\.*\\.*"'
) DO ECHO selected : %%s
)
ECHO ====Method 3 - to ignore ...\target\subdir that has any subdir ==============
FOR /f %%i IN (u:\directory\textfile.txt) DO (
FOR /f %%s IN (
'DIR /s /b /ad u:\directory ^| FINDSTR /r ".*\\%%i\\.*" ^| FINDSTR /v /r ".*\\%%i\\.*\\.*"'
) DO (
FOR /f %%c IN ( 'DIR /a:d %%s ^|FIND /c "<" ' ) DO IF %%c==2 ECHO SELECTED : %%s
)
)
Here's the run results:
Here is a test structure
-----------------------------
u:\directory\another
u:\directory\yetanother
u:\directory\572
u:\directory\another\yetanother
u:\directory\another\yetanother\572
u:\directory\another\yetanother\1572
u:\directory\another\yetanother\5722
u:\directory\another\yetanother\572\wantthis
u:\directory\another\yetanother\572\andthis
u:\directory\another\yetanother\572\maywantthisidontknow
u:\directory\another\yetanother\572\572
u:\directory\another\yetanother\572\maywantthisidontknow\ignore
u:\directory\another\yetanother\1572\ignorethis
u:\directory\another\yetanother\5722\ignorethis
u:\directory\yetanother\572
u:\directory\yetanother\572\wantthis
u:\directory\572\wantthis
------Here is the textfile---------
23
753309
572
====Method 1==============
u:\directory\another\yetanother\572\wantthis
u:\directory\another\yetanother\572\andthis
u:\directory\another\yetanother\572\maywantthisidontknow
u:\directory\another\yetanother\572\572
u:\directory\yetanother\572\wantthis
u:\directory\572\wantthis
====Method 2==============
selected : u:\directory\another\yetanother\572\wantthis
selected : u:\directory\another\yetanother\572\andthis
selected : u:\directory\another\yetanother\572\maywantthisidontknow
selected : u:\directory\another\yetanother\572\572
selected : u:\directory\yetanother\572\wantthis
selected : u:\directory\572\wantthis
====Method 3 - to ignore ...\target\subdir that has any subdir ==============
SELECTED : u:\directory\another\yetanother\572\wantthis
SELECTED : u:\directory\another\yetanother\572\andthis
SELECTED : u:\directory\another\yetanother\572\572
SELECTED : u:\directory\yetanother\572\wantthis
SELECTED : u:\directory\572\wantthis
The two FINDSTR regex structures are
FINDSTR /r ".*\\%%i\\.*"
Any number of any characters, \, the target string, \, any number of any characters
FINDSTR /v /r ".*\\%%i\\.*\\.*"
Any number of any characters, \, the target string, \, any number of any characters,\, any number of any characters
BUT - the /v on FINDSTR means except lines matching...
I can make little sense of copy the sub-folder from a parent folder with a random name.
If the requirement is to copy into the selected directory from that directory's parent directory, then after verifying that the target directories being displayed by ECHO SELECTED : %%s replace ECHO SELECTED : %%s with
(
pushd %%s
xcopy ..\* . >nul
popd
)
The >nul suppresses xcopy reports
If it means something else, more information is required.