我需要一个PowerShell脚本,它可以访问文件的属性并发现LastWriteTime属性并将其与当前日期进行比较并返回日期差异.
我有这样的事......
$writedate = Get-ItemProperty -Path $source -Name LastWriteTime
Run Code Online (Sandbox Code Playgroud)
...但我无法将LastWriteTime强制转换为"DateTime"数据类型.它说,"无法将@ {LastWriteTime = ... date ...}"转换为"System.DateTime".
Jar*_*Par 26
请尝试以下方法.
$d = [datetime](Get-ItemProperty -Path $source -Name LastWriteTime).lastwritetime
Run Code Online (Sandbox Code Playgroud)
这是物品属性怪异的一部分.当您运行Get-ItemProperty时,它不会返回值,而是返回属性.您必须使用一个更多级别的间接来获取值.
bri*_*ary 14
(ls $source).LastWriteTime
Run Code Online (Sandbox Code Playgroud)
("ls","dir"或"gci"是Get-ChildItem的默认别名.)
小智 6
我有一个我想分享的例子
$File = "C:\Foo.txt"
#retrieves the Systems current Date and Time in a DateTime Format
$today = Get-Date
#subtracts 12 hours from the date to ensure the file has been written to recently
$today = $today.AddHours(-12)
#gets the last time the $file was written in a DateTime Format
$lastWriteTime = (Get-Item $File).LastWriteTime
#If $File doesn't exist we will loop indefinetely until it does exist.
# also loops until the $File that exists was written to in the last twelve hours
while((!(Test-Path $File)) -or ($lastWriteTime -lt $today))
{
#if a file exists then the write time is wrong so update it
if (Test-Path $File)
{
$lastWriteTime = (Get-Item $File).LastWriteTime
}
#Sleep for 5 minutes
$time = Get-Date
Write-Host "Sleep" $time
Start-Sleep -s 300;
}
Run Code Online (Sandbox Code Playgroud)
我不能错过任何答案,因为OP接受其中一个解决他们的问题.但是,我发现它们在某方面存在缺陷.当您将赋值的结果输出到变量时,它包含许多空行,而不仅仅是所寻求的答案.例:
PS C:\brh> [datetime](Get-ItemProperty -Path .\deploy.ps1 -Name LastWriteTime).LastWriteTime
Friday, December 12, 2014 2:33:09 PM
PS C:\brh>
Run Code Online (Sandbox Code Playgroud)
我喜欢代码,简洁和正确的两件事.brianary有权对Roger Lipscombe采取简洁的措辞,但由于结果中的额外线条,两者都错过了正确性.这就是我认为OP正在寻找的东西,因为它让我超越终点线.
PS C:\brh> (ls .\deploy.ps1).LastWriteTime.DateTime
Friday, December 12, 2014 2:33:09 PM
PS C:\brh>
Run Code Online (Sandbox Code Playgroud)
请注意缺少额外的行,只有PowerShell用于分隔提示的行.现在可以将其分配给变量进行比较,或者在我的情况下,将其存储在文件中以便在以后的会话中进行读取和比较.