powershellhex

PowerShell convert Int to Hex and write info to text file


I'm working on PowerShell Module Library that we want to use in our environment to simplify some coding. I'm having small module that read registry values, and I want to do the following Module reads DWORD value, but it should show not only Decimal but also Hex value

Log "Operating System UBR: $(GetDWORDValue "HKLM" "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "UBR" "64")"

Log "Operating System UBR (hex): ($(GetDWORDValue "HKLM" "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "UBR" "64")).ToString('X')"

Output [06/21/2024 14:15:34 - TemplateScript.ps1] Operating System UBR: 3737 [06/21/2024 14:15:34 - TemplateScript.ps1] Operating System UBR (hex): (3737).ToString('X') item in Bold is not correct and should show 'E99'

I've tried various combinations:

Which is basically module that's using Add-Content and as param the text that I'm passing.

Log module

function Log {
    param (
        [string]$sText
    )

    $logFolderPath = "C:\Logs"
    if ($sAppName -eq $null) {
          $sAppName = $scriptName
        }
    $logFilePath = Join-Path -Path $logFolderPath -ChildPath "$sAppName.log"

    if (-not (Test-Path -Path $logFolderPath)) {
        New-Item -Path $logFolderPath -ItemType Directory
    }

    $sCurTime = Get-Date -Format "MM/dd/yyyy HH:mm:ss"
    $logEntry = "[$sCurTime - $scriptName] $sText"

    Add-Content -Path $logFilePath -Value $logEntry
}

Any idea/suggestions are welcome Thx!


Solution

  • You need to surround the whole (...).ToString('X') invocation in a subexpression $(...):

    Log "Operating System UBR (hex): $((GetDWORDValue "HKLM" "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "UBR" "64").ToString('X'))"
    

    You can also use a single pipeline by having ForEach-Object invoke the ToString method, like so:

    Log "Operating System UBR (hex): $(GetDWORDValue "HKLM" "SOFTWARE\Microsoft\Windows NT\CurrentVersion" "UBR" "64" |ForEach-Object ToString 'X')"
    

    Makes it slightly more readable without the double parens :)