Powershell:文件日期/时间戳检查,需要输出才能退出代码

时间:2014-01-13 18:05:55

标签: powershell

我将自定义代码部署到数千台计算机,并且能够获得返回代码,以便在我必须用来推出代码的工具中为一个或两个对象正常运行。但我正在寻找一种设置文件验证器的方法 - 因为开发人员不一致地使用版本编号我已经能够使用下面的代码来检查每个对象的日期戳。

代码:

$foo1= Get-ChildItem "C:\path\file1.exe" | Where-Object {$_.LastWriteTime -gt "11/1/2013"} | Out-String
$foo2= Get-ChildItem "C:\path\file2.exe" | Where-Object {$_.LastWriteTime -gt "9/10/2013"} | Out-String
$foo3= Get-ChildItem "C:\path\file3.exe" | Where-Object {$_.LastWriteTime -gt "4/23/2013"} | Out-String
$foo4= Get-ChildItem "C:\path\file4.exe" | Where-Object {$_.LastWriteTime -gt "12/17/2012"} | Out-String

以上工作但会显示对象名称和上次写入时间。我可以用以下代码编写退出代码:

if($foo1){Write-Host '0'
}else{
Write-Host '5'
Exit 5 
}

有没有办法可以说明foo1是否存在(即不是$ null)然后将其读作0并且如果它为null则将其读为1然后声明$ foochecksum = $ foo1 + $ foo2 + $ foo3 + $ foo4并执行上面引用的If Else一次将退出代码写入我的部署工具?

从功能上来说,我正在寻找的是一种检查多个文件日期/时间戳的方法,然后如果一切正常,那么将0传递给将为我的部署工具写入通过或失败的If / Else语句。

如果需要,我可以使用多个if / else,但是需要检查40个文件,而不是必须有40个不同的IF / Else语句。

我也很乐意在PS V2和V3中使用可能有效的东西,因为我在生产中混合使用2003和2008服务器。

谢谢,

德怀特

2 个答案:

答案 0 :(得分:1)

使用变量来保存脚本的“错误状态”,并使用HashTable保存您正在“测试”的每个文件的PathLastWriteTime值。 / p>

$ErrorExists = $false;

# Declare some file/lastwritetime pairs
$FileList = @{
        1 = @{ Path = 'C:\path\file1.exe';
        LastWriteTime = '11/1/2013'; };
        2 = @{ Path = 'C:\path\file2.exe';
        LastWriteTime = '9/10/2013'; };
        3 = @{ Path = 'C:\path\file3.exe';
        LastWriteTime = '4/23/2013'; };
        4 = @{ Path = 'C:\path\file4.exe';
        LastWriteTime = '12/17/2012'; };
        };

foreach ($File in $FileList) {
    # If LastWriteTime is LESS than the value specified, raise an error
    if ((Get-Item -Path $File.Path).LastWriteTime -lt $File.LastWriteTime) {
        $ErrorExists = $true;
    }
}

if ($ErrorExists) {
    # Do something
}

答案 1 :(得分:0)

也许是这样的?

$foos = &{
Get-ChildItem "C:\path\file1.exe" | Where-Object {$_.LastWriteTime -gt "11/1/2013"} | select -last 1
Get-ChildItem "C:\path\file2.exe" | Where-Object {$_.LastWriteTime -gt "9/10/2013"}  | select -last 1
Get-ChildItem "C:\path\file3.exe" | Where-Object {$_.LastWriteTime -gt "4/23/2013"} | select -last 1
Get-ChildItem "C:\path\file4.exe" | Where-Object {$_.LastWriteTime -gt "12/17/2012"} | select -last 1
}

if ($foos.count -eq 4) {Write-Host '0'}
else {Write-Host '5';Return '5'}