【问题标题】:How can I use powershell to create an ascii to hex converter in batch?如何使用 powershell 批量创建 ascii 到 hex 转换器?
【发布时间】:2014-05-07 13:37:51
【问题描述】:

我对批量编写脚本相当陌生,我正在寻找一种有效的方法来制作 ASCII 到十六进制转换器。我尝试在网上搜索一些教程,但我发现的唯一内容是使用 Perl 或其他脚本语言。

所以我真正的问题是我可以在批处理文件中使用哪些语言?标准语言是什么?什么是兼容的?我知道我真的应该投资一本脚本书或脚本课程,但这只是我在公司从事的众多副项目之一,并且没有太多时间成为专家。提前感谢您提供的任何信息,并帮助消除我的困惑!

编辑

好的,看起来最好的方法是使用支持脚本工具之一,如 VBscript、Jscript 或 powershell。有谁知道哪种方法最适合我的情况。

基本上,我需要从询问如下所示的部件号开始:“BL6A-19T508-NYL”。我可以用这个做到这一点。

SET /p "str1=输入零件号"

但是从那里我应该使用哪个脚本支持工具?以及如何实现它以使用我输入的变量?

从那里我可能应该将十六进制输出回同一个变量。在我的情况下,最好没有十六进制值之间的空格。所以我想将零件号 BL6A-19T508-NY 转换为 424c36412d3139543530382d4e59

我真的不明白我该怎么做

我在从 ascii 转换为 hex 时发现了这个 powershell 代码

$a = "http://www.google.com";
$b = $a.ToCharArray();
Foreach ($element in $b) {$c = $c + " " + [System.String]::Format("{0:X2}", [System.Convert]::ToUInt32($element))}

我尝试使用该网站http://learningpcs.blogspot.com/2009/07/powershell-string-to-hex-or-whatever.html 中的规则来允许它在我的批处理文件中工作。这就是我得到的。

@echo off
SET /p "str1=Enter part number "
powershell.exe -command '$a = "BL6A-19T508-NYL";'
powershell.exe -command '$b = $a.ToCharArray();'
powershell.exe -command 'Foreach ($element in $b) {$c = $c + " " + [System.String]::Format("{0:X2}", [System.Convert]::ToUInt32($element))}'
powershell.exe -command '$c'
pause

我输入了零件编号,并添加了暂停以查看会发生什么。它所做的只是

这不太行......

所以我的第一步是让转换器正常工作。从那里开始,从变量开始工作,最后将十六进制值放回变量或新变量中。

我会继续努力,如果有人看到我可以做的任何事情,或者我做错了什么,将不胜感激。谢谢你们!!

【问题讨论】:

  • 你是说batch还是bash?
  • 我的意思是批量。它们是 .bat 文件,对吗?这就是我一直在玩的。
  • 如果您正在寻找替代方案,内置的 Powershell、VBScript 或 JScript 脚本支持将更适合此。
  • 我可以在我的批处理文件中使用它们吗?我主要担心的是,如果我把它放在网络上供我公司的其他用户使用,他们是否需要在他们的电脑上安装一些特殊的解释器?或者他们只是能够双击它而不用担心它?
  • 所有最近的机器都应该能够运行 VBScript (*.vbs) 或 JScript (*.js) 脚本。 (除非 IT 政策明确拒绝)

标签: batch-file powershell command-line scripting


【解决方案1】:

注意 - 当问题要求批处理解决方案时,我开始研究此答案,然后将其编辑为要求 PowerShell。

这是我心头所爱的话题。 (其实很多科目)

在批处理中嵌入其他脚本语言

有很好的策略可以批量嵌入许多脚本语言。见js/vbs/html/hta hybrids and chimeras in cmd/bat

一般来说,我认为创建混合代码不是一个好主意。 Batch 的功能非常有限。如果您可以编写嵌入另一种语言的混合批处理脚本,那么使用另一种脚本语言简单地编写整个解决方案会更容易、更有效。

但我认为创建独立的混合批处理实用程序来解决批处理的一些限制是合理的。这些实用程序可用于为任何想要继续批量工作的人有效地扩展批处理语言。当然,第 3 方可执行文件可以做同样的事情,但许多公司不赞成引入非标准可执行文件,但允许使用脚本。

