Keep the same file name on output file on a batch file - batch-file

I'm currently working on an encrypting/decrypting automatization project and I need to create batch files for the task scheduler
And I'm facing the issue with the decrypting command
--passphrase "password" --batch -d --output ".JOAARPT.out" "*.JOAARPT"
the command decrypts all the JOAARPT files and changes the output file to JOAARPT.out but I cannot make the created decrypted file keep the same name as the source file
What wildcard should I use?

In cmd.exe a FOR loop is needed. Yes, it is awkward, but it is what it is. Use the FOR /? command to learn all about it.
FOR /F "delims=" %%A IN ('DIR /B "*.JOAARPT"') DO (
decry.exe --passphrase "password" --batch -d --output "%%~nA.JOAARPT.out" "%%~A"
)
If you wanted to step up to PowerShell, you could:
Get-ChildItem -File -Filter "*.JOAARPT" |
ForEach-Object {
& decry.exe --passphrase "password" --batch -d --output $($_.BaseName + '.JOAARPT.out') "$_.FullName"
}

Related

Multiple commands using Plink and batch file for Cisco switch

I am currently trying to write a script to change the location (snmp) of more than 200 Cisco switches.
My problem is that I can't run more than one command at once. I've made a batch file which connects to the switch automatically and reads a .txt file where the commands are listed. But no matter what I do the best result I got was that only the first command was executed.
batch File:
cmd.exe /c echo n | "Filepath(plink)" -ssh Switch Hostname -l Username -pw "Password" -m "txt File"
txt File:
conf t
snmp-server location test
end
wr
exit
I've already tried other delimiters in the txt-File like ; | etc.
But nothing seems to work.
It's actually a known limitation of Cisco, that it does not support multiple commands in an SSH "exec" channel command.
Quoting section 3.8.3.6 -m: read a remote command or script from a file of PuTTY/Plink manual:
With some servers (particularly Unix systems), you can even put multiple lines in this file and execute more than one command in sequence, or a whole shell script; but this is arguably an abuse, and cannot be expected to work on all servers. In particular, it is known not to work with certain ‘embedded’ servers, such as Cisco routers.
Though actually, your commands are probably not standalone top-level shell commands anyway. I guess that the snmp-server (and others) are subcommands of conf t, aren't they? So your code would not work, even if Cisco did support multiple commands on the "exec" channel.
For details, see How to type commands in PuTTY by creating batch file?
You need to execute the conf t and then provide its subcommands to its standard input.
One way to do that is like this:
(
echo snmp-server location test
echo end
echo wr
echo exit
) | plink -ssh hostname -l username -pw password conf t
If the above mentioned Cisco limitation doesn't affect this syntax:
SET /P USERNAME=Enter remote Username:
SET "psCommand=powershell -Command "$pword = read-host 'Enter remote Password' -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
plink -t -pw %PASSWORD% %USERNAME%#Hostname "COMMAND1; COMMAND2; COMMAND3; ETC"
If the above mentioned Cisco limitation DOES affect the above syntax:
SET /P USERNAME=Enter remote Username:
SET "psCommand=powershell -Command "$pword = read-host 'Enter remote Password' -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
plink -t -pw %PASSWORD% %USERNAME%#Hostname "COMMAND1"
plink -t -pw %PASSWORD% %USERNAME%#Hostname "COMMAND2"
plink -t -pw %PASSWORD% %USERNAME%#Hostname "COMMAND3"
plink -t -pw %PASSWORD% %USERNAME%#Hostname "Etc"
Barbaric, yes, but I think Cisco can be thanked for that ;) (This is un-tested as I don't have a cisco device to poke at, but theory should be sound)

How to write a directory listing to a text file on Windows?

I have a folder that contains over 40,000 video files.
I want to be able to list them all in a text file
I've used the command:
#echo off
set dirpath=%location
dir %dirpath% /-p /o:gn > "%dirpath%\DirContents.txt"
exit
However, this just list the directory command thats in cmd.
I want to be able to do this: have a text file that has:
File Name, Date Modified
import glob
import os
import time
with open("DirContents.txt","w") as fOut:
fOut.write("FileName, DateModified\n")
files = glob.glob("~/Videos/*")
for fName in files:
stat = time.ctime(os.stat(fName).st_mtime)
fOut.write("\""+ fName + "\", \"" + stat+"\"\n")
This is easily done using PowerShell. If you are on a supported version of Windows, it will have PowerShell.
Run this in a cmd.exe shell.
SET "LOCATION=C:\src\t"
powershell -NoLogo -NoProfile -Command ^
"Get-ChildItem -Path %LOCATION% |" ^
"ForEach-Object { '{0},{1}' -f #($_.Name, $_.LastWriteTime) }"
If you can use PowerShell without cmd.exe, it is even easier. Run this in a PowerShell shell.
$Location = 'C:\src\t'
Get-ChildItem -Path $Location |
ForEach-Object {'{0},{1}' -f #($_.Name, $_.LastWriteTime)} |
Out-File -FilePath "$Env:USERPROFILE\Desktop\DirContents.txt" -Encoding ascii
If you want to just stick with the old ways, run this in a cmd.exe shell.
FORFILES /P C:\src\t /M *.txt /C "cmd /c ECHO #file,#fdate #ftime"

User-specified scripts and output folders for sqlcmd in batch file

Currently, the below For/Do loop goes through all SQL files that are in the same folder as the batch file itself and outputs the CSVs to a user-specified folder (%OUTPUTFOLDER% is actually created earlier in the batch file as a subfolder of %SCRIPTFOLDER%, which is specified by the user):
FOR /F "tokens=*" %%S IN (
'DIR /B "%SCRIPTFOLDER%\*.sql" '
) DO (
echo Reading scripts from: %SCRIPTFOLDER%\*.sql
echo Script: %%~fS
echo Output: %OUTPUTFOLDER%\%%~nS.csv
sqlcmd -b -S %INSTANCE% -d %DATABASE% -i "%%~fS" -s "|" -o "%OUTPUTFOLDER%\%%~nS.csv" -W
IF ERRORLEVEL 1 GOTO errorhandling
ECHO %%~nS.csv successfully created
)
For a visual example, if I had the folder structure
C:\Extract\extract.bat
C:\Extract\Scripts\
C:\Extract\Output\
The variable %SCRIPTFOLDER% is set by the user and is the folder that, you guessed it, holds the scripts. But the batch file has to be in that folder, too. I need to change this so that the scripts do not have to be in the same folder as the batch file. I.e. the user can specify both %SCRIPTFOLDER% and %OUTPUTFOLDER%
Due to the output of echo Script: %%fS, I'm guessing that's what I need to change - possibly what's in the FOR line as well, but I'm not seeing how exactly to do that.

DOS Batch file - Copy file based on filename into folder

I would like to use a batch file to put them into default folder, but the account name is in the middle of the folder. Have any script I can use in dos command prompt?
888123AA.pdf
888123BB.pdf
888123CC.pdf
777456AA.pdf
777456BB.pdf
777456CC.pdf
Default folder:
999-888123-03
666-777456-01
#echo off
setlocal EnableDelayedExpansion
rem Process all .pdf files
for %%a in (*.pdf) do (
rem Get just the file name, ie: "888123AA"
set fileName=%%~Na
rem Using the file name minus two last chars, ie: "888123"
rem get the default folder with that name
for /D %%b in (*-!fileName:~0,-2!-*) do (
rem And copy the file to that folder
copy "%%a" "%%b"
)
)
I don't remember any apparent way to do it other than a UNIX shell... Maybe get MSYS and use that (outdated) bash to help?
Here is a bash script that can use after you installed bash from MSYS (or you can sort it with a Linux box - Ubuntu is no bigger than 800MB and can run as LiveCD without interfering your current Windows system, and the LiveCD can double as a system saver when needed. :-)
#!/bin/bash
for each in ./*; do
if [ -d $each ]; then # Only folders are minded.
# Extract the second part of the folder name.
ACCOUNT_NAME=`echo $each | sed "s/\\-/\n/" | head -n 2 | tail -n 1`
cp -v ./$ACCOUNT_NAME*.pdf $each
fi
done

how to execute all .sql file of current and sub folder using xp_cmdshell

I am using sql server 2008 , I am developing script that get all .sql file of given path ( also serch in subfolder recursively). Thanks in advance.
You could use a batch file like this. Call it ashwin.bat (or whatever you like) and it will look for all the files in C:\tmp\so\ashwin that have a .sql extension and then invokes sqlcmd against all of those files against a named instance database of localhost\localsqla and runs them in the master database.
#echo off
For /R "C:\tmp\so\ashwin\" %%i in (*.sql) DO CALL sqlcmd.exe -E -S localhost\localSQLA -d master -i %%i
A litle enhancement for logging purposes:
#echo off
For /R "C:\Deploy\SQL" %%i in (*.sql) DO CALL echo %%i && sqlcmd.exe -E -S DB_IP -d DATABASE -i %%i -j

Resources