我想在批處理腳本中也能在 PowerShell CLI 中實作我可以做的事情:
PS C:\Users\andreas.luckert> $timestamp = Get-Date -UFormat "%d-%m-%Y--%R-UTC%Z" | ForEach-Object { $_ -replace ":", "." }
PS C:\Users\andreas.luckert> echo $timestamp
26-11-2021--15.55-UTC 01
現在,在我的批處理腳本中,我嘗試了類似于以下的方法
SET _timestamp=('Get-Date -UFormat "%d-%m-%Y--%R-UTC%Z" | ForEach-Object { $_ -replace ":", "." }')
然而,它不起作用。
像這樣的解決方案對我來說看起來有點 hacky,批處理變數的一般說明在這種情況下沒有幫助,與我在開頭提到的漂亮干凈的 PowerShell 命令相比,所有這些方法在語法方面都非常丑陋。此外,它們都不包括時區,這對我來說很重要。
uj5u.com熱心網友回復:
您需要呼叫
powershell.exeWindows PowerShell 的CLI才能從批處理檔案中執行PowerShell命令- 請注意,此類呼叫的成本很高。- 或者,要使用按需安裝的跨平臺PowerShell (Core) 7 版本,請呼叫
pwsh.exe
- 或者,要使用按需安裝的跨平臺PowerShell (Core) 7 版本,請呼叫
您需要通過
for /f批處理檔案中的回圈來決議輸出;for /?從cmd.exe會話中運行尋求幫助(命令提示符)。您需要將批處理檔案應逐字處理的字符加倍 。
%
把它們放在一起:
@echo off
for /f "usebackq delims=" %%i in (`
powershell -c "(Get-Date -UFormat '%%d-%%m-%%Y--%%R-UTC%%Z') -replace ':', '.'"
`) do set _timestamp=%%i
echo %_timestamp%
注意:考慮放置-noprofilebefore-c以抑制加載 PowerShell 的組態檔,以獲得更好的性能和可預測的執行環境。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369565.html
