Powershell 文件检查循环

Powershell File Checking Loop

以下脚本对给定路径进行文件验证。脚本 return if found any of the file is missing...我想完成对提到的所有 4 个文件的检查,然后 return 如果有任何文件丢失..我需要如何更改代码..

还需要将日志捕获到一个变量中以用于邮寄目的.. 提前致谢..

$LocalPath = "D:\Data\Inst"
$paths = foreach($file in @("\abcd.exe", "\xyz.exe", "\IND3.exe", "\ENG7.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"
}
}
# Files to check
$ToCheck = @{'D:\Data\Inst' = @('abcd.exe', 'xyz.exe', 'IND3.exe', 'ENG7.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
}

我会做这样的事情。

$LocalPath = "D:\Data\Inst"
$paths = "\abcd.exe", "\xyz.exe", "\IND3.exe", "\ENG7.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."
}

测试每个文件并将每个测试路径的结果记录到自定义变量中。然后我们检查是否 any 结果是 $False。如果一个是,那么我们显示一个不存在的 return。

可选地,根据您的需要,您现在可以将变量 $results 输出到文件。

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