Copy a directory over http within a windows batch file - http

I need a command to use in a batch file, which copies the contents of a remote directory to a local directory over http.
For example to copy folder http ://path//folder to C:\folder
I need to do this without installing any additional tools.
Thanks in advance!

There's no standard way for an http server to list accessible directories.
For example I took http://unomoralez.com/content/files/catalog2/source/ as one of the common ways to list directory with http. Your site could look different though but there's no way for me tho know... (ther's a temp list2.txt file - you can remark its deletion to check the format of directory page and tell me if its not working. IF it is IIS could look like this: http://live.sysinternals.com/tools/)
the script downloads all content into .\download_dir (not recursive download) :
#if (#X)==(#Y) #end /****** jscript comment ******
#echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist simpledownloader.exe goto :skip_compilation
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"simpledownloader.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
:: download the file
:::::::::::::::::::::::::::::::::::::::::
::::just change the link and the file::::
:::::::::::::::::::::::::::::::::::::::::
::!!!!!!!!!!!!!!!!!!!!!!!!!:::
simpledownloader.exe "http://unomoralez.com/content/files/catalog2/source/" "list2.txt"
md download_dir >nul 2>&1
for /f "skip=1 tokens=4 delims=>< " %%a in ('type list2.txt^| find /i "href" ') do (
simpledownloader.exe "http://unomoralez.com/content/files/catalog2/source/%%a" .\download_dir\%%a
)
del /q /f list2.txt
exit /b 0
****** end of jscript comment ******/
import System;
var arguments:String[] = Environment.GetCommandLineArgs();
var webClient:System.Net.WebClient = new System.Net.WebClient();
print("Downloading " + arguments[1] + " to " + arguments[2]);
try {
webClient.DownloadFile(arguments[1], arguments[2]);
} catch (e) {
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n\nProblem with downloading " + arguments[1] + " to " + arguments[2] + "Check if the internet address is valid");
Console.ResetColor();
Environment.Exit(5);
}
As you have powershell you also have .net so this code will be executed without problems for you.
This was more or less a code that I already had but you can also check this -> https://code.google.com/p/curlie/ if you are familiar with cURL and create a hybrid jscript/.bat file.

Related

How to create folder by Date time in batch file

I am trying to create a folder by date time in my batch file using following code
#echo off & for /F "tokens=1-4 delims=/ " %%A in ('date/t') do (
set DateDay=%%A
set DateMonth=%%B
set Date=%%C
set DateYear=%%D
)
#echo off & for /F "tokens=1-4 delims=/ " %%D in ('time/t') do (
set DateTime=%%D
)
set CurrentDate=%Date%-%DateMonth%-%DateYear%-0%time:~0,2%.%time:~3,2%.%time:~6,2%
mkdir %CurrentDate%
using this I get folder name as 22-02-2021-010.01.37
But if time Hours is in 1 to 9 hr my folder is displayed as
22-02-2021-0 9.59.19 there is always a space in 0 and 9 and 1 to 9 hr is not displayed as 01,02,03 Hr
Answer Should Be:
22-02-2021-009.59.19
The best and the correct method to get this is to use the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:
#echo off
Title Get FileName With Date and Time
Call :GetFileNameWithDateTime MyCurrentDate
echo %MyCurrentDate%
MkDir %MyCurrentDate%
pause & exit
::----------------------------------------------------------------------------------
:GetFileNameWithDateTime <FileName>
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set "MyDate=%%x"
set "%1=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%-%MyDate:~8,2%-%MyDate:~10,2%"
Exit /B
::----------------------------------------------------------------------------------
set "CurrentDate=%Date%-%DateMonth%-%DateYear%-0%time:~0,2%.%time:~3,2%.%time:~6,2%"
set "CurrentDate=%currentDate: =0%"
mkdir %CurrentDate%
substituting 0 for in currentdate
Tips : Use set "var1=data" for setting values - this avoids problems caused by trailing spaces. In comparisons, use if "thing1" == "thing2" ... to avoid problems caused by spaces in thing1/2.
If you want something which will work on any modern system, and still output the directory name in your specific format/order, regardless of user or locale settings, then…
you could do it like this from a batch-file:
#For /F "Tokens=1-6 Delims=/: " %%G In ('%SystemRoot%\System32\Robocopy.exe \: . /NJH /L ^| %SystemRoot%\System32\find.exe " 123"') Do #MD "%%I-%%H-%%G-0%%J.%%K.%%L"
or directly from the Windows command-line, cmd.exe:
For /F "Tokens=1-6 Delims=/: " %G In ('%SystemRoot%\System32\Robocopy.exe \: . /NJH /L ^| %SystemRoot%\System32\find.exe " 123"') Do #MD %I-%H-%G-0%J.%K.%L

