【问题标题】:Difference between PowerShell's echo and CMD's echoPowerShell 的 echo 和 CMD 的 echo 的区别
【发布时间】:2020-04-11 07:35:18
【问题描述】:

我在 PowerShell 中得到以下信息:

D:\> echo "Apple Pie" | git hash-object --stdin
157cb7be4778a9cfad23b6fb514e364522167053

D:\> "Apple Pie" | git hash-object --stdin
157cb7be4778a9cfad23b6fb514e364522167053

但在 CMD.exe 中:

C:\>echo "Apple Pie" | git hash-object --stdin
bb3918d5053fea31fc9a58fae1e5bdeabe3ec647

在 PluralSight 视频中,我看到了与 Mac 控制台不同的价值:

在每种情况下,从echo 传输的确切值是多少?

如果我转到其中一个在线 SHA1 生成器并输入字符串 Apple Pie,我会得到不同的哈希值。从我得到的:

8d69b7365f59237d3fb052c1f2f15ea33457fe51

【问题讨论】:

  • cmd.exe内部命令 ECHO 还输出双引号和留给重定向运算符 | 的空格字符。我想没有测试,因为没有安装git,散列将与PowerShell中使用echo Apple Pie| git hash-object --stdin创建字符串Apple Pie的散列相同。如果它仍然不同于 cmd 命令,ECHO 还会在字符串 Apple Pie 之后输出换行符。
  • 你是对的! echo Apple Pie|git hash-object --stdin 产生 157cb7b..,与 PowerShell 'echo "Apple Pie"` 相同。
  • 而 Powershell echo '"Apple Pie" ' | git hash-object --stdin 产生 bb39...,与 CMD echo "Apple Pie" | ... 相同。
  • echo "Apple Pie" | where {$_length -eq 9} 表示该字符串没有添加CRLF,但如果重定向到文件,则有CRLF

标签: powershell cmd hash sha1 git-hash


【解决方案1】:

据我所知:

使用 CMD :

echo Apple Pie|git hash-object --stdin

在 PowerShell 中返回与以下相同的想法

"Apple Pie" | git hash-object --stdin

也就是说:

157cb7be4778a9cfad23b6fb514e364522167053

@Mofi 似乎是对的,您可以使用以下命令在 Powershell 中重现 CMD 结果:

'"Apple Pie" ' | git hash-object --stdin

解释 Mac OS 之一:要获得 157cb7be4778a9cfad23b6fb514e364522167053,经过哈希处理的真正字符列表是 'Apple Pie\r\n'(带有回车换行符),在 Mac 或 linux 之类的命令行中是 'Apple Pie\r'

如果您想对此进行测试:将'Apple Pie' 放入带有回车符的文本文件中,并将其保存为Windows 文本样式(CR+LF),然后使用git hash-object yourfile.txt。然后将其保存为 Linux 风格(LF)并再次测试,您将找到您的两个哈希。


关于\r\n的部分。

"Apple Pie" | where {$_.length -eq 9} 显示字符串正好是 9 个字符长

对我来说,这是因为在您的情况下,管道位于两个 PowerShell 部分之间,管道传输一个对象。当管道位于 PowerShell 和外部 EXE 之间时,将添加 \r\n。这是一种使用 C# 编写的小型 exe 文件进行测试的方法:

using System;
namespace C_Param
{
  class Program
  {
    static void Main(string[] args)
    {
      string line = Console.In.ReadToEnd();
      foreach (char character in line){
        Console.WriteLine(String.Format("{0:X2}", Convert.ToByte(character)));
      }
    }
  }
}

PowerShell 控制台中的结果是:

"Apple Pie" | .\C_Param.exe
41
70
70
6C
65
20
50
69
65
0D
0A

CMD 控制台中的结果是:

echo "Apple Pie" | .\C_Param.exe
22
41
70
70
6C
65
20
50
69
65
22
20
0D
0A

QED ?

【讨论】:

  • 是的,我现在清楚了,除了关于\r\n 的部分。 "Apple Pie" | where {$_.length -eq 9} 表明字符串正好是 9 个字符长。
  • 我添加一个解释。
猜你喜欢
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 2020-04-25
  • 1970-01-01
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多