如何使用批处理命令从文本文件中删除CRLF和换行

问题描述

目标是使用批处理脚本执行以下操作:

  1. 从Windows计算机中提取主机名。
  2. 在主机名值上应用sha256哈希(从步骤1获得)。

我的系统的主机名是: W0000000000ZQ

我的批处理脚本如下:

@echo off
hostname>hostname.txt
CertUtil -hashfile hostname.txt SHA256 //<- this is generating wrong sha256 string because
                                       //   the above generated file contains CRLF and a new line
                                       //   screenshot of this file provided below.
CertUtil -hashfile hostname-manual.txt SHA256 //<- this is generating correct sha256 string because
                                              //   i manually created this file and pasted hostname
                                              //   only (W0000000000ZQ) without CRLF and new line.
                                              //   screenshot of this file provided below.

hostname.txt:

enter image description here

hostname-manual.txt

enter image description here

脚本的输出

enter image description here

能否请您建议如何从“ hostname.txt”中删除CRLF和换行符,以便Certutil选择正确的字符串以生成sha256值。

解决方法

以下内容将主机名保存到文件中,且不包含尾随CRLF。

for /f %%h in ('hostname') do (>hostname.txt <nul set /p unused=%%h)