I have an issue on inserting data into an excel sheet.
Example: I have bat file like below;
echo %computername%; %userdomain% ; %username%; %date% ; %time% >>
C:\Server\user\palani\logout.csv
This bat file returns the output like this:
ABCD-D-1256G; DIR ; viswa; Wed 09/02/2015 ; 19:17:11.85
The output below is stored in excel sheet single column.
But I want to output a separate column like this:
|ABCD-D-1256G |DIR | viswa |Wed 09/02/2015 | 19:17:11.85
Could you please guide me how to use the tab function or delimiter?
To add a new line you should add a:
& echo.
instead of the >>.
If I understand you're question right.
Your syntax is good, the only problem is the delimiter you use. check what is your List separator in your computer regional settings (control panel -> region and Language -> additionnal settings -> List separator).
Make sure your echo ouput the same thing to separate column than your computer regional settings. If your List separator is set to colon then you need to change your code to look like this:
echo %computername%,%userdomain%,%username%,%date%,%time% >> C:\Server\user\palani\logout.csv
Related
I have this input in my ps script. I am passing $(Build.ArtifactStagingDirectory) system variable to get the path in the input %1. The path has spaces i.e. E:\Build Agents\Agent2\_work\15\a. I need to concatenate this with other path but I am not able to do so.
set BuildDrop=%1
set Directory=%BuildDrop% + "\adapters\bin"
This is my output, which is incorrect as Directory should be something like E:\Build Agents\Agent2\_work\15\a\adapters\bin. How to solve this?
set BuildDrop="E:\Build Agents\Agent2\_work\15\a"
set Directory="E:\Build Agents\Agent2\_work\15\a" + "\adapters\bin"
My task is like this in my build pipeline
Task : Batch script
Description : Run a Windows command or batch script and optionally allow it to change the environment
Version : 1.1.10
I found the solution for this. Since my %1 had space I needed to remove apostrohphe before assigning. I did it using ~ variable. working code looks like this.
set "BuildDrop=%~1"
set "Directory=%BuildDrop%\adapters\bin"
You could try this :
set BuildDrop=%1
set Directory= %BuildDrop%\adapters\bin
echo %Directory%
Sample Output
This is the concatenation code.
%BuildDrop%\adapters\bin
In my above sample I am trying to concatenate C:\Users\svijay\Desktop & \adapters\bin using the batch script
And the output : C:\Users\svijay\Desktop\adapters\bin
UPDATE :
#echo off
set BuildDrop=%1
set Directory= %BuildDrop%\adapters\bin
set Directory= %Directory:"=%
echo %Directory%
If you have space, you could provide the "" to provide input.
In your code you could remove the double quotes.
%Directory:"=% - Removes the Double quotes from the string literal.
Sample output :
You may use this to create Azure DevOps variable containing your path
powershell: |
$directory = $(Build.ArtifactStagingDirectory)
$newDirectory = $directory + "\adapters\bin"
Write-Host "##vso[task.setvariable variable=testvar]$newDirectory "
and if you need set variable in powershell script
$BuildDrop=$args[0]
$Directory=$BuildDrop + "\adapters\bin"
Here you have an article how to use parameters in powershell.
We can use powershell task in the Azure DevOps to concatenate two variables.
Sample:
Write-Host "Build.ArtifactStagingDirectory is $(Build.ArtifactStagingDirectory)"
Write-Host "Build.ArtifactStagingDirectory is $(Build.ArtifactStagingDirectory)\adapters\bin"
Result:
In addition, I found a similar issue, please also check it.
Update1
Use power shell script in the Azure DevOps pipeline
$testpath1 = "E:\Build Agents\Agent2\_work\15\a"
$testpath2 = "\adapters\bin"
Write-Host "path is $($testpath1)$($testpath2)"
Result:
Use local power shell
Result:
Update2
.bat file
set testpath1=E:\Build Agents\Agent2\_work\15\a
set testpath2=\adapters\bin
set newpath=%testpath1%%testpath2%
echo %newpath%
Pipeline result:
For example, I can copy a file to the clipboard like this:
clip < file.txt
(Now the contents of file.txt is in the clipboard.)
How can I do the opposite:
???? > file.txt
So that the contents of the clipboard will be in file.txt?
If it would be acceptable to use PowerShell (and not cmd), then you can use Get-Clipboard exactly as you were looking for.
Get-Clipboard > myfile.txt
The advantage of this method is that you have nothing to install.
Note: In place of clip you can use Set-Clipboard that has more options.
Note 2: If you really want to run it from cmd, you can call powershell as in the following example powershell -command "Get-Clipboard | sort | Set-Clipboard".
You can use the paste.exe software in order to paste text just like you are describing.
http://www.c3scripts.com/tutorials/msdos/paste.html
With it you can do:
paste | command
to paste the contents of the windows clipboard into the input of the specified command prompt
or
paste > filename
to paste the clipboard contents to the specified file.
Clarifying an answer from #Kpym:
powershell -command "Get-Clipboard" > file.txt
This directly answers the question without using a 3rd party tool.
To get contents of clipboard
From win cmd:
powershell get-clipboard
or (via a temp file from HTML parser) on cmd:
echo x = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text") > temp.vbs
echo WScript.Echo x >> temp.vbs
cscript //nologo temp.vbs
Output may be redirected to file.
Using the doskey macro definition feature, you can do:
doskey unclip=(powershell -command "Get-Clipboard") $*
Then (e.g.)
dir/b | clip
unclip | sort/r
I have a pair of utilities (from before the Clip command was part of windows) available on this page:
http://www.clipboardextender.com/general-clipboard-use/command-window-output-to-clipboard-in-vista
There are two utilities in there, Clip2DOS and DOS2Clip. You want Clip2DOS:
Clip2DOS Copyright 2006 Thornsoft Development
Dumps clipboard text (1024 bytes) to stdout.
Usage: Clip2Dos.exe > out.txt
Result: text is in the file.
Limits: 1024 bytes.
License: Free, as in Free Beer!
http://www.thornsoft.com/dist/techsupport/dos2clip.zip
DELPHI SOURCE INCLUDED!
And hey, here it is (Clip2DOS.dpr) :
{Clip2DOS - copyright 2005 Thornsoft Development, Inc. All rights reserved.}
program Clip2Dos;
{$APPTYPE CONSOLE}
uses
Clipbrd,
ExceptionLog,
SysUtils;
var
p : Array[0..1024] of Char;
begin
try
WriteLn('Clip2DOS Copyright 2006 Thornsoft Development');
Clipboard.GetTextBuf(p,1024);
WriteLn(p);
except
//Handle error condition
on E: Exception do
begin
beep;
Writeln(SysUtils.format('Clip2DOS - Error: %s',[E.Message]));
ExitCode := 1; //Set ExitCode <> 0 to flag error condition (by convention)
end;
end
end.
Pasteboard is another option. It can also work from WSL. First, install via choco:
choco install pasteboard
then the command is simply
pbpaste.exe > file.txt
And that works from cmd and wsl bash.
Well, from a million years ago, we did something like this:
type con > filename.txt
... and then you perform your paste operation (Ctrl-v, middle-click the mouse, or choose Edit->Paste from them menu) into the waiting prompt. This will capture the stdin buffer (the console device, named 'con'), and when an end-of-file is received, it will write the contents to the file. So, after your paste, you type 'Ctrl-z' to generate an EOF, and the type command terminates, and the contents of your paste buffer (the clipboard) are captured in 'filename.txt'.
There are third party clip commands that work bidirectionally.
Here's one:
CLIP - Copy the specified text file to the clip board
Copyright (c) 1998,99 by Dave Navarro, Jr. (dave#basicguru.com)
Here is the CLIP program by Dave Navarro, as referred to in the answer by #foxidrive. It is mentioned in an article here: copying-from-clipboard-to-xywrite
A link to the download, along with many other resources is on this page: http://www.lexitec.fi/xywrite/utility.html
Here is a direct link to the download:
"DOWNLOAD Clip.exe Copy from and to the clipboard by Dave Navarro, Jr."
It may be possible with vbs:
Option Explicit
' Gets clipboard's contents as pure text and saves it or open it
Dim filePath : filePath = "clipboard.txt"
' Use the HTML parser to have access to the clipboard and get text content
Dim text : text = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text")
' to open
If Not IsNull(text) then
Dim WshShell, somestring, txFldr2Open
Set WshShell = WScript.CreateObject("WScript.Shell")
txFldr2Open = "C:\Users"
txFldr2Open = text
somestring = "EXPLORER.exe /e," & txFldr2Open ', /select
WshShell.run somestring
Set WshShell = Nothing
else
msgbox("Empty")
end if
' Create the file and write on it
msgbox(text)
Dim fileObj : Set fileObj = CreateObject("Scripting.FileSystemObject").CreateTextFile(filePath)
fileObj.Write(text)
fileObj.Close
You can use cbecho, a program I wrote in plain C. It will send any clipboard text to stdout, from where you can pipe it to other programs.
I am not sure if this command was not supported at that time or not, but it surely does work
clip > file.txt
This dirty trick worked for my needs, and it comes with Windows!
notepad.exe file.txt
Ctrl + V, Ctrl + S, Alt + F, X
Good Day All!
I have a batch script, and when I echo a variable like this
echo %variable1%
I get out put like this
TestLine1
TestLine2
TestLine3
TestLine4
My goal would be to modify this variable to remove all the newline characters so the output would look more like
TestLine1TestLine2TestLine3TestLine4
Is there a simple way to do this without creating files?
Thank you for your assistance.
You can use the command tr:
cleanedVariable1=$(echo $variable1 | tr -d '\n' )
echo $cleanedVariable1
The command tr removes or translates characters. The option -d removes the given characters. In this case, we are removing all new lines from our variable and assign it to a new variable.
Is it possible to execute SQL commands written in a batch (.bat) file without accessing an external SQL script file. How can I do that? I don't want to call an external sql because i want to require as input a month, then execute the sql command that contains that month in some queries.
Asuume you have 3 files in your folder.
file 1 => .sql file
file 2 => mybatchfile1.bat(which has sqlcmds or cmd to execute the above .sql file)
file 3 => one other batch file(myexecute.bat) to call the above batch file(which has content "start mybatchfile1.bat")
All you need to create is myexecute.bat with the below content:
start mybatchfile1.bat
or
call mybatchfile1.bat
You can use either start or call.
Recomend on using powershell script:
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "SERVER\Instance" -Password "Password"
the output will be orginized as a Table and it's far more easy then bat file
Yes, you can run a query from a single DOS batch script, getting input from command line parameters and/or user prompts, rather easily. SQLCMD allows for passing in a query on the command line. By the very nature of passing something into a program from the command line, you can just place the DOS variable wherever you want it to go.
Place the following into a script with an extension of .cmd (you should not be using the .bat extension unless you have a specific need for something to run in a 16-bit process):
#ECHO OFF
ECHO.
SET /P Month="Please enter in a month: "
ECHO.
ECHO.
ECHO Month = %Month%
ECHO.
SET Month=%Month:'=%
ECHO Month with single-quotes removed = %Month%
ECHO.
SQLCMD.EXE -E -Q "IF (COALESCE(TRY_CONVERT(TINYINT, REPLACE('%Month%', '''', '''''')), 0) NOT BETWEEN 1 AND 12) BEGIN RAISERROR('Please enter a value 1 - 12.', 16, 1); RETURN; END; SELECT DATENAME(MONTH, '2014-%Month%-01') AS [MonthName];"
Run it without passing in any parameters. It will prompt for the month. It will then substitute that value in the query, which does its own data validation on the input.
NOTE: be sure to validate input to protect against SQL Injection. The above example replaces single-quotes with escaped-single-quotes for this reason. It also removes all single-quotes before the variable is even used in the query so the REPLACE() is just a redundant safety.
C:\>.\SingleScriptToAcceptParamForQuery.cmd
Please enter in a month: '5
Month = '5
Month with single-quotes removed = 5
MonthName
------------------------------
May
(1 rows affected)
I have been tasked with getting data output from a handheld scanner into a legacy application. The scanner program does not give me any options for formatting output.
I have researched and played with this, but my DOS scripting experience is limited. I found this on your site:
Batch file convert comma delimited to fixed length
but it fails due to the quote-marks; and it does not have the capability to space fill to a desired column width.
The Input file below is what comes from the scanner. The Desired Output is what I need it to look like for the legacy application. The'|' ending each line is not desired. I used it to indicate there are trailing spaces. The output is 8 characters, a comma, then 14 characters; left justified; space filled to the right.
I have another file that has three columns 8,14,14.
Basically, I need to go from .csv to fixed width fields separated by commas.
Input:
"20009","01138913"
"20009","01138915"
"20009","01138916"
"20009","01138914"
"20009","01138918"
"20009","01138920"
"20009","01138919"
Desired output:
20009 ,01138913 |
20009 ,01138915 |
20009 ,01138916 |
20009 ,01138914 |
20009 ,01138918 |
20009 ,01138910 |
20009 ,01138919 |
Any help would be greatly appreciated.
You can use the following, which should also be robust for columns without quotation marks:
#echo off
for /f "tokens=1,2 delims=," %%x in (test.csv) do call :process %%x %%y
goto :eof
:process
set "A=%~1 "
set "B=%~2 "
set "A=%A:~0,8%"
set "B=%B:~0,14%"
(echo %A%,%B%)
There are a few tricks here. First for /f can be used to sort-of parse CSV. We get around the quotes by passing the two column values to a subroutine. As parameters can be quoted or not and we use %~1 to access them, which removes quotes if present, the quotes pose no problem here. %A% and %B% are set to the column values with lots of padding space to the right and the following two lines select the value with the appropriate padding. Then we simply output the lines one by one.
To get an output file, simply redirect into a new file, or add >> out.txt to the last line.
However, if at all you can use other tools, then by all means do so. E.g. in PowerShell this would be fairly trivial:
Parse the file
Import-Csv test.csv -Delimiter ',' -Header A,B |
Output, using a format string
ForEach-Object { '{0,-8},{1,-14}' -f $_.A,$_.B } |
Write to a new file
Out-File out.txt -Encoding Default