簡體   English   中英

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

為了簡潔起見,請盡可能縮短參數名和變量名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM