kvm-guest-drivers-windows

Форк
0
/
CollectSystemInfo.ps1 
288 строк · 11.1 Кб
1
#  This script collects various system information for diagnostic
2
#  purposes. The collected data includes system configuration,
3
#  event logs, driver lists, registry information, update logs,
4
#  services, uptime, running processes, installed applications,
5
#  installed KBs, and memory dumps.
6

7
#  Copyright (c) 2024 Red Hat, Inc. and/or its affiliates. All rights reserved.
8

9
#  Redistribution and use in source and binary forms, with or without
10
#  modification, are permitted provided that the following conditions
11
#  are met:
12
#  1. Redistributions of source code must retain the above copyright
13
#     notice, this list of conditions and the following disclaimer.
14
#  2. Redistributions in binary form must reproduce the above copyright
15
#     notice, this list of conditions and the following disclaimer in the
16
#     documentation and/or other materials provided with the distribution.
17
#  3. Neither the names of the copyright holders nor the names of their contributors
18
#     may be used to endorse or promote products derived from this software
19
#     without specific prior written permission.
20
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21
#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
24
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26
#  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27
#  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28
#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29
#  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30
#  SUCH DAMAGE.
31

32

33
#  Ensure the script runs with an unrestricted execution policy (for Windows 10 and Windows Server 2016)
34
#  Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force
35

36
#  For gathering event logs run the script as an administrator
37

38
#  IncludeSensitiveData is used to include memory dumps add this parameter to your command line to collect them
39
#  Example:  .\CollectSystemInfo.ps1 -IncludeSensitiveData
40

41
param (
42
    [switch]$IncludeSensitiveData,
43
    [switch]$Help
44
)
45

46
Add-Type -AssemblyName 'System.IO.Compression.FileSystem'
47

48
function Compress-Files {
49
    param (
50
        [string]$SourcePath,
51
        [string]$DestinationPath
52
    )
53

54
    [System.IO.Compression.ZipFile]::CreateFromDirectory($SourcePath, $DestinationPath)
55
}
56

57
function Show-Help {
58
    Write-Host "Usage: .\CollectSystemInfo.ps1 [-IncludeSensitiveData] [-Help]"
59
    Write-Host ""
60
    Write-Host "Parameters:"
61
    Write-Host "  -IncludeSensitiveData  Include sensitive data (memory dump)"
62
    Write-Host "  -Help                  Show this help message"
63
    Write-Host ""
64
    Write-Host "If no parameters are provided, the script will run with default behavior."
65
}
66

67
function Export-SystemConfiguration {
68
    try {
69
        Write-Host 'Collecting system configuration started it may take a while...'
70
        Start-Process -FilePath 'msinfo32.exe' -ArgumentList '/report', (Join-Path $logfolderPath 'msinfo32.txt') -Wait
71
        Write-Host 'System configuration collection completed.'
72
    } catch {
73
        Write-Warning "Failed to collect system configuration: $_"
74
    }
75
}
76

77
function Export-EventLogs {
78
    try {
79
        $logNames = @('system', 'security', 'application')
80
        foreach ($logName in $logNames) {
81
            $logPath = Join-Path $logfolderPath "$logName.evtx"
82
            wevtutil epl $logName $logPath
83
            wevtutil al $logPath
84
        }
85
        Write-Host 'Event logs collection completed.'
86
    } catch {
87
        Write-Warning "Failed to collect event logs: $_"
88
    }
89
}
90

91
function Export-DriversList {
92
    try {
93
        Get-WindowsDriver -Online -All | Select-Object -Property * | Export-Csv -Path (Join-Path $logfolderPath 'drv_list.csv') -NoTypeInformation
94
        Write-Host 'Drivers list collection completed.'
95
    } catch {
96
        Write-Warning "Failed to collect drivers list: $_"
97
    }
98
}
99

