Powershell in Batch: String to Binary and back - powershell

In my batch file, I am trying to convert a string (%input%) to binary and save the result in a batch variable %varBinary%. My attempt:
for /f "delims=" %%a in ( ' powershell " [System.Text.Encoding]::UTF8.GetBytes(/"%_input%"/) | %{ [System.Convert]::ToString($_,2).PadLeft(8,'0') } " ' ) do set "varBinary=%%a"
echo.%varBinary%
echo."%varBinary%"
echo "%varBinary%"
echo %varBinary%
Output of %varBinary% is always empty. What is wrong here? And how to convert back the Binary to the original string so that it works? Because that didn't work either.
For example, hello should be 0110100001100101011011000110110001101111.

You were close, but you missed a few characters that needed to be escaped.
First, powershell (and most other things) uses \ to escape quotes, not /. Second, in batch, plain % need to be escaped by using %% instead. (On a side note, you would normally have to escape the |, but you don't have to here because it's in a quoted string.)
Finally, if you want to build the string and not just return the binary of the last character, you're going to have to enable delayed expansion and concatenate each line of the output.
#echo off
setlocal enabledelayedexpansion
set /p "_input=Input: "
for /f "delims=" %%A in ('powershell "[System.Text.Encoding]::UTF8.GetBytes(\"%_input%\") | %%{[System.Convert]::ToString($_,2).PadLeft(8,'0')}"') do set "varBinary=!varBinary!%%A"
echo.!varBinary!
echo."!varBinary!"
echo "!varBinary!"
echo !varBinary!

Related

Use Variable insted of Get-Date in powershell

