Batch Duplicate Script - function

I made a batch script that duplicates the file I specify when opening the file via the command line. This is the script:
setlocal
set file=%1
for /f %%i in ("%file%") do (
set drv=%%~di
set path=%%~pi
set ext=%%~xi
set name=%%~ni
)
copy "%1" "%drv%%path%%name% - Duplicate%ext%"
pause
And this is the command I use:
D:\> "duplicate.bat" D:\testfile.txt
This example works perfectly, but when I have a space in the file name, for example:
D:\> "duplicate.bat" D:\test file.txt
The batch file reads the file name as test and the extension is left blank.
Hopefully this is possible :)
Ok, so thanks to madhawa priyashantha for helping with that problem, but now I realise that if I wan't to hide the cmd window that pops up when I run the script, I can use this solution here, but now the script fails to work on files with spaces again. Hopefully this is the last thing I need to do. :)

this is tested and working .if you want to pass argument which consist spaces you need to wrap your argument otherwise bat consider next part after space as a next argument
#echo off
copy %1 "%~n1 - Duplicate%~x1"
pause
now you need to call this bat file like this
m.bat "D:\test file.txt"
and if no spaces,
m.bat "D:\testfile.txt"

Try.
D:> "duplicate.bat" "D:\test file.txt"

Related

Adding functions in .cshrc in C-Shell

I want to add custom functions in my .cshrc file to execute some functionality with some inputs through my command line. I'm using C-shell. is there any way I could implement this or any work around to get the desired result?
C Shell doesnt support functions.
I suggest you can create scripts to emulate the functions and then use alias in the .cshrc file to call those scripts when you type your command in the command line.
e.g , i want to define a new command called test in my csh environment.
So i would add the below line in the .cshrc file
alias test "${HOME}/.test.sh"
Now i would create a .test.sh script in my ${HOME} directory ( or whereever you want it to be) and put the logic for the command inside the script.
An example as follows:
/home/abis> cat .test.sh
#!/usr/bin/ksh
echo $1 $2
Then i would give execute permission to the .test.sh script and source the .cshrc file( it would be done anyway when you open a new login shell).
Then when i execute the command from the command line , the actual script would be called.
/home/abis> test "Hello" "World"
Hello World

Pass parameter from Batch file to MYSQL script

I'm having a really hard time believing this question has never been asked before, it MUST be! I'm working on a batch file that needs to run some sql commands. All tutorials explaining this DO NOT WORK (referring to this link:Pass parameters to sql script that someone will undoubtedly mention)! I've tried other posts on this site verbatim and still nothing is working.
The way I see it, there are two ways I can approach this:
1. Either figure out how to call my basic MYSQL script and specify a parameter or..
2. Find an equivalent "USE ;" command that works in batch
My Batch file so far:
:START
#ECHO off
:Set_User
set usrCode = 0
mysql -u root SET #usrCode = '0'; \. caller.sql
Simply put, I want to pass 'usrCode' to my MYSQL script 'caller.sql' which looks like this:
USE `my_db`;
CALL collect_mismatch(#usrCode);
I know that procedures are a whole other topic to get into, but assume that the procedure is working just fine. I just can't get my parameter from Batch to MYSQL.
Ideally I would like to have the 'USE' & 'CALL' commands in my Batch file, but I can't find anything that let's me select a database in Batch before CALLing my procedure. That's when I tried the above link which boasts a simple command line entry and you're off to the races, but it isn't the case.
Any help would be greatly appreciated.
This will work;
echo SET #usrCode = '0'; > params.sql
type params.sql caller.sql | mysql -u root dbname

Disable My SQL Foreign Key Constrain (FOREIGN_KEY_CHECKS ) from bat file

I need to run around 100 .sql files from a batch file for loading data into a look up table in our application. I need to disable constains before loading process starts and enable it again after the process finish.
My current code is
for /r "%ScriptsPathLookup%" %%f in (*.sql) do (
mysql --host=%Server% --port=%PortNumber% --user=%UserName% --password=%UserPassword% --database=%DB% <%ConstrainPath%\Constrain-disable.sql<%%f)
Here Constrain-disable.sql -> SET FOREIGN_KEY_CHECKS = 0;
But this is not working. I believe if I go and put 'SET FOREIGN_KEY_CHECKS = 0;' in all the .sql files it will load correctly. This is not the best approach and would be tough to maintain. Can anyone suggest a better solution? Thanks.
Your example code has double input redirects < which isn't going to work. A relatively simple approach, using the same looping mechanism that you have, involves creating a temporary file with the disable code at the top and then using that file with the MySQL command.
set TempFile="%TEMP%\MyTempSql.sql"
for /r "%ScriptsPathLookup%" %%f in (*.sql) do (
type %ConstrainPath%\Constrain-disable.sql >%TempFile%
echo.>>%TempFile%
type %%f >>%TempFile%
mysql --host=%Server% --port=%PortNumber% --user=%UserName% --password=%UserPassword% --database=%DB% <%TempFile%
)
del %TempFile%

Using shell script to insert data into remote MYSQL database

I've been trying to get a shell(bash) script to insert a row into a REMOTE database, but I've been having some trouble :(
The script is meant to upload a file to a server, get a URL, HASH, and a file size, connect to a remote mysql database, and insert the data into an existing table. I've gotten it working until the remote MYSQL database bit.
It looks like this:
#!/bin/bash
zxw=randomtext
description=randomtext2
for file in "$#"
do
echo -n *****
ident= *****
data= ****
size=` ****
hash=`****
mysql --host=randomhost --user=randomuser --password=randompass randomdb
insert into table (field1,field2,field3) values('http://www.example.com/$hash','$file','$size');
echo "done"
done
I'm a total noob at programming so yeah :P
Anyway, I added the \ to escape the brackets as I was getting errors. As it is right now, the script is works fine until connects to the mysql database. It just connects to the mysql database and doesn't do the insert command (and I don't even know if the insert command would work in bash).
PS: I've tried both the mysql commands from the command line one by one, and they worked, though I defined the hash/file/size and didn't have the escaping "".
Anyway, what do you guys think? Is what I'm trying to do even possible? If so how?
Any help would be appreciated :)
The insert statement has to be sent to mysql, not another line in the shell script, so you need to make it a "here document".
mysql --host=randomhost --user=randomuser --password=randompass randomdb << EOF
insert into table (field1,field2,field3) values('http://www.site.com/$hash','$file','$size');
EOF
The << EOF means take everything before the next line that contains nothing but EOF (no whitespace at the beginning) as standard input to the program.
This might not be exactly what you are looking for but it is an option.
If you want to bypass the annoyance of actually including your query in the sh script, you can save the query as .sql file (useful sometimes when the query is REALLY big and complicated). This can be done with simple file IO in whatever language you are using.
Then you can simply include in your sh scrip something like:
mysql -u youruser -p yourpass -h remoteHost < query.sql &
This is called batch mode execution. Optionally, you can include the ampersand at the end to ensure that that line of the sh script does not block.
Also if you are concerned about the same data getting entered multiple times and your rdbms getting inconsistent, you should explore MySql transactions (commit, rollback, etc).
Don't use raw SQL from bash; bash has no sane facility for sanitizing the data beforehand. Generate a CSV file and upload that instead.

