powershell - 在PowerShell中转换日期时间格式

标签 powershell powershell-2.0 powershell-3.0

如何将以下日期转换为dd / mm / yyyy格式?

Tue Aug  4 17:05:41 2015

我尝试了多种方法和选项,但是没有运气。
$a = Get-Date -UFormat %c
(Get-Date $a).ToString("ddMMyyyy")

在日志文件中找到此dateformat,我的系统datetime格式为dd / mm / yyyy。
我正在尝试对它们进行比较。因此,我需要更改日期时间格式。

最佳答案

@jisaak的答案几乎是正确的,除了日期分量前面的额外填充空间(“2015年8月4日星期二17:05:41”)会在尝试解析日期:每月的10号到31号:

PS C:\> [Datetime]::ParseExact('Tue Aug  4 17:05:41 2015', 'ddd MMM  d HH:mm:ss yyyy', $us)

Tuesday, August 04, 2015 5:05:41 PM


PS C:\> [Datetime]::ParseExact('Tue Aug 11 17:05:41 2015', 'ddd MMM  d HH:mm:ss yyyy', $us)
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:1 char:1
+ [Datetime]::ParseExact('Tue Aug 11 17:05:41 2015', 'ddd MMM  d HH:mm:ss yyyy', $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

最简单的方法是删除输入字符串和格式字符串中的填充空间:
function Parse-CustomDate {
    param(
        [Parameter(Mandatory=$true)]
        [string]$DateString,
        [string]$DateFormat = 'ddd MMM d HH:mm:ss yyyy',
        [cultureinfo]$Culture = $(New-Object System.Globalization.CultureInfo -ArgumentList "en-US")
    )

    # replace double space by a single one
    $DateString = $DateString -replace '\s+',' '

    [Datetime]::ParseExact($DateString, $DateFormat, $Culture)
}

关于powershell - 在PowerShell中转换日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31808296/

相关文章:

powershell - (Powershell) 捕获 "Get-WinEvent : No events were found"Get-WinEvent

powershell - 如何在传递给函数的Powershell中附加字符串

.net - 测试 TCP 端口是否在未连接的情况下打开

powershell - 如何复制带有子文件夹的文件夹?

powershell - 使用Powershell 3下载磁链接

azure - 如何将参数传递给 Azure PowerShell Set-AzVmRunCommand?

powershell - Get-ChildItem为Assembly。*。dll添加排除筛选器,但包括Assembly.Some。*。dll

powershell - 自动 Web 部署到远程 IIS 服务器

linux - 尝试使用 PowerShell 从我的本地计算机复制文本文件内容并将其添加到 Linux 服务器中的另一个文件

rest - Powershell v3 Invoke-RestMethod header