1

下午好,

有人可以告诉我如何使用 powershell 将日期 20120624 转换为 yyyyMMdd,因为我在运行以下代码时得到“字符串未被识别为有价值的日期时间”

[String]$ServiceTag = "b26ybt1";

Try{ 
       $AssetService = New-WebServiceProxy -Uri "http://xserv.dell.com/services/AssetService.asmx?WSDL"; 
       $ApplicationName = "AssetService"; 
       $Guid = [Guid]::NewGuid(); 
       $Asset = $AssetService.GetAssetInformation($Guid,$ApplicationName,$ServiceTag); 
       $Writer = New-Object "System.IO.StringWriter"; 
       $XmlSerializer = New-Object System.Xml.Serialization.XmlSerializer($Asset.GetType()); 
       $XmlSerializer.Serialize($Writer,$Asset); 
       [String]$Result = $Writer.ToString(); 
       $Writer.Flush(); 
       $Writer.Close(); 
       Return $Result; 
} 
Catch{ 
       Write-Host $($_.Exception.Message);     
}

$prog = [regex]::match($Result,'(?<=StartDate>)(.*)(?=T00)').Groups[1].Value
[System.Text.RegularExpressions.Regex]::Replace($prog,"[-]","");

[datetime]::ParseExact($prog,"yyyyMMdd",$null)
4

2 回答 2

3

改变

[System.Text.RegularExpressions.Regex]::Replace($prog,"[-]","");

$prog = [System.Text.RegularExpressions.Regex]::Replace($prog,"[-]","");

您所做的只是返回替换将执行的操作,而实际上从未将其分配给变量。当我像上面那样运行它时,我得到了以下信息:

Sunday, June 24, 2012 12:00:00 AM
于 2012-09-06T16:24:04.567 回答
1

您可以将结果转换为 XML 而不是 String 并避免字符串解析:

[xml]$Result = $Writer.ToString()
[datetime]$Result.ArrayOfAsset.Asset.Entitlements.EntitlementData[0].StartDate
于 2012-09-06T17:47:14.217 回答