令人尴尬的错误出现在 .bat 文件中,而不是在 CMD 中

An embarrassing error appears in a .bat file and not in CMD

我实际上正在开发“Computer Info Dumper”,我需要获取 ram 名称 + 容量,问题是使它生效的行:它在 CMD 中有效,但在 .bat 文件中无效.

这里是'command':powershell -command "GWmi CIM_PhysicalMemory|%{\"\"+ ([int]$_.banklabel.Replace('BANK ','') + 1) + \") \" + ($_.capacity/1GB)+\"GB from \"+($_.manufacturer)}"

在 CMD 中,它给了我想要的结果:

8GB from Corsair
4GB from Kingston
8GB from Corsair
4GB from Kingston

但是在 .bat 文件中,它给了我这个错误:(它将被翻译,因为它是法语,所以翻译不会完美)

To character Line:1 : 25

+ ... sicalMemory|{""+ ([int]$_.banklabel.Replace('BANK ','') + 1) + ") " + ...

Expressions are only allowed as the first element of a pipeline.

+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException

+ FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline

谁能帮我解决这个问题?

应要求,我的评论作为回答:

中,% 字符具有特殊含义,因此文字字符需要转义。百分号的转义字符是另一个,即 %%.

@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -Command "Get-CimInstance CIM_PhysicalMemory | %% { \"\" + ([Int]$_.BankLabel.Replace('BANK ','') + 1) + \") \" + ($_.Capacity / 1GB) + \"GiB from \" + ($_.Manufacturer) }"

或者最好不要在 中使用 ForEach-Object% 别名,这样您就可以将命令提示符代码与您的脚本相匹配。

@%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -Command "Get-CimInstance CIM_PhysicalMemory | ForEach-Object { \"\" + ([Int]$_.BankLabel.Replace('BANK ','') + 1) + \") \" + ($_.Capacity / 1GB) + \"GiB from \" + ($_.Manufacturer) }"

您会看到我更正确地将 Capacity 单位分配为 GiB,并且我已将 Get-WmiObjectGWmi 别名替换为推荐的PowerShell v3.0+ 替代 Get-CimInstance, (别名 gcim).