这是我编写的几个混合实用程序:

  • REPL.BAT - 在标准输入上执行正则表达式搜索和替换并将结果写入标准输出
  • getTimestamp.bat - 日期和时间格式化程序和计算引擎

使用批处理的 ASCII 到十六进制转换器

这是我处理过的第一批项目之一。我成功地创建了CHARLIB.BAT - 一个包含 str2Hex 的纯批处理实用程序,该函数将字符串转换为表示 ASCII 码值的十六进制数字字符串。如果您点击链接,它将下载一个名为 CHARLIB.BAT.TXT 的文件 - 只需将文件重命名为 CHARLIB.BAT 即可使用。运行不带任何参数的脚本以获得有关如何使用它的帮助。

可以在http://www.dostips.com/forum/viewtopic.php?f=3&t=1733关注该实用程序的开发

这是一个简单的用法示例:

@echo off
setlocal
set "str=Hello world!"
call charlib str2hex str hex
echo str=%str%
echo hex=%hex%

-- 输出--

str=Hello world!
hex=48656C6C6F20776F726C6421

但是 CHARLIB.BAT 的脚本中嵌入了一些字符,这些字符不能很好地在此类网站上发布。

然后我在Batch macros to convert between ASCII code and character 创建了两个关键函数的宏版本。这有两个主要改进:

  • 它使用先进的批处理编程技术Batch "macros" with arguments 来显着提高性能

  • 它通过 WSF 使用嵌入式 VBScript 来生成查找图,以便现在可以在此类网站上发布代码。

下面是一个扩展版本,它添加了一个我在最初的 DosTips 帖子中没有的 @Str2Hex 宏:

charMacros.bat

<!-- : Begin batch script
@echo off
:: charMacros.bat
::
::   This script installs macros that can be used to interconvert between
::   numeric extended ASCII codes and character values.
::
::   The script defines the following variables:
::
::     @Str2Hex - A macro used to convert a string into a string of hex digit
::                pairs representing the ASCII codes in the string.
::
::     @asc - A macro used to convert a character into the decimal ASCII code
::
::     @ascHex - A macro used to convert a character into the hex ASCII codde
::
::     @chr - A macro used to convert a numeric ASCII code into a character
::
::     #LF - A variable containing a line feed character
::
::     #CR - A variable containing a carriage return character
::
::     #charMap - A variable used by the @asc macro
::
::     #asciiMap - A variable used by the @chr macro
::
::     #mapCodePage - The CHCP setting at the time the maps were loaded
::
::     \n - used for specifiying the end of line in a macro definition
::
:: Originally developed and posted by Dave Benham (with help from DosTips users) at
:: http://www.dostips.com/forum/viewtopic.php?f=3&t=4284

if "!" == "" >&2 echo ERROR: Delayed expansion must be disabled when loading %~nx0&exit /b 1

:: Define a Carriage Return string, only useable as !#CR!
for /f %%a in ('copy /Z "%~dpf0" nul') do set "#CR=%%a"

