PowerShell - Convert FileTime to HexString

383 views Asked by At

After searching the interwebs, I've managed to create a C# class to get a FileTimeUTC Hex String.

public class HexHelper
{
    public static string GetUTCFileTimeAsHexString()
    {
        string sHEX = "";

        long ftLong = DateTime.Now.ToFileTimeUtc();
        int ftHigh = (int)(ftLong >> 32);
        int ftLow = (int)ftLong;
        sHEX = ftHigh.ToString("X") + ":" + ftLow.ToString("X");

        return sHEX;
    }
}

For PowerShell I've tried using this same code:

$HH = @"
public class HexHelper
{
    public static string GetUTCFileTimeAsHexString()
    {
        string sHEX = "";

        long ftLong = DateTime.Now.ToFileTimeUtc();
        int ftHigh = (int)(ftLong >> 32);
        int ftLow = (int)ftLong;
        sHEX = ftHigh.ToString("X") + ":" + ftLow.ToString("X");

        return sHEX;
    }
}
"@;

Add-Type -TypeDefinition $HH;
$HexString = [HexHelper]::GetUTCFileTimeAsHexString();
$HexString;

The problem is I get a few error messages:

The name 'DateTime' does not exist in the current context

+ FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand

Add-Type : Cannot add type. Compilation errors occurred.

+ CategoryInfo          : InvalidData: (:) [Add-Type], InvalidOperationException
+ FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand

I don't know how to get this C# code valid for PowerShell and would like a working solution. I don't know why PowerShell can't recognize the DateTime class in my C# snippet.

2

There are 2 answers

0
C Sharp Conner On BEST ANSWER

Turns out you need to include the using directive. In this case, "using System;"

$HH = @"
using System;

public class HexHelper
{
    public static string GetUTCFileTimeAsHexString()
    {
        string sHEX = "";

        long ftLong = DateTime.Now.ToFileTimeUtc();
        int ftHigh = (int)(ftLong >> 32);
        int ftLow = (int)ftLong;
        sHEX = ftHigh.ToString("X") + ":" + ftLow.ToString("X");

        return sHEX;
    }
}
"@;

Add-Type -TypeDefinition $HH;
$HexString = [HexHelper]::GetUTCFileTimeAsHexString();
$HexString;
0
AudioBubble On

My answer here is technically not an answer to your question, as it does not address your technical problem (which you have already solved by yourself).

However, you might be interested in knowing that the desired result can be achieved with what is basically a Powershell one-liner:

function GetUTCFileTimeAsHexString
{
    return `
        (Get-Date).ToFileTimeUtc() `
        | % { "{0:X8}:{1:X8}" -f (($_ -shr 32) -band 0xFFFFFFFFL), ($_ -band 0xFFFFFFFFL) }
}

$HexString = GetUTCFileTimeAsHexString
$HexString;

Note that this requires at least Powershell 3, which introduced the -shr and -band operators.