powershell - 如何在 cmd 中设置一个变量,它是来自 powershell 命令结果的字符串?
问题描述
我想将 powershell 命令的结果存储在 cmd 变量中作为 String : powershell -com "(ls | select -Last 1).FullName"
。这个怎么做?
解决方案
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.
推荐阅读
- jenkins - Jenkins 启动时安装插件失败
- python - Python selenium循环打开页面
- java - 如何从内部停止线程?
- node.js - 如何通知用户 NPM 包版本更新?
- ruby-on-rails - 为什么工头完成后ruby进程继续存在?
- oauth-2.0 - Freshdesk OAuth SSO:Freshdesk 登录页面不 Ping 我的身份验证页面?
- mysql - 如何构建内部查询以查找趋势前 3
- c++ - 如何将 printf 输出转换为 char 数组?
- clickhouse - 无法启动 ClickHouse。退出代码 203
- django - 如何使用 router.register 参数化 django url?