:: Define a Line Feed (newline) string (normally only used as !#LF!)
set #LF=^


:: Above 2 blank lines are required - do not remove

:: Define a newline with line continuation
set ^"\n=^^^%#LF%%#LF%^%#LF%%#LF%^^"

:: Define character maps used to interconvert between extended ASCII codes
:: and characters.
set "#charMap="
for /f "delims=" %%A in ('cscript //nologo "%~f0?.wsf"') do (
  if defined #charMap (set "#asciiMap=%%A") else set "#charMap= %%A"
)
for /f "delims=" %%A in ('chcp') do set "#mapCodePage=%%A"


:: %@Str2Hex%  StrVar  [RtnVar]
::
::   Converts the string within StrVar into a string of extended ASCII codes,
::   with each code represented as a pair of hexadecimal digits. The length of
::   the result will always be exactly twice the length of the original string.
::
::   Any character within the string that is not in the currently loaded code
::   page will be represented as 00.
::
::   The result is stored in RtnVar, or ECHOed if RtnVar is not specified.
::
::   The macro is safe to "call" regardless whether delayed expansion
::   is enabled or not.
::
::     StrVar = The name of a variable that contains the string
::              to be converted
::
::     RtnVar = The name of the variable used to store the result.
::
set @Str2Hex=for %%# in (1 2) do if %%#==2 (%\n%
for /f "eol= tokens=1,2 delims=, " %%a in ("!#args!") do (endlocal%\n%
  setlocal enableDelayedExpansion%\n%
  if defined %%~a (%\n%
    set "str=!%%~a!"%\n%
    set "s=!%%~a!"%\n%
    set "len=0"%\n%
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (%\n%
      if "!s:~%%P,1!" neq "" (%\n%
        set /a "len+=%%P"%\n%
        set "s=!s:~%%P!"%\n%
      )%\n%
    )%\n%
    set "rtn="%\n%
    for /l %%N in (0 1 !len!) do (%\n%
      set "chr=!str:~%%N,1!"%\n%
      set "hex="%\n%
      if "!chr!"=="=" set hex=3D%\n%
      if "!chr!"=="^!" set hex=21%\n%
      if "!chr!"=="!#lf!" set hex=0A%\n%
      if not defined hex for /f delims^^=^^ eol^^= %%c in ("!chr!!#CR!") do (%\n%
        set "test=!#asciiMap:*#%%c=!"%\n%
        if not "%%c"=="!test:~0,1!" set "test=!test:*#%%c=!"%\n%
        if "%%c"=="!test:~-0,1!" (set "hex=!test:~1,2!") else set "hex=00"%\n%
      )%\n%
      set "rtn=!rtn!!hex!"%\n%
    )%\n%
    for %%v in (!rtn!) do endlocal^&if "%%~b" neq "" (set "%%~b=%%v") else echo(%%v%\n%
  ) else endlocal%\n%
set "#args=")) else setlocal enableDelayedExpansion^&set #args=,


:: %@asc%  StrVar  Position  [RtnVar]
::
::   Converts a character into the extended ASCII code value.
::   The result is stored in RtnVar, or ECHOed if RtnVar is not specified.
::   A value of -1 is returned if the character is not in the currently loaded
::   code page. The macro is safe to "call" regardless whether delayed expansion
::   is enabled or not.
::
::     StrVar = The name of a variable that contains the character
::              to be converted
::
::     Position = The position of the character within the string
::                to be converted. 0 based.
::
::     RtnVar = The name of the variable used to store the result.
::
set @asc=for %%# in (1 2) do if %%#==2 (%\n%
for /f "eol= tokens=1-3 delims=, " %%a in ("!#args!") do (endlocal%\n%
  setlocal enableDelayedExpansion%\n%
  if defined %%~a (%\n%
    set "str=!%%~a!"%\n%
    set /a "n=%%~b" 2^>nul%\n%
    for %%N in (!n!) do set "chr=!str:~%%N,1!"%\n%
    if defined chr (%\n%
      set "rtn="%\n%
      if "!chr!"=="=" set rtn=61%\n%
      if "!chr!"=="^!" set rtn=33%\n%
      if "!chr!"=="!#lf!" set rtn=10%\n%
      if not defined rtn for /f delims^^=^^ eol^^= %%c in ("!chr!!#CR!") do (%\n%
        set "test=!#asciiMap:*#%%c=!"%\n%
        if not "%%c"=="!test:~0,1!" set "test=!test:*#%%c=!"%\n%
        if "%%c"=="!test:~-0,1!" (set /a "rtn=0x!test:~1,2!") else set "rtn=-1"%\n%
      )%\n%
    )%\n%
    for %%v in (!rtn!) do endlocal^&if "%%~c" neq "" (set "%%~c=%%v") else echo(%%v%\n%
  ) else endlocal%\n%
set "#args=")) else setlocal enableDelayedExpansion^&set #args=,


:: %@chr%  AsciiCode  [RtnVar]
::
::   Converts an extended ASCII code into the corresponding character.
::   The result is stored in RtnVar, or ECHOed if RtnVar is not specified.
::   The macro supports value 1 - 255. The value 0 is not supported.
::   The macro is safe to "call" regardless whether delayed expansion is
::   enabled or not.
::
::     AsciiCode - Any value from 1 to 255. The value can be expressed as any
::                 numeric expression supported by SET /A.
::
::     RtnVar - The name of the variable used to store the result
::
set @chr=for %%# in (1 2) do if %%#==2 (%\n%
for /f "eol= tokens=1,2 delims=, " %%a in ("!#args!") do (endlocal%\n%
  setlocal%\n%
  set "NotDelayed=!"%\n%
  setlocal EnableDelayedExpansion%\n%
  set "n=0"%\n%
  set /a "n=%%~a"%\n%
  if !n! gtr 255 set "n=0"%\n%
  if !n! gtr 0 (%\n%
    if !n! equ 10 (%\n%
      for %%C in ("!#LF!") do (%\n%
        endlocal^&endlocal%\n%
        if "%%~b" neq "" (set "%%~b=%%~C") else echo(%%~C%\n%
      )%\n%
    ) else (%\n%
      for %%N in (!n!) do set "c=!#charMap:~%%N,1!"%\n%
      if "!c!" equ "^!" if not defined NotDelayed set "c=^^^!"%\n%
      for /f delims^^=^^ eol^^= %%C in ("!c!!#CR!") do (%\n%
        endlocal^&endlocal%\n%
        if "%%~b" neq "" (set "%%~b=%%C") else echo(%%C%\n%
      )%\n%
    )%\n%
  ) else endlocal^&endlocal%\n%
set "#args=")) else setlocal enableDelayedExpansion^&set #args=,


:: %@ascHex%  StrVar  Position  [RtnVar]
::
::   Converts a character into the extended ASCII code hex value.
::   The result is stored in RtnVar, or ECHOed if RtnVar is not specified.
::   A value of -1 is returned if the character is not in the currently loaded
::   code page. The macro is safe to "call" regardless whether delayed expansion
::   is enabled or not.
::
::     StrVar = The name of a variable that contains the character
::              to be converted
::
::     Position = The position of the character within the string
::                to be converted. 0 based.
::
::     RtnVar = The name of the variable used to store the result.
::
set @ascHex=for %%# in (1 2) do if %%#==2 (%\n%
for /f "eol= tokens=1-3 delims=, " %%a in ("!#args!") do (endlocal%\n%
  setlocal enableDelayedExpansion%\n%
  if defined %%~a (%\n%
    set "str=!%%~a!"%\n%
    set /a "n=%%~b" 2^>nul%\n%
    for %%N in (!n!) do set "chr=!str:~%%N,1!"%\n%
    if defined chr (%\n%
      set "rtn="%\n%
      if "!chr!"=="=" set rtn=3D%\n%
      if "!chr!"=="^!" set rtn=21%\n%
      if "!chr!"=="!#lf!" set rtn=0A%\n%
      if not defined rtn for /f delims^^=^^ eol^^= %%c in ("!chr!!#CR!") do (%\n%
        set "test=!#asciiMap:*#%%c=!"%\n%
        if not "%%c"=="!test:~0,1!" set "test=!test:*#%%c=!"%\n%
        if "%%c"=="!test:~-0,1!" (set "rtn=!test:~1,2!") else set "rtn=-1"%\n%
      )%\n%
    )%\n%
    for %%v in (!rtn!) do endlocal^&if "%%~c" neq "" (set "%%~c=%%v") else echo(%%v%\n%
  ) else endlocal%\n%
set "#args=")) else setlocal enableDelayedExpansion^&set #args=,


exit /b 0


----- Begin wsf script --->
<job><script language="VBScript">
for i=1 to 255
  if i=10 then WScript.Stdout.Write " " else WScript.Stdout.Write chr(i)
next
WScript.Stdout.Write chr(10)+"#"
for i=1 to 255
  if i<>10 then WScript.Stdout.Write chr(i)+chr(i)+right("0"+hex(i),2)+"#"
next
</script></job>

charMacros 被设计为“终止并保持驻留”,这意味着它们只需要加载一次,然后任意数量的批处理脚本都可以利用它们。

这里有一个简单的例子来说明如何使用@Str2Hex:

@echo off
:: Load the charMacros if not already loaded. The macros are dependent on
:: the active code page, so if it has changed, then the macros are reloaded.
:: The macros are loaded prior to SETLOCAL so that the macros persist after
:: the script terminates
for /f "delims=" %%A in ('chcp') do if "%%A" neq "%#mapCodePage%" call charMacros

:: Test the Str2Hex macro
setlocal
set "str=Hello world!"
%@Str2Hex% str hex
echo str=%str%
echo hex=%hex%

-- 输出--

str=Hello world!
hex=48656C6C6F20776F726C6421

【讨论】:

  • 哇!这真是太棒了!最初我正在寻找类似的东西,但一无所获。那是我开始探索其他选择的时候......太棒了
猜你喜欢
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 2011-08-09
  • 1970-01-01
  • 2012-03-01
  • 2018-08-30
相关资源
最近更新 更多