在 Windows 批处理文件中的多个命令中使用 powershell 变量

Using a powershell variable in multiple commands within a Windows batch file

在 Windows 7 批处理文件中,我可以调用 powershell v2 创建一个字符串,然后将该字符串分配给一个批处理文件变量,以便稍后在另一个命令中使用,如下所示:

for /f "delims=" %%a in ('powershell -noninteractive -NoProfile -Command "Get-Date -format 'yyyy-MM-dd HH_mm_ss'"') do set "datetime=%%a"
rem process file1.txt here
ren file1.txt "newname %datetime%.txt"

如果我尝试以更简单的方式做同样的事情(在批处理文件中),它不起作用:

编者注:事实证明它 确实 有效 - 内部 " 实例正确转义为 \".

powershell -noninteractive -NoProfile -Command "$datetime_string = Get-Date -format 'yyyy-MM-dd HH_mm_ss'; (gc file1.txt) -join [char]10 | Out-File -Encoding Ascii \"newname $datetime_string.txt\""

你能帮忙吗?

如果内部双引号有问题,您可以简单地避免它们:

powershell -NonI -NoP -Com  "$DT=Get-Date -format 'yyyy-MM-dd HH_mm_ss';(gc file1.txt) -join [char]10|Out-File ('newname '+$DT+'.txt') -Enc Ascii"

为简洁起见,参数和变量名称尽可能缩短。