PowerShell-将FileTime转换为HexString



在搜索interweb之后,我成功地创建了一个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类。

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

然而,您可能有兴趣知道,使用Powershell的一行代码可以实现所需的结果

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

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

原来您需要包含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;

最新更新