I need to use the Powershell command below and set the output number as a variable using command prompt (batch)
Powershell Command:
( (1..6) | ForEach-Object { Get-Random -Minimum 0 -Maximum 9 } ) -join {}
Batch Code:
set "genCode=Powershell -Command "( (1..6) | ForEach-Object { Get-Random -Minimum 0 -Maximum 9 } ) -join {}""
echo %genCode%
I know the Powershell command works in cmd since I've tested it. However, when I use the command in a variable, it terminates the script and gives an error.
CodePudding user response:
Solution:
for /F "delims=" %%c in (' powershell "( (1..6) | ForEach-Object { Get-Random -Minimum 0 -Maximum 9 } ) -join {}" ') do set "genCode=%%c"
CodePudding user response:
Looks like ColDog5044 beat me to the use of the FOR command, but for the sake of speed, I would recommend using the -NoProfile parameter.
This code comes in 2 halves. The first half is fully batch, and the second half will produce upto 16 random digits - simply change $DigitCount = 16
to the desired amount.
@ECHO OFF
SET "Rand1=000%RANDOM%"
SET "Rand2=000%RANDOM%"
SET "genCode=%Rand1:~-3%%Rand2:~-3%"
ECHO [%genCode%]
FOR /F "USEBACKQ DELIMS=" %%C IN (`PowerShell -NonInteractive -NoProfile -Command "$DigitCount = 16; $RandString = [string](Get-Random -Minimum 100000000000000000 -Maximum 1000000000000000000); Write-Host $($RandString.Substring($RandString.Length-($DigitCount 1),$DigitCount)) -NoNewline"`) DO SET "genPSCode=%%C"
ECHO [%genPSCode%]