7

在搜索了互联网后,我设法创建了一个 C# 类来获取 FileTimeUTC 十六进制字符串。

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;
    }
}

对于 PowerShell,我尝试使用相同的代码:

$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 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

我不知道如何让这个 C# 代码对 PowerShell 有效,并且想要一个可行的解决方案。我不知道为什么 PowerShell 无法识别我的 C# 代码段中的 DateTime 类。

4

2 回答 2

7

我在这里的回答在技术上不是对您问题的回答,因为它没有解决您的技术问题(您已经自己解决了)。

但是,您可能有兴趣知道使用基本上是 Powershell 单线的东西可以实现所需的结果:

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

$HexString = GetUTCFileTimeAsHexString
$HexString;

请注意,这至少需要引入-shrand-band运算符的 Powershell 3。

于 2018-11-22T21:45:13.113 回答
2

原来你需要包含 using 指令。在这种情况下,“使用系统;”

$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;
于 2018-11-22T20:43:45.250 回答