如何从 powershell 命令设置环境变量?

Tim*_*Tim 5 powershell command-line

我想在 cmd.exe 中有一个包含星期几的环境变量。

当我运行这个命令时,我得到了我想要的结果。

C:\Users\tisc>powershell (get-date).dayofweek
Friday
Run Code Online (Sandbox Code Playgroud)

在这里,我试图将结果存储在环境变量中。

C:\Users\tisc>set dow = powershell (get-date).dayofweek
Run Code Online (Sandbox Code Playgroud)

但是当我试图得到它时,我没有得到我想要的字符串。

C:\Users\tisc>set dow
DoW=0
dow = powershell (get-date).dayofweek
Run Code Online (Sandbox Code Playgroud)

我的目标是将批处理文件中的变量用于某些备份脚本。

Ryn*_*ant 3

要在没有临时文件的情况下执行此操作,您可以执行以下操作:

@ECHO off
FOR /F %%i in ('powershell.exe -noprofile "(get-date).DayOfWeek"') DO SET dow=%%i
ECHO Day of week %dow%
PAUSE
Run Code Online (Sandbox Code Playgroud)

从命令提示符删除双%%:

FOR /F %i in ('powershell.exe -noprofile "(get-date).DayOfWeek"') DO SET dow=%i
Run Code Online (Sandbox Code Playgroud)

-noprofile如果您为 PowerShell 设置了配置文件,则使用它会使其运行得更快。