PowerShell을 사용하여 ASCII에서 16 진수로의 변환기를 일괄 적으로 생성하려면 어떻게해야합니까?

제레미 롤러

저는 스크립트를 일괄 적으로 작성하는 데 상당히 익숙하며 ASCII를 16 진수로 변환하는 효과적인 방법을 찾고 있습니다. 온라인에서 몇 가지 튜토리얼을 검색해 보았지만 내가 찾은 유일한 것은 Perl이나 다른 스크립팅 언어를 사용하는 것뿐이었습니다.

그래서 내 진짜 질문은 배치 파일 내에서 어떤 언어를 사용할 수 있습니까? 표준 언어는 무엇입니까? 무엇이 호환됩니까? 저는 제가 스크립팅 책이나 스크립팅 수업에 정말로 투자해야한다는 것을 압니다.하지만 이것은 제가 여기 제 회사에서 일하고있는 많은 부수 프로젝트 중 하나였으며 전문가가 될 시간이 많지 않았습니다. 제공 할 수있는 모든 정보에 미리 감사 드리며 혼란을 해결하도록 도와주세요 !!

편집하다

좋습니다. VBscript, Jscript 또는 powershell과 같은 지원 스크립팅 도구 중 하나를 사용하는 것이 가장 좋은 방법 인 것 같습니다. 누구든지 내 상황에 가장 적합한 접근 방식을 알고 있습니까?

기본적으로 "BL6A-19T508-NYL"과 같은 부품 번호를 묻는 것으로 시작해야합니다. 이것으로 할 수 있습니다.

SET / p "str1 = 부품 번호 입력"

하지만 거기에서 어떤 스크립팅 지원 도구를 사용해야합니까? 입력 한 변수를 사용하려면 어떻게 구현해야합니까?

거기에서 나는 아마도 Hex를 같은 변수로 다시 출력해야합니다. 제 경우에는 16 진수 값 사이에 공백이없는 것이 좋습니다. 그래서 부품 번호 BL6A-19T508-NY를 424c36412d3139543530382d4e59로 변환하고 싶습니다.

나는 내가 어떻게 할 수 있는지 정말로 이해하지 못한다.

ascii에서 16 진수로 변환 할 때이 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

부품 번호를 입력하고 어떤 일이 발생하는지보기 위해 일시 ​​중지를 추가했습니다. 그것이하는 일은

코드 출력의 스크린 샷입니다.

잘 안되네요 ...

그래서 첫 번째 단계는 변환기가 제대로 작동하도록하는 것입니다. 그리고 거기에서 변수에서 작업하고 마지막으로 16 진수 값을 다시 변수 또는 새 변수에 배치합니다.

나는 계속해서 노력할 것입니다. 누군가 내가 할 수있는 일을 보거나 내가 잘못하고있는 일을 본다면 대단히 감사하겠습니다. 모두 감사합니다!!

드 벤햄

참고-PowerShell을 요청하도록 편집하기 전에 질문에서 배치 솔루션을 요청했을 때이 답변에 대한 작업을 시작했습니다.

이것은 내 마음에 가깝고 소중한 주제입니다. (사실 많은 과목)

배치 내에 다른 스크립팅 언어 포함

많은 스크립팅 언어를 일괄 적으로 포함하는 좋은 전략이 있습니다. cmd / bat의 js / vbs / html / hta hybrids 및 chimeras를 참조하십시오 .

일반적으로 하이브리드 코드를 만드는 것은 좋지 않다고 생각합니다. Batch는 기능이 매우 제한적입니다. 다른 언어를 포함하는 하이브리드 배치 스크립트를 작성할 수 있다면 다른 스크립팅 언어를 사용하여 전체 솔루션을 작성하는 것이 더 쉽고 효율적일 가능성이 높습니다.

그러나 배치의 일부 한계를 해결하는 독립형 하이브리드 배치 유틸리티를 만드는 것이 합리적이라고 생각합니다. 이러한 유틸리티는 일괄 작업을 계속하려는 모든 사용자를 위해 일괄 언어를 효과적으로 확장하는 데 사용할 수 있습니다. 확실히 제 3 자 실행 파일도 같은 일을 할 수 있지만, 많은 회사들이 비표준 실행 파일을 도입하는 것에 눈살을 찌푸 리지만 스크립트는 허용합니다.

내가 작성한 몇 가지 하이브리드 유틸리티는 다음과 같습니다.

  • REPL.BAT- 정규식 검색을 수행하고 stdin에서 대체하고 결과를 stdout에 씁니다.
  • getTimestamp.bat- 날짜 및 시간 포맷터 및 계산 엔진

배치를 사용하는 ASCII에서 16 진 변환기

이것은 내가 다룬 첫 번째 일괄 프로젝트 중 하나였습니다. 문자열을 ASCII 코드 값을 나타내는 16 진수 문자열로 변환하는 함수 인 str2Hex를 포함하는 순수 배치 유틸리티 인 CHARLIB.BAT 를 만드는 데 성공했습니다 . 링크를 따라 가면 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에는 이와 같은 사이트에 잘 게시되지 않는 문자가 스크립트 내에 포함되어 있습니다.

그런 다음 배치 매크로 에서 두 가지 주요 기능의 매크로 버전을 만들어 ASCII 코드와 문자 사이를 변환했습니다 . 여기에는 두 가지 주요 개선 사항이 있습니다.

  • 고급 배치 프로그래밍 기술인 배치 "매크로"와 인수 를 사용하여 성능을 크게 향상시킵니다.

  • 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

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관