首页 > 解决方案 > 如何在 cmd 中设置一个变量,它是来自 powershell 命令结果的字符串?

问题描述

我想将 powershell 命令的结果存储在 cmd 变量中作为 String : powershell -com "(ls | select -Last 1).FullName"。这个怎么做?

标签: powershellcmd

解决方案


CMD does not have a straightforward way of assigning command output to a variable. If the command produces just a single line you could use a for loop

for /f "delims=" %a in ('some_command /to /run') do @set "var=%a"

However, if the command produces multiple lines that will capture only the last line. A better approach would be redirecting the output of the command to a file and then reading that file into a variable:

set "tempfile=C:\temp\out.txt"
>"%tempfile%" some_command /to /run
set /p var=<"%tempfile%"
del /q "%tempfile%"

If you literally need only the last file in a directory you don't need to run PowerShell, though. That much CMD can do by itself:

for /f "delims=" %f in ('dir /a-d /b') do @set "var=%~ff"

Beware that you need to double the % characters when running this from a batch file.


推荐阅读