Home > Mobile >  Trying to generate an alphanumeric hex code in powershell
Trying to generate an alphanumeric hex code in powershell

Time:02-02

I'm trying to generate an image based on a 6 char hex code (color code) that's being generated in powershell, but I'm getting an error for System.String when I add the non-digit characters, script is as follows:

# Generate random hex code for the background color
$backgroundColor = "#"   [System.String]::Join("", (Get-Random -Count 6 -InputObject (0..9   "a".."f") | ForEach-Object { $_ }))

# Generate random hex code for the text color
$textColor = "#"   [System.String]::Join("", (Get-Random -Count 6 -InputObject (0..9   "a".."f") | ForEach-Object { $_ }))

The error I'm receiving is this:

Cannot convert value "a" to type "System.Int32". Error: "Input string was not in a correct format."
At line:5 char:1
  $backgroundColor = "#"   [System.String]::Join("", (Get-Random -Count ...
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidArgument: (:) [], RuntimeException
      FullyQualifiedErrorId : InvalidCastFromStringToInteger

When I remove the "a".."f" portion, it generates a 6 digit hex just fine, but I need to have the alphas as well for the full spectrum, not sure how to include those characters in these snippits.

Any advice would be greatly appreciated.

I've really only tried removing the alphas to test the rest of the script which works fine, but only generates a code with the integers 0-9 which works, but isn't desired.

CodePudding user response:

Your code as is will succeed in rangeop

To overcome this you can change your logic a bit so it is compatible with both versions:

$map = [char] '0'..[char] '9'   [char] 'a'..[char] 'f'
'#'   [string]::new((Get-Random -Count 6 -InputObject $map))

CodePudding user response:

Use [char[]]"0123456789ABCDEFG" instead of 0..9 "a".."f".

$backgroundColor = "#"   [System.String]::Join("", (Get-Random -Count 6 -InputObject ([char[]]"0123456789ABCDEFG") | ForEach-Object { $_ }))

$textColor = "#"   [System.String]::Join("", (Get-Random -Count 6 -InputObject ([char[]]"0123456789ABCDEFG") | ForEach-Object { $_ }))

CodePudding user response:

To work in powershell 5.1:

"#"   [System.String]::Join("", (Get-Random -Count 6 -InputObject (0..9   
  [char[]](97..102))))

#d1b5a8
  • Related