100
function Export-VirtioWinStorageDrivers {
101
    $registryPaths = @(
102
        'HKLM:\SYSTEM\CurrentControlSet\Services\Disk',
103
        'HKLM:\SYSTEM\CurrentControlSet\Services\viostor\Parameters',
104
        'HKLM:\SYSTEM\CurrentControlSet\Services\vioscsi\Parameters'
105
    )
106
    $valuesToQuery = @('IoTimeoutValue', 'TimeoutValue')
107

108
    foreach ($path in $registryPaths) {
109
        foreach ($value in $valuesToQuery) {
110
            $property = Get-ItemProperty -Path $path -Name $value -ErrorAction SilentlyContinue
111
            $output = "$path\$value : $($property.$value)" 
112
            $output | Out-File -FilePath (Join-Path $logfolderPath 'virtio_disk.txt') -Append
113
        }
114
    }
115
    Write-Host 'Virtio-Win storage drivers configuration collection completed.'
116
}
117

118
function Export-WindowsUpdateLogs {
119
    try {
120
        $logPath = Join-Path $logfolderPath 'WindowsUpdate.log'
121
        $command = "Get-WindowsUpdateLog -LogPath '$logPath'"
122
        Start-Process -FilePath 'powershell.exe' -ArgumentList '-NoLogo', '-NoProfile', '-Command', $command -NoNewWindow -Wait -RedirectStandardOutput (Join-Path $logfolderPath 'OutputWindowsUpdate.log') -RedirectStandardError (Join-Path $logfolderPath 'ErrorWindowsUpdate.log')
123
        Write-Host 'Windows Update logs collection completed.'
124
    } catch {
125
        Write-Warning "Failed to collect Windows Update logs: $_"
126
    }
127
}
128

