Issues with Generating SHA-256 Hash Report During USB Drive Scanning in PowerShell Script

I am trying to create an isolated computer for USB drive decontamination using a script that scans my USB drive and generates a report in the directory C:ScanReports. However, I am encountering an issue with my code. The problem is that it fails to find the directory C:ScanReports. After analyzing my code line by line to pinpoint the issue, I found that the problem lies here: Get-ChildItem : Cannot find path ‘C:Userskenny:’ because it does not exist.
At line:1 char:1

  • Get-ChildItem -Path “$($Volume.DriveLetter):”
  •   + CategoryInfo          : ObjectNotFound: (C:Userskenny::String) [Get-ChildItem], ItemNotFoundException
      + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
    
    

Write-Host “Surveillance des disques USB…”

Can anyone help me resolve this issue? Thank you!

Write-Host "Surveillance des disques USB..."

function Show-Notification {
    param ([string]$Message, [int]$DisplayTime = 3)
    Add-Type -AssemblyName System.Windows.Forms
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "Notification"
    $form.Size = New-Object System.Drawing.Size(350, 150)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
    $form.TopMost = $true
    $label = New-Object System.Windows.Forms.Label
    $label.Text = $Message
    $label.TextAlign = "MiddleCenter"
    $label.Dock = "Fill"
    $label.Font = New-Object System.Drawing.Font("Arial", 12, [System.Drawing.FontStyle]::Bold)
    $form.Controls.Add($label)
    $form.Show() | Out-Null
    Start-Sleep -Seconds $DisplayTime
    $form.Close()
    $form.Dispose()
}

function Show-Progress {
    param ([string]$Message)
    Add-Type -AssemblyName System.Windows.Forms
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "Analyse en cours"
    $form.Size = New-Object System.Drawing.Size(350, 150)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
    $form.TopMost = $true
    $label = New-Object System.Windows.Forms.Label
    $label.Text = "$Message, veuillez patienter..."
    $label.TextAlign = "MiddleCenter"
    $label.Dock = "Fill"
    $label.Font = New-Object System.Drawing.Font("Arial", 12, [System.Drawing.FontStyle]::Bold)
    $form.Controls.Add($label)
    $progressBar = New-Object System.Windows.Forms.ProgressBar
    $progressBar.Dock = "Bottom"
    $progressBar.Style = "Continuous"
    $progressBar.Minimum = 0
    $progressBar.Maximum = 100
    $progressBar.Value = 0
    $form.Controls.Add($progressBar)
    $form.Show() | Out-Null
    return [PSCustomObject]@{Form=$form; ProgressBar=$progressBar}
}

function Update-Progress {
    param ([PSCustomObject]$ProgressDialog, [int]$Value)
    if ($ProgressDialog -and $ProgressDialog.Form.Visible) {
        $ProgressDialog.ProgressBar.Value = $Value
    }
}

function Close-Progress {
    param ([PSCustomObject]$ProgressDialog)
    if ($ProgressDialog -and $ProgressDialog.Form.Visible) {
        $ProgressDialog.Form.Close()
        $ProgressDialog.Form.Dispose()
    }
}

function Get-FileHashSHA256 {
    param ([string]$FilePath)
    $sha256 = [System.Security.Cryptography.SHA256]::Create()
    $stream = [System.IO.File]::OpenRead($FilePath)
    $hash = $sha256.ComputeHash($stream)
    $stream.Close()
    return [BitConverter]::ToString($hash) -replace "-", ""
}

$ReportsPath = "C:ScanReports"
if (-not (Test-Path -Path $ReportsPath)) { New-Item -ItemType Directory -Path $ReportsPath | Out-Null }