I am using PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')" in batch script.
I want to use a variable instead of Get-Date function. Is it possible?
ADate is the variable name!
Edited:
As suggested, my script is:
For /F UseBackQ %%A In (
`PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "Freq=%%A"
Adate is simple string which comes from the file name, and has a value like 16112016.
You need to use a for loop to get the output of an external command in a batch variable:
#echo off
for /f "usebackq tokens=*" %%d in (`powershell "..."`) do set "adate=%%d"
echo %adate%
The usebackq and backticks are just so you don't need to escape the nested single quotes in your command string.
Ok. I got my crystal ball and asked it: "What is the solution here?", and it replied: "Change
PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')"
by
PowerShell "(Get-Date -Date '!Adate:~4!-!Adate:~2,2!-!Adate:~0,2!').AddDays(-7).ToString('ddMMyyyy')"
", but I have no idea what it is talking about! ;)
You can store the output of the powerShell command into a file and then read that file after that delete that temporary file.
PowerShell "(Get-Date).AddDays(-7).ToString('ddMMyyyy')" >temp.txt
set /p myVarDate= < date_Shell.txt
echo Date from Shell %myVarDate%
del temp.txt
The following takes the last modified time from a known file's properties and creates a variable with a date seven days earlier, (obviously changing C:\Test\TestFile.ext as necessary):
For /F UseBackQ %%A In (
`PowerShell "((gi 'C:\Test\TestFile.ext').LastWriteTime).AddDays(-7).ToString('ddMMyyyy')"`
) Do Set "ADate=%%A"
Edit
The following example takes a date string with a known format, (in this case provided in two variables). It then converts that string to a date object, subtracts seven days and sets it back to a string in the new %ADate% variable:
#Echo Off
Set "DateStr=16112016"
Set "DFormat=ddMMyyyy"
For /F UseBackQ %%A In (`Powershell^
"([datetime]::ParseExact('%DateStr%','%DFormat%', [System.Globalization.CultureInfo]::CurrentCulture)).AddDays(-7).ToString('%DFormat%')"
`) Do Set "ADate=%%A"
Echo(%ADate%
Timeout -1

Remove Carriage Return from String Field in File Windows Command Line

I have a file that is ouput with | as the delimiter. However, one of the fields is a description field from the source system which contains carriage returns. This is an issue when trying to read the file as it breaks it on to a new line. What I would like to do is remove all CF/LF that aren't preceeded by a |.
I feel like this should be possible on command line but haven't been able to come up with it.
Sample data
|A|Testing CF/LF
This|CF/LF
Expected Output
|A|Testing This|CF/LF
#ECHO Off
SETLOCAL
SET "line="
(
FOR /f "delims=" %%a IN (q26895698.txt) DO (
CALL :generate "%%a"
)
)>newfile.txt
TYPE newfile.txt
GOTO :EOF
:generate
SET "line=%line%%~1"
IF "%line:~-1%"=="|" SET "line="&FOR %%x IN ("%line%") DO ECHO(%%~x
GOTO :eof
I used a file named q26895698.txt containing your data (such as it was) for my testing.
Produces newfile.txt
Can't help but get the impression that you'd be better off with SED thouh - google "GNU SED" for details...

eol unix to windows in command line .bat batch

I am trying to convert text file eol to windows format from unix on windows xp machine using command line (batch file). how do I do that? what is the command for that? thanks.
This simple script is fast and works great except it converts every TAB character into 8 spaces. The number of spaces can be modified with the MORE /T option, but there is no way to preserve the TAB characters. Pass the file name (optionally with path) as the one and only argument.
#echo off
more %1 >%1.new
move /y %1.new %1 >nul
All that is needed is to read and echo each line. The FOR /F command is perfect, except it ignores empty lines. Here I use FINDSTR to prefix each line with the line number, followed by a :, thus preserving empty lines. Then I use search and replace to remove the number prefix. I must toggle delayed expansion on and off within the loop to preserve any ! that may appear. This script preserves TABs, but is limited to ~8191 bytes per line. It is also relatively slow. It will become very slow with very large files.
#echo off
setlocal disableDelayedExpansion
>%1.new (
for /f "delims=" %%A in ('findstr /n "^" %1') do (
set "ln=%%A"
setlocal enableDelayedExpansion
echo(!ln:*:=!
endlocal
)
)
move /y %1.new %1 >nul
Finally, here is a hybrid batch/JScript solution that is very fast, and does not have any limitations that I am aware of.
#if (#X)==(#Y) #end /* Harmless hybrid line that begins a JScript comment
::************ Batch portion ***********
#echo off
<%1 cscript //E:JScript //nologo "%~f0" >%1.new
move /y %1.new %1 >nul
exit /b
************* JScript portion **********/
while (!WScript.StdIn.AtEndOfStream) {
WScript.Stdout.WriteLine(WScript.StdIn.ReadLine());
}

Batch : read lines from a file having spaces in its path

To read lines from a file, in a batch file, you do :
for /f %%a in (myfile.txt) do (
:: do stuff...
)
Now suppose you file is in C:\Program Files\myfolder
for /f %%a in ("C:\Program Files\myfolder\myfile.txt") do (
echo %%a
)
Result :
C:\Program Files\myfolder\myfile.txt
This seems to interpret the given path as a string, and thus %%a is your given path.
Nothing about this in the documentation I have found so far.
Please someone help me before I shoot myself.
The documentation you get when you type help for tells you what to do if you have a path with spaces.
For file names that contain spaces, you need to quote the filenames with
double quotes. In order to use double quotes in this manner, you also
need to use the usebackq option, otherwise the double quotes will be
interpreted as defining a literal string to parse.
By default, the syntax of FOR /F is the following.
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
This syntax shows why your type workaround works. Because the single quotes say to execute the type command and loop over its output. When you add the usebackq option, the syntax changes to this:
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ('string') DO command [command-parameters]
FOR /F ["options"] %variable IN (`command`) DO command [command-parameters]
Now you double quote paths to files, single-quote literal strings, and put backticks (grave accents) around commands to execute.
So you want to do this:
for /f "usebackq" %%a in ("C:\Program Files\myfolder\myfile.txt") do (
echo %%a
)
Found it.
for /f %%a in ('type "C:\Program Files\myfolder\myfile.txt"') do (
echo Deleting: %%a
)
Don't even ask me why that works.
Just sharing the below code, hoping that somebody will get benefited.
The below code take both the path having spaces and also if the read lines has spaces, it wont cause any issue of the characters after space is missing;
FOR /f "tokens=* delims=," %%a in ('type "C:\Progrem File\My Program"') do (
echo %%a
)

Search and replace with a batch file

I am writing a batch file script using Windows command and want to change each occurrence of some blank space with "," What is the simplest way to do that?
If your users are a list of words on one line in a text file, separated by spaces, eg:
one two three four
Create a batch file SpaceToComma.bat as follows:
#echo off
setlocal
for /F "tokens=* delims= " %%a in (%1) do #set data=%%a
echo %data: =,%
endlocal
Then run it, you'll get the words separated by commas. Is this what you want?
C:\>SpaceToComma.bat data.txt
one,two,three,four
If you have a multi-line file, then this will do it:
data.txt
one two three four
five six seven
SpaceToComma.bat
#echo off
setlocal
for /F "tokens=* delims= " %%a in (%1) do #call :processaline %%a
endlocal
goto :eof
:processaline
setlocal
set data=%*
echo %data: =,%
endlocal
goto:eof
Output
C:\>SpaceToComma.bat data.txt
one,two,three,four
five,six,seven
(There's probably a clever way of doing this without the subroutine, using the !data! syntax for delayed variable expansion, but I couldn't get it to work with the substitution syntax.)
If this is not what you want, then please explain and I can try to help.
(PS: I delight in using batch files where people insist it can't be done.)
You could download sed.exe from http://unxutils.sourceforge.net/ and run this command:
sed -e "s/ /,/" infile.txt >outfile.txt
Well it will depend a lot on how you are getting the data, but you may be able to finagle something with a For-Do construct. Make the field seperator be a space then build the string back in the do with a , between each token. Might I suggest a more robust scripting language? You should have VBScript on just about any relatively modern windows bow.