簡體   English   中英

Powershell:文件日期/時間戳檢查,需要輸出以退出代碼

[英]Powershell: File date/time stamp check, need to output to exit code

我將自定義代碼部署到數千台計算機上,並且能夠使返回代碼針對必須用於推出代碼的工具中的一個或兩個對象正確運行。 但是我正在尋找一種設置文件驗證器的方法-因為開發人員不會一直使用版本編號,所以我已經能夠使用下面的代碼檢查每個對象的日期戳。

碼:

$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 if,但是需要檢查40個文件,而不必使用40個不同的IF / Else語句。

我也很想擁有一些可以在PS V2和V3中運行的功能,因為我在產品中混合了2003和2008服務器。

謝謝,

德懷特

使用變量來保存腳本的“錯誤狀態”,並使用HashTable來保存要“測試”的每個文件的PathLastWriteTime值。

$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
}

也許是這樣的嗎?

$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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM