![](/img/trans.png)
[英]Save the output of a powershell command in a variable and use it in batch script?
[英]PowerShell Output into Batch Variable
我的目標是在批處理腳本的變量中保存和使用 PowerShell 命令的結果。 PowerShell 命令是:
-join ((1..12) | %{ '{0:X}' -f (Get-Random -Max 16) })
要么
(1..12 | %{ '{0:X}' -f (Get-Random -Max 16) }) -join ''
我有幾個使用 FOR...DO 語句的示例。 但我不知道為什么所有這些都不能使我的目標實現:
@echo off
1st try : for /f "tokens=* delims= " %%a in ('powershell -Executionpolicy Bypass -Command "-join ((1..12) | %{ '{0:X}' -f (Get-Random -Max 16) })" ') do set "var=%%a"
2nd try : for /f "delims=" %%a in (' powershell "-join ((1..12) | %{ '{0:X}' -f (Get-Random -Max 16) })" ') do set "var=%%a"
3rd try : for /f "tokens=*" %%a in ('powershell /command "(1..12 | %{ '{0:X}' -f (Get-Random -Max 16) }) -join ''"') do set var=%%a
4th try : for /f "delims=" %%a in (' powershell /command "(1..12 | %{ '{0:X}' -f (Get-Random -Max 16) }) -join ''" ') do set "var=%%a"
echo %var%
pause
你能告訴我該怎么做嗎?
您還可以使用和替換%
by ForEach-Object
alias ForEach
from PowerShell 命令:
@echo off
Title Get Variable Value from Powershell Scipt with a Batch file
Set PsCommand="-join ((1..12) | ForEach { '{0:X}' -f (Get-Random -Max 16) })"
@for /f "delims=" %%a in ('Powershell -C %PsCommand%') do Set "Var=%%a"
echo My Variable Value from Powershell script is : [%Var%]
Pause
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.