how to find out the existence of a file in system verilog

I have a file abc/xyz.log in log directory. How can I find if the file exists or not in SystemVerilog class. If the file exists I want to delete the file.
Thanks.
You can use $fopen and it returns 0 if it doesn't exist. If it does exist, $fclose the file and then use $system("shell command") to delete it.
Using the Unix utility "test" (see "man test") through a $system call can do the job. It can also be done through direct C using the stat() function (much more cumbersome). This example can be leveraged to do what you want. In this case it checks for the existence of a directory and it not found, attempts to create it.
string report_dir;
report_dir = {SIM_ROOT,"/",PROJ_NAME,"/",TECH_PROCESS,"/",LOGNAME,"/doc/functional"};
if ($system($sformatf("/usr/bin/test -d %s", report_dir)) != 0) begin
$display("INFO: creating output directory %s", report_dir);
if($system($sformatf("mkdir -p %s", report_dir)) != 0) begin
$display("ERROR: mkdir -p %s returned an error", report_dir);
$fatal(0);
end
end
if($system($sformatf("/usr/bin/test -d %s -o -w %s", report_dir, report_dir)) != 0) begin
$display("ERROR: output directory %s does not exist or is not writeable", report_dir);
$fatal(0);
end

PowerShell script not working on server

I have a simple PowerShell script in which I try to write some log data.
The script that's not working:
Add-Content -Path C:\temp\logg.txt -Value $file.FullName
This line I placed in the middle of the script and I never get any text in the logg.txt. The Script executes fine except this, it compiles some files to a zip file.
This is on a Windows server.
If I, however, run the same script on my local machine, Win7, it does work!?
So I think it must be something with the server but I can't figure it out. Am using -ExecutionPolicy Bypass when I run the script.
EDIT: more info.
The script is called from an ASP.NET webpage:
Process.Start("Powershell.exe", "-ExecutionPolicy Bypass -Command ""& {" & destinationFolderRoot.Replace("\\", "\") & "\scriptParameters.ps1}""")
BaseZipScript:
function New-Zip
{
param([string]$zipfilename)
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
function Add-Zip
{
param([string]$zipfilename)
if(-not (Test-Path($zipfilename)))
{
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = New-Object -COM Shell.Application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Add-Content -Path "C:\temp\logg.txt" -Value $file.FullName
Start-Sleep -Milliseconds 750
}
}
scriptParameters1:
. "C:\temp\multiDownload\baseZipScript.ps1"
New-Zip c:\temp\multiDownload\user379\2016-09-15_14.39\files_2016-09-15_14.39.zip
dir c:\temp\multiDownload\user379\2016-09-15_14.39\tempCopy\*.* -Recurse |
Add-Zip c:\temp\multiDownload\user379\2016-09-15_14.39\files_2016-09-15_14.39.zip
Start-sleep -milliseconds 250
exit
As I said earlier the script works on local machine and also on the server, e.g. the files are being zipped, except that on the server nothing is logged in logg.txt.
Though the logg.txt works and exists on the server because the webpage also log some info there and that is being written.
Update:
As the comments guessed it was as simple as write access to the file. Though, it is kind of wierd because all files are created from the webservice if they doesn't exists? Any how, it works now. Thx! : )

Powershell Script to copy files based on date modifed to check newest file from a remote location

I am new to powershell scripting and i cant figure out why my script copies
all files and doesn't seem to check the date and then copies all the files
anyway. I was trying to do by days and minutes too, but I am not quite sure
on how to do that. any help would be great!
see my script below.
$RemotePath = "\\eb-pc\E$\testlocation\*.txt"
$LocalPath = "C:\testlocation"
$Max_days = "-1"
#Max_mins = "-5"
$Curr_date = get-date
#Checking date and then copying file from RemotePath to LocalPath
Foreach($file in (Get-ChildItem $RemotePath))
{
if($file.LastWriteTime -gt ($Curr_date).adddays($Max_days))
{
Copy-Item -Path $file.fullname -Destination $LocalPath
#Move-Item -Path $file.fullname -Destination $LocalPath
}
}
If you want to use Hours and minutes, instead of AddDays, just use the .AddMinutes(), .AddHours(), or .AddSeconds() methods instead.
For what it's worth, I made a small modifcation, adding an Else{Scriptblock} to the script to echo out the files which aren't being copied. As written your code will only copy files written in the last 24 hours.
$RemotePath = "t:\"
$LocalPath = "C:\temp"
$Max_days = "-1"
#Max_mins = "-5"
$Curr_date = get-date
#Checking date and then copying file from RemotePath to LocalPath
Foreach($file in (Get-ChildItem $RemotePath))
{
if($file.LastWriteTime -gt ($Curr_date).adddays($Max_days))
{
Copy-Item -Path $file.fullname -Destination $LocalPath -WhatIf
#Move-Item -Path $file.fullname -Destination $LocalPath
}
ELSE
{"not copying $file"
}
}
>What if: Performing the operation "Copy File" on target "Item: T:\file.htm Destination: C:\temp\file.ht
m".
not copying ListOfSacredVMs.txt
not copying newUser_01.png
not copying newUser_015.png
not copying newUser_02.png
not copying newUser_03.png
What if: Performing the operation "Copy File" on target "Item: T:\values.csv Destination: C:\temp\values.csv".
It has been a while since I did anything in PowerShell. However you may want to try to Echo out the values you are comparing to see what they are really returning.
Echo "LastWrite : " & $file.LastWriteTime
Echo "Copy After : " & ($Curr_date).adddays($Max_days)
This would help to determine what you are attempting to compare.
HopeThisHelps at least a little.

How to get locale-independent modified time and creation time of a file in batch?

With batch variable/parameter expansion like %~t1 one can get a timestamp of a file.
I would like to set the year of the file to another variable would like to support multiple locales.
How can you get a file's datetime, independent of locale and regional settings? No powershell please.
I'll post few options
1)First one is with wmic (not available for XP home edition) (LastModified can be changed with CreationDate or LastAccessed )
#echo off
set file_loc=.\temp_file
for %%# in ("%file_loc%") do set file_loc=%%~dpfnx#
set file_loc=%file_loc:\=\\%
for /f "delims=." %%t in ('"WMIC DATAFILE WHERE name="%file_loc%" get LastModified /format:value"') do (
for /f %%$ in ("%%t") do if "%%$" neq "" set %%$
)
echo %LastModified%
echo year : %LastModified:~0,4%
echo month : %LastModified:~4,2%
echo day : %LastModified:~6,2%
2). Jscript/.bat hybrid (DateLastModified can be changed to DateCreated or DateLastAccessed .Time format can be changed to whatever you want ):
#if (#X)==(#Y) #end /****** jscript comment ******
#echo off
set file_loc=.\temp_file
for %%# in ("%file_loc%") do set file_loc=%%~dpfnx#
::set file_loc=%file_loc:\=\\%
cscript //E:JScript //nologo "%~f0" "%file_loc%"
exit /b 0
****** end of jscript comment ******/
var file_loc = WScript.Arguments.Item(0);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var the_file=fso.GetFile(file_loc);
var the_date= new Date(the_file.DateLastModified);
WScript.Echo(the_date.getFullYear());
WScript.Echo(the_date.getMonth());
WScript.Echo(the_date.getUTCDate());
3) selfcompiled jscript.net/bat hybrid (GetLastWriteTime can be changed to GetLastAccessTime or GetCreationTime . Time format can be changed) :
#if (#X)==(#Y) #end /****** silent line that start jscript comment ******
#echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
set file_loc=.\temp_file
for %%# in ("%file_loc%") do set file_loc=%%~dpfnx#
"%~n0.exe" "%file_loc%"
exit /b 0
****** end of jscript comment ******/
import System;
import System.IO;
var arguments:String[] = Environment.GetCommandLineArgs();
var the_file=arguments[1];
var last_modified=File.GetLastWriteTime(the_file);
Console.WriteLine(last_modified.ToString("yyyy-MM-dd"));
4). robocopy - with this you can get only last modified date (with other methods you can get all time attributes).As time stamps in robocopy are always YYYY/MM/DD HH:mm:SS this can be used...
#ECHO OFF
set file_loc=.\temp_file
for %%# in ("%file_loc%") do set file_dir=%%~dp#
for %%# in ("%file_loc%") do set file_name=%%~nx#
pushd %file_dir%
for /f "tokens=1,2" %%a in ('robocopy "." "%temp%" /l /fat /ts /LEV:1 /NP /NC /NS /NJS /NJH^|findstr /i /e /c:"%file_name%"') do (
echo %%a %%b
)
popd
EDIT Here are ready to use parametrized scripts using all the listed methods:
fileModifiedTime.bat - gets last modified time of file with settings independent format.Based on robocopy
fileTimes.bat - gets file time stamps with WMIC
dirTimes.bat - gets directory time stamps with WMIC
fileTimesJS.bat - file time stamps with jscript
dirTimesJS.bat - directory time stamps with jscript
fileTimesNET.bat - file time stamps with .NET
dirTimesNET.bat - dir time stamps with .NET

Resources