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

标签 windows powershell batch-file powershell-2.0 filenames

在 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/

相关文章:

powershell - 将JSON文件上传到Web API

Windows Powershell 策略执行绕过

javascript - 如何在Windows 10上启动Edge with Open程序包

JAVA_HOME 未指向 JDK

azure - 使用 Azure 自动化帐户,将文件从一个文件共享跨存储复制到另一个文件共享

Powershell Copy-Item 远程计算机复制到错误位置

email - 发送电子邮件的批处理脚本

BAT文件中的SQLCMD实用程序-如何在语法错误的情况下返回ERRORLEVEL

java - JNI 中的 JVM-Crash 调用 ReleaseStringUTFChars,仅在 Windows 7、Windows XP 上正常

windows - Composer 不工作