My goal is to save and use the result of a PowerShell command in a variable in the batch script. The PowerShell comand is:
-join ((1..12) | %{ '{0:X}' -f (Get-Random -Max 16) })
or
(1..12 | %{ '{0:X}' -f (Get-Random -Max 16) }) -join ''
I've several examples that use the FOR...DO statement. But I don't know why all of them can't make my goal work:
@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
Can you please advise me what to do?.
CodePudding user response:
You can also use and replace %
by ForEach-Object
alias ForEach
from PowerShell Command :
@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