首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell -将FileTime转换为HexString

PowerShell -将FileTime转换为HexString
EN

Stack Overflow用户
提问于 2018-11-22 20:40:14
回答 2查看 298关注 0票数 7

在搜索完网络之后,我成功地创建了一个C#类来获得一个FileTimeUTC十六进制字符串。

代码语言:javascript
复制
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,我尝试使用相同的代码:

代码语言:javascript
复制
$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;

问题是我收到了一些错误消息:

代码语言:javascript
复制
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类。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-11-22 20:43:45

结果是你需要包括使用指令。在这种情况下,“使用系统;”

代码语言:javascript
复制
$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;
票数 2
EN

Stack Overflow用户

发布于 2018-11-22 21:45:13

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

但是,您可能有兴趣知道,可以使用基本上是Powershell的一行程序来实现所需的结果:

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

$HexString = GetUTCFileTimeAsHexString
$HexString;

请注意,这至少需要Powershell 3,它引入了-shr-band运算符。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53437755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档