Powershell文件检查循环

时间:2015-02-17 10:55:00

标签: powershell

以下脚本在给定路径上执行文件验证。如果发现任何文件丢失,脚本返回...我想完成所有提到的4个文件的检查,然后返回任何一个丢失的..如何我需要更改代码..

还需要捕获变量中的日志以用于邮寄目的.. 在此先感谢..

$LocalPath = "D:\Data\Inst"
$paths = foreach($file in @("\abcd.exe", "\xyz.exe", "\IND\123.exe", "\ENG\987.exe"))
{
"$LocalPath$file"
}

foreach ($fullpath in $paths)
{
write-host "Varifying File : $fullpath"
If (-not (Test-Path $fullpath -ErrorAction "SilentlyContinue") ) 
{ 
write-host "`nFile varification $fullpath Failed.!! `a`n "

return 
}
ELSE
{
write-host "$fullpath : is available `n"
}
}

2 个答案:

答案 0 :(得分:0)

# Files to check
$ToCheck = @{'D:\Data\Inst' = @('abcd.exe', 'xyz.exe', 'IND\123.exe', 'ENG\987.exe')}

# Check files
$Log = $ToCheck.GetEnumerator() |
            ForEach-Object {
                foreach ($File in $_.Value){

                    $CurrFile = Join-Path -Path $_.Key -ChildPath $File
                    "Verifying File : $CurrFile"
                    if(Test-Path -LiteralPath $CurrFile -PathType Leaf)
                    {
                        "$CurrFile : is available"
                    }
                    else
                    {
                        $FileMissing = $true
                        "File verification $CurrFile Failed.!!"
                    }
                }
            }

# Send email
if($FileMissing)
{
    Send-MailMessage -SmtpServer 'mail.company.com' -From 'script@company.com' -To 'admin@company.com' -Subject 'File status' -Body $Log
}

答案 1 :(得分:0)

我会做这样的事情。

$LocalPath = "D:\Data\Inst"
$paths = "\abcd.exe", "\xyz.exe", "\IND\123.exe", "\ENG\987.exe" | ForEach-Object{
    "$LocalPath$_"
}

$results = $paths | ForEach-Object{
    [pscustomobject][ordered]@{
        Path = $_
        Exists = Test-Path $_ -ErrorAction "SilentlyContinue"
    } 
}

if ($results.Exists -contains $False){
    $results | Where-Object{$_.Exists -eq $false} | ForEach-Object{ Write-Warning "$($_.Path) does not exists."}
    return
} Else {
    Write-Host "All paths are present."
}

测试每个文件并将每个Test-Path的结果记录到自定义变量中。然后我们检查任何结果是否为$False。如果是,那么我们将展示一个不存在并返回的那个。

或者,根据您的需要,您可以立即将变量$results输出到文件。

$results | Export-CSV C:\temp\results.csv -NoTypeInformation