Robocopy, Multi-Line Execute Process SSIS Task, or Output Batch File Results to SSIS

I need to robocopy files from one location to another in a SSIS package. Since the folder is on another domain, I need to impersonate another account before I run the robocopy.exe command. I found I can execute a "net use" command to impersonate the necessary user account and then execute the robocopy command immediately afterwards. I don't see any way to do this in an Execute Process command to do this directly, so I use an Execute Process task to run a batch file that has these two commands as separate lines. The downside of this approach is that I cannot read the results of the Execute Process command. So this leads me to three questions:
Is there a way to execute a multi-line command in a single Execute Process task?
Is there a way to execute robocopy.exe while impersonating another account in one line?
Is there a way to write the results of a batch file back to either a variable in SSIS or to the SSIS database log?
If there is a positive answer for any of the above three questions, then I may be able to work out a way to add job success or failure rules based on the results of the robocopy command.
This can easily be achived if you have enabled the use of the Extended Stored Procedure "xp_cmdshell" (see Books Online for "Surface Area Configuration").
In the following sample I have build a .CMD file containing all my ROBOCOPY options and simple executes this command file using xp_cmdshell grabbing the output to a table variable (can be a persistent table instead):
Just add a Execute T-SQL statement Task to your SSIS package with the following statement:
/** START **/
DECLARE #cmdfile nvarchar(255) = N'C:\myFolder\myCommandFile.cmd'
DECLARE #logtable table (
[RowId] integer IDENTITY(1,1) NOT NULL
,[Message] nvarchar(1024) NULL
)
INSERT INTO #logtable ([Message])
EXEC xp_cmdshell #cmdfile
SELECT *
FROM #logtable
WHERE
[Message] IS NOT NULL
/** END **/
Depending on your logging options set for the ROBOCOPY command you can show progress, headers, report or more. See the ROBOCOPY documentation for those options. Also try use the /TEE switch if to grab any console output from the ROBOCOPY command.
One way I can think of doing this is to execute a batch command ( so you can execute multiple line items) with RUNAS (to impersonate another user account)
You can capture the output of the batch file in a log file and read the contents of that into SSIS using the Script.
I am not sure on how to write to the SSIS log and am interested to see what other developers have to say about that.
I found two round-about methods for getting data from a batch file execution into the database. One method is to add logging to the actual batch file. I haven't tried this yet, but it seems conceptually possible. The other option I have tried that has worked is to put the batch file execution as a SQL Server Agent job step and add flat-file logging. After I did this, I created a small package that scrapes the file for specific messages. I would still prefer a better solution, but this works well enough for now.
Is there a way to execute a multi-line command in a single Execute
Process task?
Yes, use "Cmd.exe" as executable
Create a string variable with following expression (sample):
*"/C \"start robocopy c:\\temp\\v10.2a c:\\temp\\v1 *.WRI /Z /S && start robocopy c:\\temp\\v10.2a c:\\temp\\v1 *.dll /Z /S\""*
And then map to the arguments parameter via component expression. Then you can execute those two (or more) robocopy in //