1

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?.

2
  • 2
    In a batch file, the percent, (%), character is special, and needs escaping. The escape method for that character is another percent character. Example: @For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "-join ((1..12) | %%{ '{0:X}' -f (Get-Random -Max 16) })" 2^>NUL') Do @Set "var=%%G". Commented Dec 31, 2022 at 2:14
  • Time to switch to powershell scripts. Commented Dec 31, 2022 at 14:11

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.