129
function Export-WindowsUptime {
130
    try {
131
        $uptime = (Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime
132
        $uptime.ToString() | Out-File -FilePath (Join-Path $logfolderPath 'WindowsUptime.txt')
133
        Write-Host 'Windows uptime collection completed.'
134
    } catch {
135
        Write-Warning "Failed to collect Windows uptime: $_"
136
    }
137
}
138

139
function Export-ServicesList {
140
    try {
141
        Get-Service | Select-Object -Property Name, DisplayName, Status, StartType | Export-Csv -Path (Join-Path $logfolderPath 'Services.csv') -NoTypeInformation
142
        Write-Host 'Services list collection completed.'
143
    } catch {
144
        Write-Warning "Failed to collect list of services: $_"
145
    }
146
}
147

148
function Export-RunningProcesses {
149
    try {
150
        Get-Process | Select-Object -Property Id, ProcessName, StartTime | Export-Csv -Path (Join-Path $logfolderPath 'RunningProcesses.csv') -NoTypeInformation
151
        Write-Host 'Running processes collection completed.'
152
    } catch {
153
        Write-Warning "Failed to collect list of running processes: $_"
154
    }
155
}
156

157
function Export-InstalledApplications {
158
    try {
159
        Get-ItemProperty -Path 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' |
160
        Select-Object -Property DisplayName, DisplayVersion, Publisher, InstallDate |
161
        Export-Csv -Path (Join-Path $logfolderPath 'InstalledApplications.csv') -NoTypeInformation
162
        Write-Host 'Installed applications collection completed.'
163
    } catch {
164
        Write-Warning "Failed to collect list of installed applications: $_"
165
    }
166
}
167

168
function Export-InstalledKBs {
169
    try {
170
        Get-HotFix | Select-Object -Property Description, HotFixID, InstalledOn | Export-Csv -Path (Join-Path $logfolderPath 'InstalledKBs.csv') -NoTypeInformation
171
        Write-Host 'Installed KBs collection completed.'
172
    } catch {
173
        Write-Warning "Failed to collect list of installed KBs: $_"
174
    }
175
}
176

177
function Export-NetworkConfiguration {
178
    try {
179
        Get-NetAdapterAdvancedProperty | Out-File -FilePath (Join-Path $logfolderPath 'NetworkInterfaces.txt')
180
        ipconfig /all | Out-File -FilePath (Join-Path $logfolderPath 'IPConfiguration.txt')
181

182
        Write-Host 'Network configuration collection completed.'
183
    } catch {
184
        Write-Warning "Failed to collect network configuration: $_"
185
    }
186
}
187

188
function Export-WindowsMemoryDump {
189
    $memoryDumpPaths = @("$env:SystemRoot\MEMORY.DMP", "$env:SystemRoot\Minidump")
190

191
    foreach ($dump in $memoryDumpPaths) {
192
        Copy-Item -Path $dump -Destination $dumpfolderPath -Recurse -ErrorAction SilentlyContinue
193
    }
194
    Write-Host 'Windows memory dump collection completed.'
195
}
196

197
function Write-InformationToArchive {
198
    param (
199
        [string]$FolderPath,
200
        [string]$SubFolderPath,
201
        [string]$ArchiveFileName
202
    )
203
    try {
204
        $archivePath = Join-Path -Path $FolderPath -ChildPath "$ArchiveFileName.zip"
205
        Compress-Files -SourcePath $SubFolderPath -DestinationPath $archivePath
206
        Write-Host "Archiving completed ($ArchiveFileName.zip)."
207
    } catch {
208
        Write-Warning "Failed to archive ($ArchiveFileName.zip): $_"
209
    }
210
}
211

212
function StopTranscriptAndCloseFile {
213
    if ($transcriptStarted) {
214
        Stop-Transcript | Out-Null
215
        $transcriptStarted = $false
216
    }
217
}
218

219
$validParams = @('IncludeSensitiveData', 'Help')
220
if ($Help -or $args -contains '-?' -or $args -contains '--Help') {
221
    Show-Help
222
    return
223
}
224

225
foreach ($param in $args) {
226
    if ($param -notlike '-*' -or ($param -like '-*' -and $validParams -notcontains $param.TrimStart('-'))) {
227
        Write-Host "A parameter cannot be found that matches parameter name '$param'"
228
        Show-Help
229
        return
230
    }
231
}
232

233
$breakHandler = {
234
    Write-Host "Script interrupted by user. Stopping transcript..."
235
    StopTranscriptAndCloseFile
236
    exit
237
}
238
Register-EngineEvent -SourceIdentifier ConsoleBreak -Action $breakHandler | Out-Null
239
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action $breakHandler | Out-Null
240

241
$timestamp = Get-Date -Format 'yyyy-MM-dd_HH-mm-ss'
242
$folderName = "SystemInfo_$timestamp"
243
$logfolderName = "Log_folder_$timestamp"
244
$dumpfolderName = "Dump_folder_$timestamp"
245
$folderPath = Join-Path -Path (Get-Location) -ChildPath $folderName
246
$logfolderPath = Join-Path -Path $folderPath -ChildPath $logfolderName
247
$dumpfolderPath = Join-Path -Path $folderPath -ChildPath $dumpfolderName
248
$progressFile = "$folderPath\Collecting_Status.txt"
249
New-Item -Path $logfolderPath -ItemType Directory | Out-Null
250
New-Item -Path $progressFile -ItemType File | Out-Null
251
Write-Host "Starting system info collecting into $folderPath"
252
Write-Output "Log folder path: $logfolderPath"
253

254
try {
255
    Start-Transcript -Path $progressFile -Append
256
    $transcriptStarted = $true
257
    Export-SystemConfiguration
258
    Export-EventLogs
259
    Export-DriversList
260
    Export-VirtioWinStorageDrivers
261
    Export-WindowsUpdateLogs
262
    Export-ServicesList
263
    Export-WindowsUptime
264
    Export-RunningProcesses
265
    Export-InstalledApplications
266
    Export-InstalledKBs
267
    Export-NetworkConfiguration
268

269
    if ($IncludeSensitiveData) {
270
        Write-Output "Dump folder path: $dumpfolderPath"
271
        New-Item -Path $dumpfolderPath -ItemType Directory | Out-Null
272
        Export-WindowsMemoryDump
273
    }
274
} catch {
275
    $errorMsg = "An error occurred: $_"
276
    Write-Host $errorMsg
277
    Add-Content -Path $progressFile -Value $errorMsg
278
} finally {
279
    StopTranscriptAndCloseFile
280
    Unregister-Event -SourceIdentifier ConsoleBreak
281
    Unregister-Event -SourceIdentifier PowerShell.Exiting
282
}
283

284
Remove-Item -Path $progressFile -ErrorAction SilentlyContinue
285
Write-InformationToArchive -FolderPath $folderPath -SubFolderPath $logfolderPath -ArchiveFileName $logfolderName
286
if ($IncludeSensitiveData) {
287
    Write-InformationToArchive -FolderPath $folderPath -SubFolderPath $dumpfolderPath -ArchiveFileName $dumpfolderName
288
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.