Wednesday, September 18, 2013

Powershell - converting array output into string (OpenSSL ...)

In my specific example, I was trying to get OpenSSL output to show up as a string in the least amount of typing (this is for a class I'll be teaching), meaning each student would have to read the slide, and type what's on it. Meaning that each extra bracket of code students type, could result in some unpredictable disaster which would stop the whole class from moving forward. So, I wanted to come up with the most elegant way possible.

PS\> openssl rand -base64 512

But what you really want is a string... The reason is, in Chef the data_bag object can be encrypted. So user names, password, data base keys are all safe and sound behind OpenSSL (pun retroactively intended). However, decrypt takes a string, and Powershell generates an array. So, I needed to convert array to string in powershell in the most elegant way possible.

I am not* going to bore you with the many failed attempts, so here is the best answer I came up with*:

PS\> -join $(openssl rand -base64 512)

Yup. That's it.

A really neat side effect, is that in every class I have a few people tell me this "join" is awesome and they had no idea it was possible.  This is why I dig what I do now.

* I didn't actually come up with the -join by itself, this dude here did:

I lied about not boring you... here are the various semi-failed attempts:

  •     [string]$(openssl rand -base64 512) -replace " ",""
  •     openssl rand -base64 512 | %{write-host $_ -NoNewline}
  •     Write-Host -Object $(openssl rand -base64 512) -Separator ""
  •     openssl rand -base64 512 | %{[string]$a+=$_}
  •     $result = $result -replace "`t|`n|`r",""
  •     ...this one is cool, but makes changes to $ofs:
              $ofs="";[string]$(openssl rand -base64 512)

No comments:

Post a Comment

Comments are welcomed and appreciated.