在 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"
为简洁起见,参数和变量名称尽可能缩短。
关于windows - 在 Windows 批处理文件中的多个命令中使用 powershell 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640288/