jsonpowershellpasswords

Import single line from text file into json file


I have a really simple question which I am sure someone can answer really quickly for me.

I have one text file (password.txt) containing a random string of characters which has been generated by a Poweshell script to be used as a wifi password.

I have another script (change-password.ps1) which logs into my router and changes the password. I have managed to get this script to look at a json file (config.json) and use one of static passphrases.

This is my json file

{ "PSKs": {
            "01":"PSKforJanuary123!!",
            "02":"PSKforFebruary123!",
            "03":"PSKforMarch123!",
            "04":"PSKforApril123!",
            "05":"PSKforMay123!",
            "06":"PSKforJune123!",
            "07":"PSKforJuly123!",
            "08":"PSKforAugust123!",
            "09":"PSKforSeptember123!",
            "10":"PSKforOctober123!",
            "11":"PSKforNovember123!",
            "12":"PSKforDecember123!"
        }
    }

So instead of using one of these from the list above, how can I replace the "PSKfor***123!" with the line of text from my password.txt?

Or is there a way I can create this random string of characters within my json file without having to run another script to generate it?

Thanks in advance!


Solution

  • How to update all properties in the Json using a password stored in a file:

    $json = Get-Content path\to\json.txt -Raw | ConvertFrom-Json
    $pass = Get-Content path\to\password.txt
    $json.PSKs.PSObject.Properties | ForEach-Object { $_.Value = $pass }
    $json | ConvertTo-Json | Set-Content path\to\json.txt
    

    How to update a single property in the Json using a password stored in a file, say for example, to dynamically update the property that corresponds with the current month:

    $json = Get-Content path\to\json.txt -Raw | ConvertFrom-Json
    $pass = Get-Content path\to\password.txt
    $month = [datetime]::Now.ToString('MM')
    # `$json.PSKs.$month` would work too here
    $json.PSKs.PSObject.Properties[$month].Value = $pass
    $json | ConvertTo-Json | Set-Content path\to\json.txt
    

    How to update all properties using a randomly generated password, for this you will need to figure out what logic you want to use to generate a random password. A very easy way is via RandomNumberGenerator.GetString(ReadOnlySpan<Char>, Int32) Method but this method only works in PowerShell 7.

    # `$chars` can be whatever you like, this is just an example
    $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&_-+='.ToCharArray()
    $json = Get-Content path\to\json.txt -Raw | ConvertFrom-Json
    $json.PSKs.PSObject.Properties | ForEach-Object {
        # `20` is for the string length
        $_.Value = [System.Security.Cryptography.RandomNumberGenerator]::GetString($chars, 20)
    }
    $json | ConvertTo-Json | Set-Content path\to\json.txt