powershellreplaceunicodestring-conversionunicode-literals

Powershell force convert the ConvertFrom-Json output to string which can then be used in all string operations incl. filenaming


As I have mentioned in the Question title, I want to convert the ConvertFrom-Json command's output to string such that, the character/string I get, should be usable such that it can be inserted into DateTime string as replacement to another character.

Currently I have following code to get the present DateTime:

$DTCurr = (Get-Date).tostring("dd-MM-yyyy_hh+mm+ss")

Now in the above code, I want to force replace the plus sign with colon sign, such that the resulting DateTime string can be used in the file-naming, so I am expecting the output(after replacement) like below:

07-11-2020_12:59:13

Now I tried this code for that forced replacement, but it doesn't work:

$colon = ('{ "str": "\uA789" }' | ConvertFrom-Json)
$DTCurr = (Get-Date).tostring("dd-MM-yyyy_hh+mm+ss")
$DTCurr = $DTCurr -replace "\+",$colon
Echo $DTCurr

This gives the output: 07-11-2020_02@{str=꞉}06@{str=꞉}28 which is ridiculous and unexpected. I can assure that $colon does print : when passed to Echo.

Can someone let me know what I doing wrong and help out achieve this ?


Solution

  • Sorry if I'm misconstruing this, but I think your end goal can be simplified by doing this

    $DTCurr = (Get-Date).tostring("dd-MM-yyyy_hh:mm:ss")
    

    or this

    $DTCurr = (Get-Date).tostring("dd-MM-yyyy_hh+mm+ss")
    $colonDT = $DTCurr -replace "\+",":"
    

    but if you wanna do it your way, the reason why it's printing that output, is because it's doing exactly what you're telling it to do. You're replacing the + with an object that has a property named str with a value of :. You would need to do this instead

    $colon = ('{ "str": "\uA789" }' | ConvertFrom-Json)
    $DTCurr = (Get-Date).tostring("dd-MM-yyyy_hh+mm+ss")
    $colonDT = $DTCurr -replace "\+",$colon.str
    Echo $colonDT
    

    If I am incorrect, and you need more assistance, let me know.