while ($true) {
    try {
        $USBDrives = Get-CimInstance win32_diskdrive | Where-Object { $_.InterfaceType -eq 'USB' }
        if ($USBDrives) {
            $Volumes = Get-Volume | Where-Object { $_.DriveType -eq 'Removable' }
            foreach ($Volume in $Volumes) {
                Show-Notification -Message "Lecteur détecté !" -DisplayTime 2

                Start-Sleep -Seconds 5  # Attente pour assurer que le lecteur soit prêt

                $progressDialog = Show-Progress -Message "Analyse en cours"
                $scanJob = $null
                $progressValue = 0
                $VolumeRemoved = $false
                while ($true) {
                    Start-Sleep -Seconds 1
                    $VolumePresent = Get-Volume -DriveLetter $Volume.DriveLetter -ErrorAction SilentlyContinue
                    if (-not $VolumePresent) {
                        Show-Notification -Message "Lecteur retiré. Annulation." -DisplayTime 2
                        Close-Progress $progressDialog
                        $VolumeRemoved = $true
                        break
                    }

                    if (-not $scanJob -and $VolumePresent) {
                        try {
                            $scanJob = Start-MpScan -ScanPath "$($Volume.DriveLetter):" -AsJob
                        } catch {
                            Show-Notification -Message "Erreur de démarrage de l'analyse. Réessayez." -DisplayTime 3
                            Close-Progress $progressDialog
                            break
                        }
                    }

                    if ($scanJob.State -eq 'Running') {
                        $progressValue += 10  # Augmenter par 10 à chaque mise à jour pour réduire la fréquence
                        $progressValue = [math]::Min($progressValue, 98)
                        Update-Progress -ProgressDialog $progressDialog -Value $progressValue
                    } elseif ($scanJob.State -eq 'Completed') {
                        Update-Progress -ProgressDialog $progressDialog -Value 100
                        Close-Progress $progressDialog
                        break
                    } elseif ($scanJob.State -eq 'Failed' -or -not $scanJob) {
                        Close-Progress $progressDialog
                        Show-Notification -Message "Erreur pendant l'analyse. Réessayez." -DisplayTime 3
                        break
                    }
                }

                if (-not $VolumeRemoved -and $scanJob -and $scanJob.State -eq 'Completed') {
                    $ReportText = @("Date : $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')", "Lecteur : $($Volume.DriveLetter):")
                    $ReportText += "Résultat : Aucun problème détecté."

                    $files = Get-ChildItem -Path "$($Volume.DriveLetter):" -Recurse -File
                    foreach ($file in $files) {
                        $hash = Get-FileHashSHA256 -FilePath $file.FullName
                        $ReportText += "Fichier : $($file.FullName)"
                        $ReportText += "SHA-256 : $hash"
                    }

                    if ($VolumePresent) {
                        $ReportFileName = "Rapport_$($Volume.DriveLetter)_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt"
                        $ReportFilePath = Join-Path -Path $ReportsPath -ChildPath $ReportFileName
                        $ReportText | Set-Content -Path $ReportFilePath -Encoding UTF8
                    }

                    $ScanResult = Get-MpThreatDetection | Where-Object { $_.Resources -like "$($Volume.DriveLetter):*" }
                    $message = if ($ScanResult) {
                        $ReportText += "Menaces détectées :"
                        foreach ($Threat in $ScanResult) {
                            $ReportText += "- Nom : $($Threat.ThreatName)"
                            $ReportText += "  Chemin : $($Threat.Resources)"
                        }
                        "Menaces détectées. Rapport généré. Veuillez retirer la clé USB."
                    } else {
                        "Aucune menace détectée. Rapport généré. Veuillez retirer la clé USB."
                    }
                    Show-Notification -Message $message -DisplayTime 5
                    Show-Notification -Message "Analyse terminée. Veuillez retirer la clé USB." -DisplayTime 10

                    # Attendre jusqu'à ce que la clé soit retirée
                    while (Get-Volume -DriveLetter $Volume.DriveLetter -ErrorAction SilentlyContinue) {
                        Start-Sleep -Seconds 1
                    }

                    # Notification pour attendre 30 secondes avant de reprendre la détection
                    Show-Notification -Message "Veuillez attendre 30 secondes avant de rebrancher une clé." -DisplayTime 10

                    # Attendre 30 secondes avant de reprendre la détection
                    Start-Sleep -Seconds 30
                }

                while (Get-Volume -DriveLetter $Volume.DriveLetter -ErrorAction SilentlyContinue) {
                    Start-Sleep -Seconds 1
                }
            }
        }
        Start-Sleep -Seconds 1
    } catch {
        Write-Host "Erreur dans la surveillance des disques USB : $_"
    }
}

New contributor

Kenny Ali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật