├── LICENSE ├── PSSQLite ├── Invoke-SqliteBulkCopy.ps1 ├── Invoke-SqliteQuery.ps1 ├── New-SqliteConnection.ps1 ├── Out-DataTable.ps1 ├── PSSQLite.psd1 ├── PSSQLite.psm1 ├── x64 │ ├── SQLite.Interop.dll │ └── System.Data.SQLite.dll └── x86 │ ├── SQLite.Interop.dll │ └── System.Data.SQLite.dll ├── PoSh-R2.ps1 ├── README.md └── Screenshots ├── 1-Script_Execution.png ├── 2-Results.png ├── 2.1-Results.png ├── 3-Results2.png └── 4-Filter.PNG /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /PSSQLite/Invoke-SqliteBulkCopy.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-SQLiteBulkCopy { 2 | <# 3 | .SYNOPSIS 4 | Use a SQLite transaction to quickly insert data 5 | 6 | .DESCRIPTION 7 | Use a SQLite transaction to quickly insert data. If we run into any errors, we roll back the transaction. 8 | 9 | The data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance. 10 | 11 | .PARAMETER DataSource 12 | Path to one ore more SQLite data sources to query 13 | 14 | .PARAMETER Force 15 | If specified, skip the confirm prompt 16 | 17 | .PARAMETER NotifyAfter 18 | The number of rows to fire the notification event after transferring. 0 means don't notify. Notifications hit the verbose stream (use -verbose to see them) 19 | 20 | .PARAMETER QueryTimeout 21 | Specifies the number of seconds before the queries time out. 22 | 23 | .PARAMETER SQLiteConnection 24 | An existing SQLiteConnection to use. We do not close this connection upon completed query. 25 | 26 | .PARAMETER ConflictClause 27 | The conflict clause to use in case a conflict occurs during insert. Valid values: Rollback, Abort, Fail, Ignore, Replace 28 | 29 | See https://www.sqlite.org/lang_conflict.html for more details 30 | 31 | .EXAMPLE 32 | # 33 | #Create a table 34 | Invoke-SqliteQuery -DataSource "C:\Names.SQLite" -Query "CREATE TABLE NAMES ( 35 | fullname VARCHAR(20) PRIMARY KEY, 36 | surname TEXT, 37 | givenname TEXT, 38 | BirthDate DATETIME)" 39 | 40 | #Build up some fake data to bulk insert, convert it to a datatable 41 | $DataTable = 1..10000 | %{ 42 | [pscustomobject]@{ 43 | fullname = "Name $_" 44 | surname = "Name" 45 | givenname = "$_" 46 | BirthDate = (Get-Date).Adddays(-$_) 47 | } 48 | } | Out-DataTable 49 | 50 | #Copy the data in within a single transaction (SQLite is faster this way) 51 | Invoke-SQLiteBulkCopy -DataTable $DataTable -DataSource $Database -Table Names -NotifyAfter 1000 -ConflictClause Ignore -Verbose 52 | 53 | .INPUTS 54 | System.Data.DataTable 55 | 56 | .OUTPUTS 57 | None 58 | Produces no output 59 | 60 | .NOTES 61 | This function borrows from: 62 | Chad Miller's Write-Datatable 63 | jbs534's Invoke-SQLBulkCopy 64 | Mike Shepard's Invoke-BulkCopy from SQLPSX 65 | 66 | .LINK 67 | https://github.com/RamblingCookieMonster/Invoke-SQLiteQuery 68 | 69 | .LINK 70 | New-SQLiteConnection 71 | 72 | .LINK 73 | Invoke-SQLiteBulkCopy 74 | 75 | .LINK 76 | Out-DataTable 77 | 78 | .FUNCTIONALITY 79 | SQL 80 | #> 81 | [cmdletBinding( DefaultParameterSetName = 'Datasource', 82 | SupportsShouldProcess = $true, 83 | ConfirmImpact = 'High' )] 84 | param( 85 | [parameter( Position = 0, 86 | Mandatory = $true, 87 | ValueFromPipeline = $false, 88 | ValueFromPipelineByPropertyName= $false)] 89 | [System.Data.DataTable] 90 | $DataTable, 91 | 92 | [Parameter( ParameterSetName='Datasource', 93 | Position=1, 94 | Mandatory=$true, 95 | ValueFromRemainingArguments=$false, 96 | HelpMessage='SQLite Data Source required...' )] 97 | [Alias('Path','File','FullName','Database')] 98 | [validatescript({ 99 | #This should match memory, or the parent path should exist 100 | if ( $_ -match ":MEMORY:" -or (Test-Path $_) ) { 101 | $True 102 | } 103 | else { 104 | Throw "Invalid datasource '$_'.`nThis must match :MEMORY:, or must exist" 105 | } 106 | })] 107 | [string] 108 | $DataSource, 109 | 110 | [Parameter( ParameterSetName = 'Connection', 111 | Position=1, 112 | Mandatory=$true, 113 | ValueFromPipeline=$false, 114 | ValueFromPipelineByPropertyName=$true, 115 | ValueFromRemainingArguments=$false )] 116 | [Alias( 'Connection', 'Conn' )] 117 | [System.Data.SQLite.SQLiteConnection] 118 | $SQLiteConnection, 119 | 120 | [parameter( Position=2, 121 | Mandatory = $true)] 122 | [string] 123 | $Table, 124 | 125 | [Parameter( Position=3, 126 | Mandatory=$false, 127 | ValueFromPipeline=$false, 128 | ValueFromPipelineByPropertyName=$false, 129 | ValueFromRemainingArguments=$false)] 130 | [ValidateSet("Rollback","Abort","Fail","Ignore","Replace")] 131 | [string] 132 | $ConflictClause, 133 | 134 | [int] 135 | $NotifyAfter = 0, 136 | 137 | [switch] 138 | $Force, 139 | 140 | [Int32] 141 | $QueryTimeout = 600 142 | 143 | ) 144 | 145 | Write-Verbose "Running Invoke-SQLiteBulkCopy with ParameterSet '$($PSCmdlet.ParameterSetName)'." 146 | 147 | Function CleanUp 148 | { 149 | [cmdletbinding()] 150 | param($conn, $com, $BoundParams) 151 | #Only dispose of the connection if we created it 152 | if($BoundParams.Keys -notcontains 'SQLiteConnection') 153 | { 154 | $conn.Close() 155 | $conn.Dispose() 156 | Write-Verbose "Closed connection" 157 | } 158 | $com.Dispose() 159 | } 160 | 161 | function Get-ParameterName 162 | { 163 | [CmdletBinding()] 164 | Param( 165 | [Parameter(Mandatory = $true, ValueFromPipeline = $true)] 166 | [string[]]$InputObject, 167 | 168 | [Parameter(ValueFromPipelineByPropertyName = $true)] 169 | [string]$Regex = '(\W+)', 170 | 171 | [Parameter(ValueFromPipelineByPropertyName = $true)] 172 | [string]$Separator = '_' 173 | ) 174 | 175 | Process{ 176 | $InputObject | ForEach-Object { 177 | if($_ -match $Regex){ 178 | $Groups = @($_ -split $Regex | Where-Object {$_}) 179 | for($i = 0; $i -lt $Groups.Count; $i++){ 180 | if($Groups[$i] -match $Regex){ 181 | $Groups[$i] = ($Groups[$i].ToCharArray() | ForEach-Object {[string][int]$_}) -join $Separator 182 | } 183 | } 184 | $Groups -join $Separator 185 | } else { 186 | $_ 187 | } 188 | } 189 | } 190 | } 191 | 192 | function New-SqliteBulkQuery { 193 | [CmdletBinding()] 194 | Param( 195 | [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] 196 | [string]$Table, 197 | 198 | [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] 199 | [string[]]$Columns, 200 | 201 | [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] 202 | [string[]]$Parameters, 203 | 204 | [Parameter(ValueFromPipelineByPropertyName = $true)] 205 | [string]$ConflictClause = '' 206 | ) 207 | 208 | Begin{ 209 | $EscapeSingleQuote = "'","''" 210 | $Delimeter = ", " 211 | $QueryTemplate = "INSERT{0} INTO {1} ({2}) VALUES ({3})" 212 | } 213 | 214 | Process{ 215 | $fmtConflictClause = if($ConflictClause){" OR $ConflictClause"} 216 | $fmtTable = "'{0}'" -f ($Table -replace $EscapeSingleQuote) 217 | $fmtColumns = ($Columns | ForEach-Object { "'{0}'" -f ($_ -replace $EscapeSingleQuote) }) -join $Delimeter 218 | $fmtParameters = ($Parameters | ForEach-Object { "@$_"}) -join $Delimeter 219 | 220 | $QueryTemplate -f $fmtConflictClause, $fmtTable, $fmtColumns, $fmtParameters 221 | } 222 | } 223 | 224 | #Connections 225 | if($PSBoundParameters.Keys -notcontains "SQLiteConnection") 226 | { 227 | $ConnectionString = "Data Source={0}" -f $DataSource 228 | $SQLiteConnection = New-Object System.Data.SQLite.SQLiteConnection -ArgumentList $ConnectionString 229 | $SQLiteConnection.ParseViaFramework = $true #Allow UNC paths, thanks to Ray Alex! 230 | } 231 | 232 | Write-Debug "ConnectionString $($SQLiteConnection.ConnectionString)" 233 | Try 234 | { 235 | if($SQLiteConnection.State -notlike "Open") 236 | { 237 | $SQLiteConnection.Open() 238 | } 239 | $Command = $SQLiteConnection.CreateCommand() 240 | $CommandTimeout = $QueryTimeout 241 | $Transaction = $SQLiteConnection.BeginTransaction() 242 | } 243 | Catch 244 | { 245 | Throw $_ 246 | } 247 | 248 | write-verbose "DATATABLE IS $($DataTable.gettype().fullname) with value $($Datatable | out-string)" 249 | $RowCount = $Datatable.Rows.Count 250 | Write-Verbose "Processing datatable with $RowCount rows" 251 | 252 | if ($Force -or $PSCmdlet.ShouldProcess("$($DataTable.Rows.Count) rows, with BoundParameters $($PSBoundParameters | Out-String)", "SQL Bulk Copy")) 253 | { 254 | #Get column info... 255 | $Columns = $DataTable.Columns | Select -ExpandProperty ColumnName 256 | $ColumnTypeHash = @{} 257 | $ColumnToParamHash = @{} 258 | $Index = 0 259 | foreach($Col in $DataTable.Columns) 260 | { 261 | $Type = Switch -regex ($Col.DataType.FullName) 262 | { 263 | # I figure we create a hashtable, can act upon expected data when doing insert 264 | # Might be a better way to handle this... 265 | '^(|\ASystem\.)Boolean$' {"BOOLEAN"} #I know they're fake... 266 | '^(|\ASystem\.)Byte\[\]' {"BLOB"} 267 | '^(|\ASystem\.)Byte$' {"BLOB"} 268 | '^(|\ASystem\.)Datetime$' {"DATETIME"} 269 | '^(|\ASystem\.)Decimal$' {"REAL"} 270 | '^(|\ASystem\.)Double$' {"REAL"} 271 | '^(|\ASystem\.)Guid$' {"TEXT"} 272 | '^(|\ASystem\.)Int16$' {"INTEGER"} 273 | '^(|\ASystem\.)Int32$' {"INTEGER"} 274 | '^(|\ASystem\.)Int64$' {"INTEGER"} 275 | '^(|\ASystem\.)UInt16$' {"INTEGER"} 276 | '^(|\ASystem\.)UInt32$' {"INTEGER"} 277 | '^(|\ASystem\.)UInt64$' {"INTEGER"} 278 | '^(|\ASystem\.)Single$' {"REAL"} 279 | '^(|\ASystem\.)String$' {"TEXT"} 280 | Default {"BLOB"} #Let SQLite handle the rest... 281 | } 282 | 283 | #We ref columns by their index, so add that... 284 | $ColumnTypeHash.Add($Index,$Type) 285 | 286 | # Parameter names can only be alphanumeric: https://www.sqlite.org/c3ref/bind_blob.html 287 | # So we have to replace all non-alphanumeric chars in column name to use it as parameter later. 288 | # This builds hashtable to correlate column name with parameter name. 289 | $ColumnToParamHash.Add($Col.ColumnName, (Get-ParameterName $Col.ColumnName)) 290 | 291 | $Index++ 292 | } 293 | 294 | #Build up the query 295 | if ($PSBoundParameters.ContainsKey('ConflictClause')) 296 | { 297 | $Command.CommandText = New-SqliteBulkQuery -Table $Table -Columns $ColumnToParamHash.Keys -Parameters $ColumnToParamHash.Values -ConflictClause $ConflictClause 298 | } 299 | else 300 | { 301 | $Command.CommandText = New-SqliteBulkQuery -Table $Table -Columns $ColumnToParamHash.Keys -Parameters $ColumnToParamHash.Values 302 | } 303 | 304 | foreach ($Column in $Columns) 305 | { 306 | $param = New-Object System.Data.SQLite.SqLiteParameter $ColumnToParamHash[$Column] 307 | [void]$Command.Parameters.Add($param) 308 | } 309 | 310 | for ($RowNumber = 0; $RowNumber -lt $RowCount; $RowNumber++) 311 | { 312 | $row = $Datatable.Rows[$RowNumber] 313 | for($col = 0; $col -lt $Columns.count; $col++) 314 | { 315 | # Depending on the type of thid column, quote it 316 | # For dates, convert it to a string SQLite will recognize 317 | switch ($ColumnTypeHash[$col]) 318 | { 319 | "BOOLEAN" { 320 | $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = [int][boolean]$row[$col] 321 | } 322 | "DATETIME" { 323 | Try 324 | { 325 | $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = $row[$col].ToString("yyyy-MM-dd HH:mm:ss") 326 | } 327 | Catch 328 | { 329 | $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = $row[$col] 330 | } 331 | } 332 | Default { 333 | $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = $row[$col] 334 | } 335 | } 336 | } 337 | 338 | #We have the query, execute! 339 | Try 340 | { 341 | [void]$Command.ExecuteNonQuery() 342 | } 343 | Catch 344 | { 345 | #Minimal testing for this rollback... 346 | Write-Verbose "Rolling back due to error:`n$_" 347 | $Transaction.Rollback() 348 | 349 | #Clean up and throw an error 350 | CleanUp -conn $SQLiteConnection -com $Command -BoundParams $PSBoundParameters 351 | Throw "Rolled back due to error:`n$_" 352 | } 353 | 354 | if($NotifyAfter -gt 0 -and $($RowNumber % $NotifyAfter) -eq 0) 355 | { 356 | Write-Verbose "Processed $($RowNumber + 1) records" 357 | } 358 | } 359 | } 360 | 361 | #Commit the transaction and clean up the connection 362 | $Transaction.Commit() 363 | CleanUp -conn $SQLiteConnection -com $Command -BoundParams $PSBoundParameters 364 | 365 | } -------------------------------------------------------------------------------- /PSSQLite/Invoke-SqliteQuery.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-SqliteQuery { 2 | <# 3 | .SYNOPSIS 4 | Runs a SQL script against a SQLite database. 5 | 6 | .DESCRIPTION 7 | Runs a SQL script against a SQLite database. 8 | 9 | Paramaterized queries are supported. 10 | 11 | Help details below borrowed from Invoke-Sqlcmd, may be inaccurate here. 12 | 13 | .PARAMETER DataSource 14 | Path to one ore more SQLite data sources to query 15 | 16 | .PARAMETER Query 17 | Specifies a query to be run. 18 | 19 | .PARAMETER InputFile 20 | Specifies a file to be used as the query input to Invoke-SqliteQuery. Specify the full path to the file. 21 | 22 | .PARAMETER QueryTimeout 23 | Specifies the number of seconds before the queries time out. 24 | 25 | .PARAMETER As 26 | Specifies output type - DataSet, DataTable, array of DataRow, PSObject or Single Value 27 | 28 | PSObject output introduces overhead but adds flexibility for working with results: http://powershell.org/wp/forums/topic/dealing-with-dbnull/ 29 | 30 | .PARAMETER SqlParameters 31 | Hashtable of parameters for parameterized SQL queries. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/ 32 | 33 | Limited support for conversions to SQLite friendly formats is supported. 34 | For example, if you pass in a .NET DateTime, we convert it to a string that SQLite will recognize as a datetime 35 | 36 | Example: 37 | -Query "SELECT ServerName FROM tblServerInfo WHERE ServerName LIKE @ServerName" 38 | -SqlParameters @{"ServerName = "c-is-hyperv-1"} 39 | 40 | .PARAMETER SQLiteConnection 41 | An existing SQLiteConnection to use. We do not close this connection upon completed query. 42 | 43 | .PARAMETER AppendDataSource 44 | If specified, append the SQLite data source path to PSObject or DataRow output 45 | 46 | .INPUTS 47 | DataSource 48 | You can pipe DataSource paths to Invoke-SQLiteQuery. The query will execute against each Data Source. 49 | 50 | .OUTPUTS 51 | As PSObject: System.Management.Automation.PSCustomObject 52 | As DataRow: System.Data.DataRow 53 | As DataTable: System.Data.DataTable 54 | As DataSet: System.Data.DataTableCollectionSystem.Data.DataSet 55 | As SingleValue: Dependent on data type in first column. 56 | 57 | .EXAMPLE 58 | 59 | # 60 | # First, we create a database and a table 61 | $Query = "CREATE TABLE NAMES (fullname VARCHAR(20) PRIMARY KEY, surname TEXT, givenname TEXT, BirthDate DATETIME)" 62 | $Database = "C:\Names.SQLite" 63 | 64 | Invoke-SqliteQuery -Query $Query -DataSource $Database 65 | 66 | # We have a database, and a table, let's view the table info 67 | Invoke-SqliteQuery -DataSource $Database -Query "PRAGMA table_info(NAMES)" 68 | 69 | cid name type notnull dflt_value pk 70 | --- ---- ---- ------- ---------- -- 71 | 0 fullname VARCHAR(20) 0 1 72 | 1 surname TEXT 0 0 73 | 2 givenname TEXT 0 0 74 | 3 BirthDate DATETIME 0 0 75 | 76 | # Insert some data, use parameters for the fullname and birthdate 77 | $query = "INSERT INTO NAMES (fullname, surname, givenname, birthdate) VALUES (@full, 'Cookie', 'Monster', @BD)" 78 | Invoke-SqliteQuery -DataSource $Database -Query $query -SqlParameters @{ 79 | full = "Cookie Monster" 80 | BD = (get-date).addyears(-3) 81 | } 82 | 83 | # Check to see if we inserted the data: 84 | Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM NAMES" 85 | 86 | fullname surname givenname BirthDate 87 | -------- ------- --------- --------- 88 | Cookie Monster Cookie Monster 3/14/2012 12:27:13 PM 89 | 90 | # Insert another entry with too many characters in the fullname. 91 | # Illustrate that SQLite data types may be misleading: 92 | Invoke-SqliteQuery -DataSource $Database -Query $query -SqlParameters @{ 93 | full = "Cookie Monster$('!' * 20)" 94 | BD = (get-date).addyears(-3) 95 | } 96 | 97 | Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM NAMES" 98 | 99 | fullname surname givenname BirthDate 100 | -------- ------- --------- --------- 101 | Cookie Monster Cookie Monster 3/14/2012 12:27:13 PM 102 | Cookie Monster![...]! Cookie Monster 3/14/2012 12:29:32 PM 103 | 104 | .EXAMPLE 105 | Invoke-SqliteQuery -DataSource C:\NAMES.SQLite -Query "SELECT * FROM NAMES" -AppendDataSource 106 | 107 | fullname surname givenname BirthDate Database 108 | -------- ------- --------- --------- -------- 109 | Cookie Monster Cookie Monster 3/14/2012 12:55:55 PM C:\Names.SQLite 110 | 111 | # Append Database column (path) to each result 112 | 113 | .EXAMPLE 114 | Invoke-SqliteQuery -DataSource C:\Names.SQLite -InputFile C:\Query.sql 115 | 116 | # Invoke SQL from an input file 117 | 118 | .EXAMPLE 119 | $Connection = New-SQLiteConnection -DataSource :MEMORY: 120 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "CREATE TABLE OrdersToNames (OrderID INT PRIMARY KEY, fullname TEXT);" 121 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID, fullname) VALUES (1,'Cookie Monster');" 122 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" 123 | 124 | # Execute a query against an existing SQLiteConnection 125 | # Create a connection to a SQLite data source in memory 126 | # Create a table in the memory based datasource, verify it exists with PRAGMA STATS 127 | 128 | .EXAMPLE 129 | $Connection = New-SQLiteConnection -DataSource :MEMORY: 130 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "CREATE TABLE OrdersToNames (OrderID INT PRIMARY KEY, fullname TEXT);" 131 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID, fullname) VALUES (1,'Cookie Monster');" 132 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID) VALUES (2);" 133 | 134 | # We now have two entries, only one has a fullname. Despite this, the following command returns both; very un-PowerShell! 135 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "SELECT * FROM OrdersToNames" -As DataRow | Where{$_.fullname} 136 | 137 | OrderID fullname 138 | ------- -------- 139 | 1 Cookie Monster 140 | 2 141 | 142 | # Using the default -As PSObject, we can get PowerShell-esque behavior: 143 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "SELECT * FROM OrdersToNames" | Where{$_.fullname} 144 | 145 | OrderID fullname 146 | ------- -------- 147 | 1 Cookie Monster 148 | 149 | .LINK 150 | https://github.com/RamblingCookieMonster/Invoke-SQLiteQuery 151 | 152 | .LINK 153 | New-SQLiteConnection 154 | 155 | .LINK 156 | Invoke-SQLiteBulkCopy 157 | 158 | .LINK 159 | Out-DataTable 160 | 161 | .LINK 162 | https://www.sqlite.org/datatype3.html 163 | 164 | .LINK 165 | https://www.sqlite.org/lang.html 166 | 167 | .LINK 168 | http://www.sqlite.org/pragma.html 169 | 170 | .FUNCTIONALITY 171 | SQL 172 | #> 173 | 174 | [CmdletBinding( DefaultParameterSetName='Src-Que' )] 175 | [OutputType([System.Management.Automation.PSCustomObject],[System.Data.DataRow],[System.Data.DataTable],[System.Data.DataTableCollection],[System.Data.DataSet])] 176 | param( 177 | [Parameter( ParameterSetName='Src-Que', 178 | Position=0, 179 | Mandatory=$true, 180 | ValueFromPipeline=$true, 181 | ValueFromPipelineByPropertyName=$true, 182 | ValueFromRemainingArguments=$false, 183 | HelpMessage='SQLite Data Source required...' )] 184 | [Parameter( ParameterSetName='Src-Fil', 185 | Position=0, 186 | Mandatory=$true, 187 | ValueFromPipeline=$true, 188 | ValueFromPipelineByPropertyName=$true, 189 | ValueFromRemainingArguments=$false, 190 | HelpMessage='SQLite Data Source required...' )] 191 | [Alias('Path','File','FullName','Database')] 192 | [validatescript({ 193 | #This should match memory, or the parent path should exist 194 | $Parent = Split-Path $_ -Parent 195 | if( 196 | $_ -match ":MEMORY:|^WHAT$" -or 197 | ( $Parent -and (Test-Path $Parent)) 198 | ){ 199 | $True 200 | } 201 | else { 202 | Throw "Invalid datasource '$_'.`nThis must match :MEMORY:, or '$Parent' must exist" 203 | } 204 | })] 205 | [string[]] 206 | $DataSource, 207 | 208 | [Parameter( ParameterSetName='Src-Que', 209 | Position=1, 210 | Mandatory=$true, 211 | ValueFromPipelineByPropertyName=$true, 212 | ValueFromRemainingArguments=$false )] 213 | [Parameter( ParameterSetName='Con-Que', 214 | Position=1, 215 | Mandatory=$true, 216 | ValueFromPipelineByPropertyName=$true, 217 | ValueFromRemainingArguments=$false )] 218 | [string] 219 | $Query, 220 | 221 | [Parameter( ParameterSetName='Src-Fil', 222 | Position=1, 223 | Mandatory=$true, 224 | ValueFromPipelineByPropertyName=$true, 225 | ValueFromRemainingArguments=$false )] 226 | [Parameter( ParameterSetName='Con-Fil', 227 | Position=1, 228 | Mandatory=$true, 229 | ValueFromPipelineByPropertyName=$true, 230 | ValueFromRemainingArguments=$false )] 231 | [ValidateScript({ Test-Path $_ })] 232 | [string] 233 | $InputFile, 234 | 235 | [Parameter( Position=2, 236 | Mandatory=$false, 237 | ValueFromPipelineByPropertyName=$true, 238 | ValueFromRemainingArguments=$false )] 239 | [Int32] 240 | $QueryTimeout=600, 241 | 242 | [Parameter( Position=3, 243 | Mandatory=$false, 244 | ValueFromPipelineByPropertyName=$true, 245 | ValueFromRemainingArguments=$false )] 246 | [ValidateSet("DataSet", "DataTable", "DataRow","PSObject","SingleValue")] 247 | [string] 248 | $As="PSObject", 249 | 250 | [Parameter( Position=4, 251 | Mandatory=$false, 252 | ValueFromPipelineByPropertyName=$true, 253 | ValueFromRemainingArguments=$false )] 254 | [System.Collections.IDictionary] 255 | $SqlParameters, 256 | 257 | [Parameter( Position=5, 258 | Mandatory=$false )] 259 | [switch] 260 | $AppendDataSource, 261 | 262 | [Parameter( Position=6, 263 | Mandatory=$false )] 264 | [validatescript({Test-Path $_ })] 265 | [string]$AssemblyPath = $SQLiteAssembly, 266 | 267 | [Parameter( ParameterSetName = 'Con-Que', 268 | Position=7, 269 | Mandatory=$true, 270 | ValueFromPipeline=$false, 271 | ValueFromPipelineByPropertyName=$true, 272 | ValueFromRemainingArguments=$false )] 273 | [Parameter( ParameterSetName = 'Con-Fil', 274 | Position=7, 275 | Mandatory=$true, 276 | ValueFromPipeline=$false, 277 | ValueFromPipelineByPropertyName=$true, 278 | ValueFromRemainingArguments=$false )] 279 | [Alias( 'Connection', 'Conn' )] 280 | [System.Data.SQLite.SQLiteConnection] 281 | $SQLiteConnection 282 | ) 283 | 284 | Begin 285 | { 286 | #Assembly, should already be covered by psm1 287 | Try 288 | { 289 | [void][System.Data.SQLite.SQLiteConnection] 290 | } 291 | Catch 292 | { 293 | if( -not ($Library = Add-Type -path $SQLiteAssembly -PassThru -ErrorAction stop) ) 294 | { 295 | Throw "This module requires the ADO.NET driver for SQLite:`n`thttp://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki" 296 | } 297 | } 298 | 299 | if ($InputFile) 300 | { 301 | $filePath = $(Resolve-Path $InputFile).path 302 | $Query = [System.IO.File]::ReadAllText("$filePath") 303 | } 304 | 305 | Write-Verbose "Running Invoke-SQLiteQuery with ParameterSet '$($PSCmdlet.ParameterSetName)'. Performing query '$Query'" 306 | 307 | If($As -eq "PSObject") 308 | { 309 | #This code scrubs DBNulls. Props to Dave Wyatt 310 | $cSharp = @' 311 | using System; 312 | using System.Data; 313 | using System.Management.Automation; 314 | 315 | public class DBNullScrubber 316 | { 317 | public static PSObject DataRowToPSObject(DataRow row) 318 | { 319 | PSObject psObject = new PSObject(); 320 | 321 | if (row != null && (row.RowState & DataRowState.Detached) != DataRowState.Detached) 322 | { 323 | foreach (DataColumn column in row.Table.Columns) 324 | { 325 | Object value = null; 326 | if (!row.IsNull(column)) 327 | { 328 | value = row[column]; 329 | } 330 | 331 | psObject.Properties.Add(new PSNoteProperty(column.ColumnName, value)); 332 | } 333 | } 334 | 335 | return psObject; 336 | } 337 | } 338 | '@ 339 | 340 | Try 341 | { 342 | Add-Type -TypeDefinition $cSharp -ReferencedAssemblies 'System.Data','System.Xml' -ErrorAction stop 343 | } 344 | Catch 345 | { 346 | If(-not $_.ToString() -like "*The type name 'DBNullScrubber' already exists*") 347 | { 348 | Write-Warning "Could not load DBNullScrubber. Defaulting to DataRow output: $_" 349 | $As = "Datarow" 350 | } 351 | } 352 | } 353 | 354 | #Handle existing connections 355 | if($PSBoundParameters.Keys -contains "SQLiteConnection") 356 | { 357 | if($SQLiteConnection.State -notlike "Open") 358 | { 359 | Try 360 | { 361 | $SQLiteConnection.Open() 362 | } 363 | Catch 364 | { 365 | Throw $_ 366 | } 367 | } 368 | 369 | if($SQLiteConnection.state -notlike "Open") 370 | { 371 | Throw "SQLiteConnection is not open:`n$($SQLiteConnection | Out-String)" 372 | } 373 | 374 | $DataSource = @("WHAT") 375 | } 376 | } 377 | Process 378 | { 379 | foreach($DB in $DataSource) 380 | { 381 | 382 | if($PSBoundParameters.Keys -contains "SQLiteConnection") 383 | { 384 | $Conn = $SQLiteConnection 385 | } 386 | else 387 | { 388 | if(Test-Path $DB) 389 | { 390 | Write-Verbose "Querying existing Data Source '$DB'" 391 | } 392 | else 393 | { 394 | Write-Verbose "Creating andn querying Data Source '$DB'" 395 | } 396 | 397 | $ConnectionString = "Data Source={0}" -f $DB 398 | 399 | $conn = New-Object System.Data.SQLite.SQLiteConnection -ArgumentList $ConnectionString 400 | $conn.ParseViaFramework = $true #Allow UNC paths, thanks to Ray Alex! 401 | Write-Debug "ConnectionString $ConnectionString" 402 | 403 | Try 404 | { 405 | $conn.Open() 406 | } 407 | Catch 408 | { 409 | Write-Error $_ 410 | continue 411 | } 412 | } 413 | 414 | $cmd = $Conn.CreateCommand() 415 | $cmd.CommandText = $Query 416 | $cmd.CommandTimeout = $QueryTimeout 417 | 418 | if ($SqlParameters -ne $null) 419 | { 420 | $SqlParameters.GetEnumerator() | 421 | ForEach-Object { 422 | If ($_.Value -ne $null) 423 | { 424 | if($_.Value -is [datetime]) { $_.Value = $_.Value.ToString("yyyy-MM-dd HH:mm:ss") } 425 | $cmd.Parameters.AddWithValue("@$($_.Key)", $_.Value) 426 | } 427 | Else 428 | { 429 | $cmd.Parameters.AddWithValue("@$($_.Key)", [DBNull]::Value) 430 | } 431 | } > $null 432 | } 433 | 434 | $ds = New-Object system.Data.DataSet 435 | $da = New-Object System.Data.SQLite.SQLiteDataAdapter($cmd) 436 | 437 | Try 438 | { 439 | [void]$da.fill($ds) 440 | if($PSBoundParameters.Keys -notcontains "SQLiteConnection") 441 | { 442 | $conn.Close() 443 | } 444 | $cmd.Dispose() 445 | } 446 | Catch 447 | { 448 | $Err = $_ 449 | if($PSBoundParameters.Keys -notcontains "SQLiteConnection") 450 | { 451 | $conn.Close() 452 | } 453 | switch ($ErrorActionPreference.tostring()) 454 | { 455 | {'SilentlyContinue','Ignore' -contains $_} {} 456 | 'Stop' { Throw $Err } 457 | 'Continue' { Write-Error $Err} 458 | Default { Write-Error $Err} 459 | } 460 | } 461 | 462 | if($AppendDataSource) 463 | { 464 | #Basics from Chad Miller 465 | $Column = New-Object Data.DataColumn 466 | $Column.ColumnName = "Datasource" 467 | $ds.Tables[0].Columns.Add($Column) 468 | 469 | Try 470 | { 471 | #Someone better at regular expression, feel free to tackle this 472 | $Conn.ConnectionString -match "Data Source=(?.*);" 473 | $Datasrc = $Matches.DataSource.split(";")[0] 474 | } 475 | Catch 476 | { 477 | $Datasrc = $DB 478 | } 479 | 480 | Foreach($row in $ds.Tables[0]) 481 | { 482 | $row.Datasource = $Datasrc 483 | } 484 | } 485 | 486 | switch ($As) 487 | { 488 | 'DataSet' 489 | { 490 | $ds 491 | } 492 | 'DataTable' 493 | { 494 | $ds.Tables 495 | } 496 | 'DataRow' 497 | { 498 | $ds.Tables[0] 499 | } 500 | 'PSObject' 501 | { 502 | #Scrub DBNulls - Provides convenient results you can use comparisons with 503 | #Introduces overhead (e.g. ~2000 rows w/ ~80 columns went from .15 Seconds to .65 Seconds - depending on your data could be much more!) 504 | foreach ($row in $ds.Tables[0].Rows) 505 | { 506 | [DBNullScrubber]::DataRowToPSObject($row) 507 | } 508 | } 509 | 'SingleValue' 510 | { 511 | $ds.Tables[0] | Select-Object -ExpandProperty $ds.Tables[0].Columns[0].ColumnName 512 | } 513 | } 514 | } 515 | } 516 | } -------------------------------------------------------------------------------- /PSSQLite/New-SqliteConnection.ps1: -------------------------------------------------------------------------------- 1 | function New-SQLiteConnection 2 | { 3 | <# 4 | .SYNOPSIS 5 | Creates a SQLiteConnection to a SQLite data source 6 | 7 | .DESCRIPTION 8 | Creates a SQLiteConnection to a SQLite data source 9 | 10 | .PARAMETER DataSource 11 | SQLite Data Source to connect to. 12 | 13 | .PARAMETER Password 14 | Specifies A Secure String password to use in the SQLite connection string. 15 | 16 | SECURITY NOTE: If you use the -Debug switch, the connectionstring including plain text password will be sent to the debug stream. 17 | 18 | .PARAMETER ReadOnly 19 | If specified, open SQLite data source as read only 20 | 21 | .PARAMETER Open 22 | We open the connection by default. You can use this parameter to create a connection without opening it. 23 | 24 | .OUTPUTS 25 | System.Data.SQLite.SQLiteConnection 26 | 27 | .EXAMPLE 28 | $Connection = New-SQLiteConnection -DataSource C:\NAMES.SQLite 29 | Invoke-SQLiteQuery -SQLiteConnection $Connection -query $Query 30 | 31 | # Connect to C:\NAMES.SQLite, invoke a query against it 32 | 33 | .EXAMPLE 34 | $Connection = New-SQLiteConnection -DataSource :MEMORY: 35 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "CREATE TABLE OrdersToNames (OrderID INT PRIMARY KEY, fullname TEXT);" 36 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID, fullname) VALUES (1,'Cookie Monster');" 37 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" 38 | 39 | # Create a connection to a SQLite data source in memory 40 | # Create a table in the memory based datasource, verify it exists with PRAGMA STATS 41 | 42 | $Connection.Close() 43 | $Connection.Open() 44 | Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" 45 | 46 | #Close the connection, open it back up, verify that the ephemeral data no longer exists 47 | 48 | .LINK 49 | https://github.com/RamblingCookieMonster/Invoke-SQLiteQuery 50 | 51 | .LINK 52 | Invoke-SQLiteQuery 53 | 54 | .FUNCTIONALITY 55 | SQL 56 | 57 | #> 58 | [cmdletbinding()] 59 | [OutputType([System.Data.SQLite.SQLiteConnection])] 60 | param( 61 | [Parameter( Position=0, 62 | Mandatory=$true, 63 | ValueFromPipeline=$true, 64 | ValueFromPipelineByPropertyName=$true, 65 | ValueFromRemainingArguments=$false, 66 | HelpMessage='SQL Server Instance required...' )] 67 | [Alias( 'Instance', 'Instances', 'ServerInstance', 'Server', 'Servers','cn','Path','File','FullName','Database' )] 68 | [ValidateNotNullOrEmpty()] 69 | [string[]] 70 | $DataSource, 71 | 72 | [Parameter( Position=2, 73 | Mandatory=$false, 74 | ValueFromPipelineByPropertyName=$true, 75 | ValueFromRemainingArguments=$false )] 76 | [System.Security.SecureString] 77 | $Password, 78 | 79 | [Parameter( Position=3, 80 | Mandatory=$false, 81 | ValueFromPipelineByPropertyName=$true, 82 | ValueFromRemainingArguments=$false )] 83 | [Switch] 84 | $ReadOnly, 85 | 86 | [Parameter( Position=4, 87 | Mandatory=$false, 88 | ValueFromPipelineByPropertyName=$true, 89 | ValueFromRemainingArguments=$false )] 90 | [bool] 91 | $Open = $True 92 | ) 93 | Process 94 | { 95 | foreach($DataSRC in $DataSource) 96 | { 97 | Write-Verbose "Querying Data Source '$DataSRC'" 98 | [string]$ConnectionString = "Data Source=$DataSRC;" 99 | if ($Password) 100 | { 101 | $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) 102 | $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) 103 | $ConnectionString += "Password=$PlainPassword;" 104 | } 105 | if($ReadOnly) 106 | { 107 | $ConnectionString += "Read Only=True;" 108 | } 109 | 110 | $conn = New-Object System.Data.SQLite.SQLiteConnection -ArgumentList $ConnectionString 111 | $conn.ParseViaFramework = $true #Allow UNC paths, thanks to Ray Alex! 112 | Write-Debug "ConnectionString $ConnectionString" 113 | 114 | if($Open) 115 | { 116 | Try 117 | { 118 | $conn.Open() 119 | } 120 | Catch 121 | { 122 | Write-Error $_ 123 | continue 124 | } 125 | } 126 | 127 | write-Verbose "Created SQLiteConnection:`n$($Conn | Out-String)" 128 | 129 | $Conn 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /PSSQLite/Out-DataTable.ps1: -------------------------------------------------------------------------------- 1 | function Out-DataTable 2 | { 3 | <# 4 | .SYNOPSIS 5 | Creates a DataTable for an object 6 | 7 | .DESCRIPTION 8 | Creates a DataTable based on an object's properties. 9 | 10 | .PARAMETER InputObject 11 | One or more objects to convert into a DataTable 12 | 13 | .PARAMETER NonNullable 14 | A list of columns to set disable AllowDBNull on 15 | 16 | .INPUTS 17 | Object 18 | Any object can be piped to Out-DataTable 19 | 20 | .OUTPUTS 21 | System.Data.DataTable 22 | 23 | .EXAMPLE 24 | $dt = Get-psdrive | Out-DataTable 25 | 26 | # This example creates a DataTable from the properties of Get-psdrive and assigns output to $dt variable 27 | 28 | .EXAMPLE 29 | Get-Process | Select Name, CPU | Out-DataTable | Invoke-SQLBulkCopy -ServerInstance $SQLInstance -Database $Database -Table $SQLTable -force -verbose 30 | 31 | # Get a list of processes and their CPU, create a datatable, bulk import that data 32 | 33 | .NOTES 34 | Adapted from script by Marc van Orsouw and function from Chad Miller 35 | Version History 36 | v1.0 - Chad Miller - Initial Release 37 | v1.1 - Chad Miller - Fixed Issue with Properties 38 | v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0 39 | v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties 40 | v1.4 - Chad Miller - Corrected issue with DBNull 41 | v1.5 - Chad Miller - Updated example 42 | v1.6 - Chad Miller - Added column datatype logic with default to string 43 | v1.7 - Chad Miller - Fixed issue with IsArray 44 | v1.8 - ramblingcookiemonster - Removed if($Value) logic. This would not catch empty strings, zero, $false and other non-null items 45 | - Added perhaps pointless error handling 46 | 47 | .LINK 48 | https://github.com/RamblingCookieMonster/PowerShell 49 | 50 | .LINK 51 | Invoke-SQLBulkCopy 52 | 53 | .LINK 54 | Invoke-Sqlcmd2 55 | 56 | .LINK 57 | New-SQLConnection 58 | 59 | .FUNCTIONALITY 60 | SQL 61 | #> 62 | [CmdletBinding()] 63 | [OutputType([System.Data.DataTable])] 64 | param( 65 | [Parameter( Position=0, 66 | Mandatory=$true, 67 | ValueFromPipeline = $true)] 68 | [PSObject[]]$InputObject, 69 | 70 | [string[]]$NonNullable = @() 71 | ) 72 | 73 | Begin 74 | { 75 | $dt = New-Object Data.datatable 76 | $First = $true 77 | 78 | function Get-ODTType 79 | { 80 | param($type) 81 | 82 | $types = @( 83 | 'System.Boolean', 84 | 'System.Byte[]', 85 | 'System.Byte', 86 | 'System.Char', 87 | 'System.Datetime', 88 | 'System.Decimal', 89 | 'System.Double', 90 | 'System.Guid', 91 | 'System.Int16', 92 | 'System.Int32', 93 | 'System.Int64', 94 | 'System.Single', 95 | 'System.UInt16', 96 | 'System.UInt32', 97 | 'System.UInt64') 98 | 99 | if ( $types -contains $type ) { 100 | Write-Output "$type" 101 | } 102 | else { 103 | Write-Output 'System.String' 104 | } 105 | } #Get-Type 106 | } 107 | Process 108 | { 109 | foreach ($Object in $InputObject) 110 | { 111 | $DR = $DT.NewRow() 112 | foreach ($Property in $Object.PsObject.Properties) 113 | { 114 | $Name = $Property.Name 115 | $Value = $Property.Value 116 | 117 | #RCM: what if the first property is not reflective of all the properties? Unlikely, but... 118 | if ($First) 119 | { 120 | $Col = New-Object Data.DataColumn 121 | $Col.ColumnName = $Name 122 | 123 | #If it's not DBNull or Null, get the type 124 | if ($Value -isnot [System.DBNull] -and $Value -ne $null) 125 | { 126 | $Col.DataType = [System.Type]::GetType( $(Get-ODTType $property.TypeNameOfValue) ) 127 | } 128 | 129 | #Set it to nonnullable if specified 130 | if ($NonNullable -contains $Name ) 131 | { 132 | $col.AllowDBNull = $false 133 | } 134 | 135 | try 136 | { 137 | $DT.Columns.Add($Col) 138 | } 139 | catch 140 | { 141 | Write-Error "Could not add column $($Col | Out-String) for property '$Name' with value '$Value' and type '$($Value.GetType().FullName)':`n$_" 142 | } 143 | } 144 | 145 | Try 146 | { 147 | #Handle arrays and nulls 148 | if ($property.GetType().IsArray) 149 | { 150 | $DR.Item($Name) = $Value | ConvertTo-XML -As String -NoTypeInformation -Depth 1 151 | } 152 | elseif($Value -eq $null) 153 | { 154 | $DR.Item($Name) = [DBNull]::Value 155 | } 156 | else 157 | { 158 | $DR.Item($Name) = $Value 159 | } 160 | } 161 | Catch 162 | { 163 | Write-Error "Could not add property '$Name' with value '$Value' and type '$($Value.GetType().FullName)'" 164 | continue 165 | } 166 | 167 | #Did we get a null or dbnull for a non-nullable item? let the user know. 168 | if($NonNullable -contains $Name -and ($Value -is [System.DBNull] -or $Value -eq $null)) 169 | { 170 | write-verbose "NonNullable property '$Name' with null value found: $($object | out-string)" 171 | } 172 | 173 | } 174 | 175 | Try 176 | { 177 | $DT.Rows.Add($DR) 178 | } 179 | Catch 180 | { 181 | Write-Error "Failed to add row '$($DR | Out-String)':`n$_" 182 | } 183 | 184 | $First = $false 185 | } 186 | } 187 | 188 | End 189 | { 190 | Write-Output @(,$dt) 191 | } 192 | 193 | } #Out-DataTable -------------------------------------------------------------------------------- /PSSQLite/PSSQLite.psd1: -------------------------------------------------------------------------------- 1 | @{ 2 | 3 | # Script module or binary module file associated with this manifest. 4 | ModuleToProcess = 'PSSQLite.psm1' 5 | 6 | # Version number of this module. 7 | ModuleVersion = '1.0.1' 8 | 9 | # ID used to uniquely identify this module 10 | GUID = '381f3394-9b8a-492e-94b4-b3aa9e775761' 11 | 12 | # Author of this module 13 | Author = 'ramblingcookiemonster' 14 | 15 | # Company or vendor of this module 16 | CompanyName = '' 17 | 18 | # Copyright statement for this module 19 | # Copyright = '(c) 2014 ramblingcookiemonster. All rights reserved.' 20 | 21 | # Description of the functionality provided by this module 22 | Description = 'Query SQLite databases' 23 | 24 | # Minimum version of the Windows PowerShell engine required by this module 25 | PowerShellVersion = '2.0' 26 | 27 | # Name of the Windows PowerShell host required by this module 28 | # PowerShellHostName = '' 29 | 30 | # Minimum version of the Windows PowerShell host required by this module 31 | # PowerShellHostVersion = '' 32 | 33 | # Minimum version of Microsoft .NET Framework required by this module 34 | # DotNetFrameworkVersion = '' 35 | 36 | # Minimum version of the common language runtime (CLR) required by this module 37 | # CLRVersion = '' 38 | 39 | # Processor architecture (None, X86, Amd64) required by this module 40 | # ProcessorArchitecture = '' 41 | 42 | # Modules that must be imported into the global environment prior to importing this module 43 | # RequiredModules = @() 44 | 45 | # Assemblies that must be loaded prior to importing this module 46 | # RequiredAssemblies = @() 47 | 48 | # Script files (.ps1) that are run in the caller's environment prior to importing this module. 49 | # ScriptsToProcess = @() 50 | 51 | # Type files (.ps1xml) to be loaded when importing this module 52 | # TypesToProcess = @() 53 | 54 | # Format files (.ps1xml) to be loaded when importing this module 55 | # FormatsToProcess = @() 56 | 57 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 58 | # NestedModules = @() 59 | 60 | # Functions to export from this module 61 | # FunctionsToExport = '*' 62 | 63 | # Cmdlets to export from this module 64 | # CmdletsToExport = '*' 65 | 66 | # Variables to export from this module 67 | # VariablesToExport = '*' 68 | 69 | # Aliases to export from this module 70 | # AliasesToExport = '*' 71 | 72 | # List of all modules packaged with this module 73 | # ModuleList = @() 74 | 75 | # List of all files packaged with this module 76 | # FileList = @() 77 | 78 | # Private data to pass to the module specified in RootModule/ModuleToProcess 79 | # PrivateData = '' 80 | 81 | # HelpInfo URI of this module 82 | # HelpInfoURI = '' 83 | 84 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 85 | # DefaultCommandPrefix = '' 86 | 87 | } 88 | 89 | -------------------------------------------------------------------------------- /PSSQLite/PSSQLite.psm1: -------------------------------------------------------------------------------- 1 | #handle PS2 2 | if(-not $PSScriptRoot) 3 | { 4 | $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent 5 | } 6 | 7 | #Pick and import assemblies: 8 | if([IntPtr]::size -eq 8) #64 9 | { 10 | $SQLiteAssembly = Join-path $PSScriptRoot "x64\System.Data.SQLite.dll" 11 | } 12 | elseif([IntPtr]::size -eq 4) #32 13 | { 14 | $SQLiteAssembly = Join-path $PSScriptRoot "x86\System.Data.SQLite.dll" 15 | } 16 | else 17 | { 18 | Throw "Something is odd with bitness..." 19 | } 20 | 21 | if( -not ($Library = Add-Type -path $SQLiteAssembly -PassThru -ErrorAction stop) ) 22 | { 23 | Throw "This module requires the ADO.NET driver for SQLite:`n`thttp://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki" 24 | } 25 | 26 | #Get public and private function definition files. 27 | $Public = Get-ChildItem $PSScriptRoot\*.ps1 -ErrorAction SilentlyContinue 28 | #$Private = Get-ChildItem $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue 29 | 30 | #Dot source the files 31 | Foreach($import in @($Public)) 32 | { 33 | Try 34 | { 35 | #PS2 compatibility 36 | if($import.fullname) 37 | { 38 | . $import.fullname 39 | } 40 | } 41 | Catch 42 | { 43 | Write-Error "Failed to import function $($import.fullname): $_" 44 | } 45 | } 46 | 47 | #Create some aliases, export public functions 48 | Export-ModuleMember -Function $($Public | Select -ExpandProperty BaseName) -------------------------------------------------------------------------------- /PSSQLite/x64/SQLite.Interop.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/PSSQLite/x64/SQLite.Interop.dll -------------------------------------------------------------------------------- /PSSQLite/x64/System.Data.SQLite.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/PSSQLite/x64/System.Data.SQLite.dll -------------------------------------------------------------------------------- /PSSQLite/x86/SQLite.Interop.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/PSSQLite/x86/SQLite.Interop.dll -------------------------------------------------------------------------------- /PSSQLite/x86/System.Data.SQLite.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/PSSQLite/x86/System.Data.SQLite.dll -------------------------------------------------------------------------------- /PoSh-R2.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | PoSH-R2 is a set of Windows Management Instrumentation interface (WMI) scripts that investigators and forensic analysts can use to retrieve information from a 4 | compromised (or potentially compromised) Windows system. The scripts use WMI to pull this information from the operating system. Therefore, this script 5 | will need to be executed with a user that has the necessary privileges. 6 | 7 | PoSH-R2 will retrieve the following data from an individual machine or a group of systems: 8 | - Autorun entries 9 | - Disk info 10 | - Environment variables 11 | - Event logs (50 latest) 12 | - Installed Software (Warning: https://gregramsey.net/2012/02/20/win32_product-is-evil/) 13 | - Logon sessions 14 | - List of drivers 15 | - List of mapped network drives 16 | - List of running processes 17 | - Logged in user 18 | - Local groups 19 | - Local user accounts 20 | - Network configuration 21 | - Network connections 22 | - Patches 23 | - Scheduled tasks with AT command 24 | - Shares 25 | - Services 26 | - System Information 27 | 28 | .EXAMPLE 29 | .\posh_r2.ps1 30 | 31 | .NOTES 32 | File Name : PoSH-R2.ps1 33 | Version : v.0.2 34 | Author : @WiredPulse 35 | Prerequisite : PowerShell 36 | Created : 10 Oct 16 37 | #> 38 | Clear-Host 39 | 40 | Import-Module "$PSScriptRoot\PSSQLite\PSSQLite.psd1" 41 | 42 | Function ListComputers{ 43 | $DN = "" 44 | $Response = "" 45 | $DNSName = "" 46 | $DNSArray = "" 47 | $objSearcher = "" 48 | $colProplist = "" 49 | $objComputer = "" 50 | $objResults = "" 51 | $colResults = "" 52 | $Computer = "" 53 | $comp = "" 54 | New-Item -type file -force "$Script:Folder_Path\Computer_List_$Script:curDate.txt" | Out-Null 55 | $Script:Compute = "$Script:Folder_Path\Computer_List_$Script:curDate.txt" 56 | $strCategory = "(ObjectCategory=Computer)" 57 | 58 | Write-Host "Would you like to automatically pull from your domain or provide your own domain?" 59 | Write-Host "Auto pull uses the current domain you are on, if you need to select a different domain use manual." 60 | $response = Read-Host = "[1] Auto Pull, [2] Manual Selection" 61 | 62 | If($Response -eq "1") { 63 | $DNSName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name 64 | If($DNSName -ne $Null) { 65 | $DNSArray = $DNSName.Split(".") 66 | for ($x = 0; $x -lt $DNSArray.Length ; $x++) { 67 | if ($x -eq ($DNSArray.Length - 1)){$Separator = ""}else{$Separator =","} 68 | [string]$DN += "DC=" + $DNSArray[$x] + $Separator } } 69 | $Script:Domain = $DN 70 | echo "Pulled computers from: "$Script:Domain 71 | $objSearcher = New-Object System.DirectoryServices.DirectorySearcher("LDAP://$Script:Domain") 72 | $objSearcher.Filter = $strCategory 73 | $objSearcher.PageSize = 100000 74 | $objSearcher.SearchScope = "SubTree" 75 | $colProplist = "name" 76 | foreach ($i in $colPropList) { 77 | $objSearcher.propertiesToLoad.Add($i) } 78 | $colResults = $objSearcher.FindAll() 79 | foreach ($objResult in $colResults) { 80 | $objComputer = $objResult.Properties 81 | $comp = $objComputer.name 82 | echo $comp | Out-File $Script:Compute -Append } 83 | $Script:Computers = (Get-Content $Script:Compute) | Sort-Object 84 | } 85 | elseif($Response -eq "2") 86 | { 87 | Write-Host "Would you like to automatically pull from your domain or provide your own domain?" 88 | Write-Host "Auto pull uses the current domain you are on, if you need to select a different domain use manual." 89 | $Script:Domain = Read-Host "Enter your Domain here: OU=West,DC=Company,DC=com" 90 | If ($Script:Domain -eq $Null) {Write-Host "You did not provide a valid response."; . ListComputers} 91 | echo "Pulled computers from: "$Script:Domain 92 | $objOU = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$Script:Domain") 93 | $objSearcher = New-Object System.DirectoryServices.DirectorySearcher 94 | $objSearcher.SearchRoot = $objOU 95 | $objSearcher.Filter = $strCategory 96 | $objSearcher.PageSize = 100000 97 | $objSearcher.SearchScope = "SubTree" 98 | $colProplist = "name" 99 | foreach ($i in $colPropList) { $objSearcher.propertiesToLoad.Add($i) } 100 | $colResults = $objSearcher.FindAll() 101 | foreach ($objResult in $colResults) { 102 | $objComputer = $objResult.Properties 103 | $comp = $objComputer.name 104 | echo $comp | Out-File $Script:Compute -Append } 105 | $Script:Computers = (Get-Content $Script:Compute) | Sort-Object 106 | } 107 | else { 108 | Write-Host "You did not supply a correct response, Please select a response." -foregroundColor Red 109 | . ListComputers } 110 | } 111 | 112 | Function ListTextFile{ 113 | $file_Dialog = "" 114 | $file_Name = "" 115 | [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null 116 | $file_Dialog = New-Object system.windows.forms.openfiledialog 117 | $file_Dialog.InitialDirectory = "$env:USERPROFILE\Desktop" 118 | $file_Dialog.MultiSelect = $false 119 | $file_Dialog.showdialog() 120 | $file_Name = $file_Dialog.filename 121 | $Comps = Get-Content $file_Name 122 | If ($Comps -eq $Null) { 123 | Write-Host "Your file was empty. You must select a file with at least one computer in it." -Fore Red 124 | . ListTextFile } 125 | Else 126 | { 127 | $Script:Computers = @() 128 | ForEach ($Comp in $Comps) 129 | { 130 | If ($Comp -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}") 131 | { 132 | $Temp = $Comp.Split("/") 133 | $IP = $Temp[0] 134 | $Mask = $Temp[1] 135 | . Get-Subnet-Range $IP $Mask 136 | $Script:Computers += $Script:IPList 137 | } 138 | Else 139 | { 140 | $Script:Computers += $Comp 141 | } 142 | } 143 | 144 | 145 | } 146 | } 147 | 148 | Function Get-Subnet-Range { 149 | Param( 150 | [string] 151 | $IP, 152 | [string] 153 | $netmask 154 | ) 155 | Begin { 156 | $IPs = New-Object System.Collections.ArrayList 157 | 158 | Function Get-NetworkAddress { 159 | Param ( 160 | [string] 161 | $IP, 162 | 163 | [string] 164 | $Mask, 165 | 166 | [switch] 167 | $Binary 168 | ) 169 | Begin { 170 | $NetAdd = $null 171 | } 172 | Process { 173 | $BinaryIP = ConvertTo-BinaryIP $IP 174 | $BinaryMask = ConvertTo-BinaryIP $Mask 175 | 0..34 | %{ 176 | $IPBit = $BinaryIP.Substring($_,1) 177 | $MaskBit = $BinaryMask.Substring($_,1) 178 | IF ($IPBit -eq '1' -and $MaskBit -eq '1') { 179 | $NetAdd = $NetAdd + "1" 180 | } elseif ($IPBit -eq ".") { 181 | $NetAdd = $NetAdd +'.' 182 | } else { 183 | $NetAdd = $NetAdd + "0" 184 | } 185 | } 186 | if ($Binary) { 187 | return $NetAdd 188 | } else { 189 | return ConvertFrom-BinaryIP $NetAdd 190 | } 191 | } 192 | } 193 | 194 | Function ConvertTo-BinaryIP { 195 | Param ( 196 | [string] 197 | $IP 198 | ) 199 | Process { 200 | $out = @() 201 | Foreach ($octet in $IP.split('.')) { 202 | $strout = $null 203 | 0..7|% { 204 | IF (($octet - [math]::pow(2,(7-$_)))-ge 0) { 205 | $octet = $octet - [math]::pow(2,(7-$_)) 206 | [string]$strout = $strout + "1" 207 | } else { 208 | [string]$strout = $strout + "0" 209 | } 210 | } 211 | $out += $strout 212 | } 213 | return [string]::join('.',$out) 214 | } 215 | } 216 | 217 | 218 | Function ConvertFrom-BinaryIP { 219 | Param ( 220 | [string] 221 | $IP 222 | ) 223 | Process { 224 | $out = @() 225 | Foreach ($octet in $IP.split('.')) { 226 | $strout = 0 227 | 0..7|% { 228 | $bit = $octet.Substring(($_),1) 229 | IF ($bit -eq 1) { 230 | $strout = $strout + [math]::pow(2,(7-$_)) 231 | } 232 | } 233 | $out += $strout 234 | } 235 | return [string]::join('.',$out) 236 | } 237 | } 238 | 239 | Function ConvertTo-MaskLength { 240 | Param ( 241 | [string] 242 | $mask 243 | ) 244 | Process { 245 | $out = 0 246 | Foreach ($octet in $Mask.split('.')) { 247 | $strout = 0 248 | 0..7|% { 249 | IF (($octet - [math]::pow(2,(7-$_)))-ge 0) { 250 | $octet = $octet - [math]::pow(2,(7-$_)) 251 | $out++ 252 | } 253 | } 254 | } 255 | return $out 256 | } 257 | } 258 | 259 | Function ConvertFrom-MaskLength { 260 | Param ( 261 | [int] 262 | $mask 263 | ) 264 | Process { 265 | $out = @() 266 | [int]$wholeOctet = ($mask - ($mask % 8))/8 267 | if ($wholeOctet -gt 0) { 268 | 1..$($wholeOctet) |%{ 269 | $out += "255" 270 | } 271 | } 272 | $subnet = ($mask - ($wholeOctet * 8)) 273 | if ($subnet -gt 0) { 274 | $octet = 0 275 | 0..($subnet - 1) | %{ 276 | $octet = $octet + [math]::pow(2,(7-$_)) 277 | } 278 | $out += $octet 279 | } 280 | for ($i=$out.count;$i -lt 4; $I++) { 281 | $out += 0 282 | } 283 | return [string]::join('.',$out) 284 | } 285 | } 286 | 287 | Function Get-IPRange { 288 | Param ( 289 | [string] 290 | $IP, 291 | 292 | [string] 293 | $netmask 294 | ) 295 | Process { 296 | iF ($netMask.length -le 3) { 297 | $masklength = $netmask.replace('/','') 298 | $Subnet = ConvertFrom-MaskLength $masklength 299 | } else { 300 | $Subnet = $netmask 301 | $masklength = ConvertTo-MaskLength -Mask $netmask 302 | } 303 | $network = Get-NetworkAddress -IP $IP -Mask $Subnet 304 | 305 | [int]$FirstOctet,[int]$SecondOctet,[int]$ThirdOctet,[int]$FourthOctet = $network.split('.') 306 | $TotalIPs = ([math]::pow(2,(32-$masklength)) -2) 307 | $blocks = ($TotalIPs - ($TotalIPs % 256))/256 308 | if ($Blocks -gt 0) { 309 | 1..$blocks | %{ 310 | 0..255 |%{ 311 | if ($FourthOctet -eq 255) { 312 | If ($ThirdOctet -eq 255) { 313 | If ($SecondOctet -eq 255) { 314 | $FirstOctet++ 315 | $secondOctet = 0 316 | } else { 317 | $SecondOctet++ 318 | $ThirdOctet = 0 319 | } 320 | } else { 321 | $FourthOctet = 0 322 | $ThirdOctet++ 323 | } 324 | } else { 325 | $FourthOctet++ 326 | } 327 | Write-Output ("{0}.{1}.{2}.{3}" -f ` 328 | $FirstOctet,$SecondOctet,$ThirdOctet,$FourthOctet) 329 | } 330 | } 331 | } 332 | $sBlock = $TotalIPs - ($blocks * 256) 333 | if ($sBlock -gt 0) { 334 | 1..$SBlock | %{ 335 | if ($FourthOctet -eq 255) { 336 | If ($ThirdOctet -eq 255) { 337 | If ($SecondOctet -eq 255) { 338 | $FirstOctet++ 339 | $secondOctet = 0 340 | } else { 341 | $SecondOctet++ 342 | $ThirdOctet = 0 343 | } 344 | } else { 345 | $FourthOctet = 0 346 | $ThirdOctet++ 347 | } 348 | } else { 349 | $FourthOctet++ 350 | } 351 | Write-Output ("{0}.{1}.{2}.{3}" -f ` 352 | $FirstOctet,$SecondOctet,$ThirdOctet,$FourthOctet) 353 | } 354 | } 355 | } 356 | } 357 | } 358 | Process { 359 | Get-IPRange $IP $netmask | %{ 360 | [void]$IPs.Add($_) 361 | } 362 | $Script:IPList = $IPs 363 | } 364 | } 365 | 366 | Function SingleEntry { 367 | $Comp = Read-Host "Enter Computer Name or IP (1.1.1.1) or IP Subnet (1.1.1.1/24)" 368 | If ($Comp -eq $Null) { . SingleEntry } 369 | ElseIf ($Comp -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/\d{1,2}") 370 | { 371 | $Temp = $Comp.Split("/") 372 | $IP = $Temp[0] 373 | $Mask = $Temp[1] 374 | . Get-Subnet-Range $IP $Mask 375 | $Script:Computers = $Script:IPList 376 | } 377 | Else 378 | { $Script:Computers = $Comp} 379 | } 380 | 381 | $script:poshDB = "$PSScriptRoot" + "\PoSh-R2_data\db\PoSh-R2.SQLite" 382 | <# 383 | $script:autorunDB = "$PSScriptRoot" + "\PoSh-R2_data\db\autorun.SQLite" 384 | $script:logonDB = "$PSScriptRoot" + "\PoSh-R2_data\db\logon.SQLite" 385 | $script:secEvtDB = "$PSScriptRoot" + "\PoSh-R2_data\db\secevt.SQLite" 386 | $script:sysEvtDB = "$PSScriptRoot" + "\PoSh-R2_data\db\sysevt.SQLite" 387 | $script:appEvtDB = "$PSScriptRoot" + "\PoSh-R2_data\db\appevt.SQLite" 388 | $script:driverDB = "$PSScriptRoot" + "\PoSh-R2_data\db\driver.SQLite" 389 | $script:mappedDB = "$PSScriptRoot" + "\PoSh-R2_data\db\mappeddrive.SQLite" 390 | $script:processDB = "$PSScriptRoot" + "\PoSh-R2_data\db\process.SQLite" 391 | $script:schedtasksDB = "$PSScriptRoot" + "\PoSh-R2_data\db\schedtasks.SQLite" 392 | $script:servicesDB = "$PSScriptRoot" + "\PoSh-R2_data\db\services.SQLite" 393 | $script:envDB = "$PSScriptRoot" + "\PoSh-R2_data\db\env.SQLite" 394 | $script:userInfoDB = "$PSScriptRoot" + "\PoSh-R2_data\db\userinfo.SQLite" 395 | $script:groupDB = "$PSScriptRoot" + "\PoSh-R2_data\db\groups.SQLite" 396 | $script:loggedinDB = "$PSScriptRoot" + "\PoSh-R2_data\db\loggedin.SQLite" 397 | $script:networkDB = "$PSScriptRoot" + "\PoSh-R2_data\db\network.SQLite" 398 | $script:sharesDB = "$PSScriptRoot" + "\PoSh-R2_data\db\shares.SQLite" 399 | $script:diskDB = "$PSScriptRoot" + "\PoSh-R2_data\db\disk.SQLite" 400 | $script:sysinfoDB = "$PSScriptRoot" + "\PoSh-R2_data\db\sysinfo.SQLite" 401 | $script:patchDB = "$PSScriptRoot" + "\PoSh-R2_data\db\patch.SQLite" 402 | $script:softwareDB = "$PSScriptRoot" + "\PoSh-R2_data\db\software.SQLite" 403 | $script:netstatDB = "$PSScriptRoot" + "\PoSh-R2_data\db\netstat.SQLite" 404 | #> 405 | 406 | Write-Host " ______ _______ __ ______ ___ " -ForegroundColor Green 407 | Write-Host " | _ \ / | | | | _ \ |__ \ " -ForegroundColor Green 408 | Write-Host " | |_) | ______ | (---- | |_____ ______ | |_) | ) | " -ForegroundColor Green 409 | Write-Host " | ___/ / __ \ \ \ | __ | |______| | / / / " -ForegroundColor Green 410 | Write-Host " | | | |__| | |----) | | | | | | |\ \-----/ /_ " -ForegroundColor Green 411 | Write-Host " | _| \______/ |_______/ |__| |__| | _| \_____|_____| " -ForegroundColor Green 412 | Write-Host "" 413 | 414 | Write-Host "What systems do you get to interrogate?" -ForegroundColor yellow 415 | $strResponse = Read-Host "`n[1] All Domain Computers (Must provide Domain) `n[2] Import Computer Names/ IPs from a File `n[3] Input Computer Names/ IPs Manually `n[4] Local System `n" 416 | If($strResponse -eq "1"){. ListComputers | Sort-Object} 417 | elseif($strResponse -eq "2"){. ListTextFile} 418 | elseif($strResponse -eq "3"){. SingleEntry} 419 | elseif($strResponse -eq "4"){$localhost = $computers = "localhost"} 420 | else{Write-Host "You did not supply a correct response, ` 421 | Please run script again."; pause -foregroundColor Red} 422 | 423 | Write-Host "Got computer list... Next task..." -ForegroundColor yellow 424 | write-output " " 425 | 426 | if (-not(test-path "$PSScriptRoot\PoSh-R2_Data")){ 427 | new-item -ItemType Directory -path "$PSScriptRoot" -name "PoSh-R2_Data" | out-null 428 | } 429 | if(-not(test-path "$PSScriptRoot\PoSh-R2_Data\db")){ 430 | new-item -ItemType directory -path "$PSScriptRoot\PoSh-R2_Data" -Name "db" | out-null 431 | } 432 | 433 | $dirDate = get-date -Format yyyy-MM-dd-HHmm 434 | new-item -ItemType Directory -path "$PSScriptRoot\PoSh-R2_Data" -Name "$dirDate" | out-null 435 | 436 | if(-not(test-path "$poshDB")){ 437 | $Query = 'CREATE TABLE autorun ( 438 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 439 | date DATETIME, 440 | computername TEXT, 441 | name TEXT, 442 | location TEXT, 443 | command TEXT, 444 | user TEXT)' 445 | 446 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 447 | 448 | 449 | $Query = 'CREATE TABLE disk ( 450 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 451 | date DATETIME, 452 | computername TEXT, 453 | deviceid TEXT, 454 | description TEXT, 455 | providername TEXT)' 456 | 457 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 458 | 459 | $Query = 'CREATE TABLE drivers ( 460 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 461 | date DATETIME, 462 | computername TEXT, 463 | name TEXT, 464 | installdate TEXT, 465 | displayname TEXT, 466 | pathname TEXT, 467 | state TEXT, 468 | startmode TEXT)' 469 | 470 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 471 | 472 | $Query = 'CREATE TABLE env ( 473 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 474 | date DATETIME, 475 | computername TEXT, 476 | username TEXT, 477 | name TEXT, 478 | variablevalue TEXT)' 479 | 480 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 481 | 482 | $Query = 'CREATE TABLE appevt ( 483 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 484 | date DATETIME, 485 | computername TEXT, 486 | logfile TEXT, 487 | eventcode TEXT, 488 | timegenerated TEXT, 489 | message TEXT, 490 | type TEXT)' 491 | 492 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 493 | 494 | $Query = 'CREATE TABLE secevt ( 495 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 496 | date DATETIME, 497 | computername TEXT, 498 | logfile TEXT, 499 | eventcode TEXT, 500 | timegenerated TEXT, 501 | message TEXT, 502 | type TEXT)' 503 | 504 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 505 | 506 | $Query = 'CREATE TABLE sysevt ( 507 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 508 | date DATETIME, 509 | computername TEXT, 510 | logfile TEXT, 511 | eventcode TEXT, 512 | timegenerated TEXT, 513 | message TEXT, 514 | type TEXT)' 515 | 516 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 517 | 518 | $Query = 'CREATE TABLE groups ( 519 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 520 | date DATETIME, 521 | computername TEXT, 522 | caption TEXT, 523 | domain TEXT, 524 | name TEXT, 525 | sid TEXT)' 526 | 527 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 528 | 529 | $Query = 'CREATE TABLE netlogon ( 530 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 531 | date DATETIME, 532 | computername TEXT, 533 | name TEXT, 534 | lastlogon TEXT, 535 | lastlogoff TEXT, 536 | numberoflogons TEXT, 537 | passwordage TEXT)' 538 | 539 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 540 | 541 | $Query = 'CREATE TABLE loggedinuser ( 542 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 543 | date DATETIME, 544 | computername TEXT, 545 | username TEXT)' 546 | 547 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 548 | 549 | $Query = 'CREATE TABLE mappeddrives ( 550 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 551 | date DATETIME, 552 | computername TEXT, 553 | providername TEXT)' 554 | 555 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 556 | 557 | $Query = 'CREATE TABLE process ( 558 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 559 | date DATETIME, 560 | computername TEXT, 561 | name TEXT, 562 | path TEXT, 563 | commandline TEXT, 564 | description TEXT, 565 | processid TEXT, 566 | parentprocessid TEXT, 567 | handle TEXT, 568 | handlecount TEXT, 569 | threadcount TEXT, 570 | creationdate TEXT)' 571 | 572 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 573 | 574 | $Query = 'CREATE TABLE schedtask ( 575 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 576 | date DATETIME, 577 | computername TEXT, 578 | name TEXT, 579 | owner TEXT, 580 | jobid TEXT, 581 | command TEXT, 582 | runrepeatedly TEXT, 583 | interactwithdesktop TEXT)' 584 | 585 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 586 | 587 | $Query = 'CREATE TABLE services ( 588 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 589 | date DATETIME, 590 | computername TEXT, 591 | processid TEXT, 592 | name TEXT, 593 | description TEXT, 594 | pathname TEXT, 595 | started TEXT, 596 | startmode TEXT, 597 | startname TEXT, 598 | state TEXT)' 599 | 600 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 601 | 602 | $Query = 'CREATE TABLE useraccount ( 603 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 604 | date DATETIME, 605 | computername TEXT, 606 | accounttype TEXT, 607 | fullname TEXT, 608 | domain TEXT, 609 | disabled TEXT, 610 | localaccount TEXT, 611 | lockedout TEXT, 612 | passwordchangeable TEXT, 613 | passwordexpires TEXT, 614 | sid TEXT)' 615 | 616 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 617 | 618 | $Query = 'CREATE TABLE networks ( 619 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 620 | date DATETIME, 621 | computername TEXT, 622 | ipaddress TEXT, 623 | ipsubnet TEXT, 624 | defaultipgateway TEXT, 625 | dhcpserver TEXT, 626 | dnshostname TEXT, 627 | dnsserversearchorder TEXT, 628 | macaddress TEXT, 629 | description TEXT)' 630 | 631 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 632 | 633 | $Query = 'CREATE TABLE shares ( 634 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 635 | date DATETIME, 636 | computername TEXT, 637 | name TEXT, 638 | path TEXT, 639 | description TEXT)' 640 | 641 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 642 | 643 | $Query = 'CREATE TABLE computersystem ( 644 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 645 | date DATETIME, 646 | computername TEXT, 647 | domain TEXT, 648 | model TEXT, 649 | manufacturer TEXT, 650 | enabledaylightsavingstime TEXT, 651 | partofdomain TEXT, 652 | roles TEXT, 653 | systemtype TEXT, 654 | numberofprocessors TEXT, 655 | totalphysicalmemory TEXT, 656 | username TEXT)' 657 | 658 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 659 | 660 | $Query = 'CREATE TABLE patch ( 661 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 662 | date DATETIME, 663 | computername TEXT, 664 | hotfixid TEXT, 665 | description TEXT, 666 | installedby TEXT, 667 | installedon TEXT)' 668 | 669 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 670 | 671 | $Query = 'CREATE TABLE software ( 672 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 673 | date DATETIME, 674 | computername TEXT, 675 | name TEXT, 676 | packetcache TEXT, 677 | vendor TEXT, 678 | version TEXT, 679 | identifyingnumber TEXT)' 680 | 681 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 682 | 683 | $Query = 'CREATE TABLE connections ( 684 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, 685 | date DATETIME, 686 | computername TEXT, 687 | protocol TEXT, 688 | version TEXT, 689 | localaddress TEXT, 690 | localport TEXT, 691 | remoteaddress TEXT, 692 | remoteport TEXT, 693 | state TEXT, 694 | processid TEXT, 695 | processname TEXT, 696 | processpath TEXT)' 697 | 698 | Invoke-SqliteQuery -Query $Query -DataSource $poshDB | Out-Null 699 | } 700 | 701 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving Autoruns information..." -ForegroundColor yellow 702 | Get-WMIObject -Namespace root\cimv2 -Class win32_startupcommand -ComputerName $computers | select PSComputername, Name, Location, Command, User | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Autoruns.csv -NoTypeInformation 703 | 704 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving logon information..." -ForegroundColor yellow 705 | Get-WMIObject -Namespace root\cimv2 -Class win32_networkloginprofile -ComputerName $computers | select PSComputername,Name, LastLogon,LastLogoff,NumberOfLogons,PasswordAge | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\NetLogon.csv -NoTypeInformation 706 | 707 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving event log information..." -ForegroundColor yellow 708 | Get-WMIObject -Namespace root\cimv2 -Class win32_ntlogevent -ComputerName $computers -filter "logfile='security'" | select PSComputername, LogFile, EventCode, TimeGenerated, Message, Type | select -first 50 | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-Security.csv -NoTypeInformation 709 | Get-WMIObject -Namespace root\cimv2 -Class win32_ntlogevent -ComputerName $computers -filter "logfile='system'" | select PSComputername, LogFile, EventCode, TimeGenerated, Message, Type | select -first 50 | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-System.csv -NoTypeInformation 710 | Get-WMIObject -Namespace root\cimv2 -Class win32_ntlogevent -ComputerName $computers -filter "logfile='application'" | select PSComputername, LogFile, EventCode, TimeGenerated, Message, Type | select -first 50 | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-Application.csv -NoTypeInformation 711 | 712 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving driver information..." -ForegroundColor yellow 713 | Get-WMIObject -Namespace root\cimv2 -Class win32_systemdriver -ComputerName $computers | select PSComputername, Name, InstallDate, DisplayName, PathName, State, StartMode | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Drivers.csv -NoTypeInformation 714 | 715 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving mapped drives information..." -ForegroundColor yellow 716 | Get-WMIObject -Namespace root\cimv2 -Class win32_mappedlogicaldisk -ComputerName $computers | select PSComputername, Name, ProviderName | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Mapped_Drives.csv -NoTypeInformation 717 | 718 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving running processes information..." -ForegroundColor yellow 719 | Get-WMIObject -Namespace root\cimv2 -Class win32_process -ComputerName $computers | select PSComputername, Name, path, Commandline, Description, ProcessID, ParentProcessID, Handle, HandleCount, ThreadCount, CreationDate | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Processes.csv -NoTypeInformation 720 | 721 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving scheduled tasks created by at.exe or Win32_ScheduledJob..." -ForegroundColor yellow 722 | Get-WMIObject -Namespace root\cimv2 -Class win32_scheduledjob -ComputerName $computers | select PSComputername, Name, Owner, JodID, Command, RunRepeatedly, InteractWithDesktop | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Scheduled_Tasks.csv -NoTypeInformation 723 | 724 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving service information..." -ForegroundColor yellow 725 | Get-WMIObject -Namespace root\cimv2 -Class win32_service -ComputerName $computers | select PSComputername, ProcessID, Name, Description, PathName, Started, StartMode, StartName, State | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Services.csv -NoTypeInformation 726 | 727 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving environment variables information..." -ForegroundColor yellow 728 | Get-WMIObject -Namespace root\cimv2 -Class win32_environment -ComputerName $computers | select PSComputername, UserName, Name, VariableValue | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Environment_Variables.csv -NoTypeInformation 729 | 730 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving user information..." -ForegroundColor yellow 731 | Get-WMIObject -Namespace root\cimv2 -Class win32_useraccount -ComputerName $computers | select PSComputername, accounttype, name, fullname, domain, disabled, localaccount, lockout, passwordchangeable, passwordexpires, sid | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Users.csv -NoTypeInformation 732 | 733 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving group information..." -ForegroundColor yellow 734 | Get-WMIObject -Namespace root\cimv2 -Class win32_group -ComputerName $computers |select PSComputername, Caption, Domain, Name, Sid | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Groups.csv -NoTypeInformation 735 | 736 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving loggedon user information..." -ForegroundColor yellow 737 | Get-WMIObject -Namespace root\cimv2 -Class win32_computersystem -ComputerName $computers | select PSComputername, Username | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Logged_on_User.csv -NoTypeInformation 738 | 739 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving network configurations..." -ForegroundColor yellow 740 | Get-WMIObject -Namespace root\cimv2 -Class win32_networkadapterconfiguration -ComputerName $computers | select PSComputername, IPAddress, IPSubnet, DefaultIPGateway, DHCPServer, DNSHostname, DNSserversearchorder, MACAddress, description| Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Network_Configs.csv -NoTypeInformation 741 | 742 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving shares information..." -ForegroundColor yellow 743 | Get-WMIObject -Namespace root\cimv2 -Class win32_share -ComputerName $computers |select PSComputername, Name, Path, Description | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Shares.csv -NoTypeInformation 744 | 745 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving disk information..." -ForegroundColor yellow 746 | Get-WMIObject -Namespace root\cimv2 -Class win32_logicaldisk -ComputerName $computers | select PSComputername, DeviceID, Description, ProviderName | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Disk.csv -NoTypeInformation 747 | 748 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving system information..." -ForegroundColor yellow 749 | Get-WMIObject -Namespace root\cimv2 -Class win32_computersystem -ComputerName $computers | select PSComputername, Domain, Model, Manufacturer, EnableDaylightSavingsTime, PartOfDomain, Roles, SystemType, NumberOfProcessors, TotalPhysicalMemory, Username | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\System_Info.csv -NoTypeInformation 750 | 751 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving installed patch information..." -ForegroundColor yellow 752 | Get-WMIObject -Namespace root\cimv2 -Class win32_quickfixengineering -ComputerName $computers | select PSComputername, HotFixID, Description, InstalledBy, InstalledOn | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Patches.csv -NoTypeInformation 753 | 754 | # Warning: https://gregramsey.net/2012/02/20/win32_product-is-evil/ 755 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving installed software information..." -ForegroundColor yellow 756 | Get-WMIObject -Namespace root\cimv2 -Class win32_product -ComputerName $computers | select PSComputername, Name, PackageCache, Vendor, Version, IdentifyingNumber | Export-CSV $PSScriptRoot\PoSh-R2_data\$dirDate\Software.csv -NoTypeInformation 757 | 758 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Retrieving network connections..." -ForegroundColor yellow 759 | if($localhost -eq $null){ 760 | foreach($computer in $computers){ 761 | Invoke-WmiMethod -Class Win32_Process -Name Create -Computername $computer -ArgumentList "cmd /c netstat -ano > c:\$computer.txt" >$null 2>&1 762 | copy-item \\$computer\c$\$computer.txt $PSScriptRoot\PoSh-R2_data\$dirDate 763 | $connections = get-content $PSScriptRoot\PoSh-R2_data\$dirDate\$computer.txt 764 | $NetStatRecords = @() 765 | Start-Sleep 2 766 | $Connections[4..$Connections.count] | foreach-object { 767 | Write-Verbose "Parsing line: $_ " 768 | $Fragments = ($_ -replace '\s+', ' ').Split(' ') 769 | if ($Fragments[2].Contains('[')) { 770 | $Version = 'IPv6' 771 | $LocalAddress = $Fragments[2].Split(']')[0].Split('[')[1] 772 | $LocalPort = $Fragments[2].Split(']')[1].Split(':')[1] 773 | } else { 774 | $Version = 'IPv4' 775 | $LocalAddress = $Fragments[2].Split(':')[0] 776 | $LocalPort = $Fragments[2].Split(':')[1] 777 | } 778 | if ($Fragments[3].Contains('[')) { 779 | $RemoteAddress = $Fragments[3].Split(']')[0].Split('[')[1] 780 | $RemotePort = $Fragments[3].Split(']')[1].Split(':')[1] 781 | } else { 782 | $RemoteAddress = $Fragments[3].Split(':')[0] 783 | $RemotePort = $Fragments[3].Split(':')[1] 784 | } 785 | $ProcessID = $(if ($RemoteAddress -eq '*') {$Fragments[4]} else {$Fragments[5]}) 786 | $Props = [ordered]@{ 787 | ComputerName = $computer 788 | Protocol = $Fragments[1] 789 | Version = $Version 790 | LocalAddress = $LocalAddress 791 | LocalPort = $LocalPort 792 | RemoteAddress = $RemoteAddress 793 | RemotePort = $RemotePort 794 | State = $(if ($RemoteAddress -eq '*') {''} else {$Fragments[4]}) 795 | ProcessID = $ProcessID 796 | } 797 | $Record = New-Object -TypeName PSObject -Property $Props 798 | $NetStatRecords += $Record 799 | } 800 | 801 | $NetStatRecords | export-csv $PSScriptRoot\PoSh-R2_data\$dirDate\connections.csv -NoTypeInformation -Append 802 | Remove-Variable NetStatRecords 803 | Remove-item $PSScriptRoot\PoSh-R2_data\$dirDate\$computer.txt 804 | } 805 | Remove-item \\$computer\c$\$computer.txt 806 | Remove-Variable localhost -ErrorAction SilentlyContinue 807 | } 808 | 809 | else{ 810 | $connections = netstat -ano 811 | $NetStatRecords = @() 812 | $Connections[4..$Connections.count] | foreach-object { 813 | Write-Verbose "Parsing line: $_ " 814 | $Fragments = ($_ -replace '\s+', ' ').Split(' ') 815 | if ($Fragments[2].Contains('[')) { 816 | $Version = 'IPv6' 817 | $LocalAddress = $Fragments[2].Split(']')[0].Split('[')[1] 818 | $LocalPort = $Fragments[2].Split(']')[1].Split(':')[1] 819 | } else { 820 | $Version = 'IPv4' 821 | $LocalAddress = $Fragments[2].Split(':')[0] 822 | $LocalPort = $Fragments[2].Split(':')[1] 823 | } 824 | if ($Fragments[3].Contains('[')) { 825 | $RemoteAddress = $Fragments[3].Split(']')[0].Split('[')[1] 826 | $RemotePort = $Fragments[3].Split(']')[1].Split(':')[1] 827 | } else { 828 | $RemoteAddress = $Fragments[3].Split(':')[0] 829 | $RemotePort = $Fragments[3].Split(':')[1] 830 | } 831 | $ProcessID = $(if ($RemoteAddress -eq '*') {$Fragments[4]} else {$Fragments[5]}) 832 | $Props = [ordered]@{ 833 | ComputerName = $computer 834 | Protocol = $Fragments[1] 835 | Version = $Version 836 | LocalAddress = $LocalAddress 837 | LocalPort = $LocalPort 838 | RemoteAddress = $RemoteAddress 839 | RemotePort = $RemotePort 840 | State = $(if ($RemoteAddress -eq '*') {''} else {$Fragments[4]}) 841 | ProcessID = $ProcessID 842 | ProcessName = $((Get-Process -Id $ProcessID).Name) 843 | ProcessPath = $((Get-Process -Id $ProcessID).Path) 844 | } 845 | $Record = New-Object -TypeName PSObject -Property $Props 846 | $NetStatRecords += $Record 847 | } 848 | $NetStatRecords | export-csv $PSScriptRoot\PoSh-R2_data\$dirDate\connections.csv -NoTypeInformation -Append 849 | Remove-Variable NetStatRecords 850 | } 851 | 852 | Write-Output " " 853 | Write-Host "Done!"-ForegroundColor Cyan 854 | Write-Output " " 855 | Write-Host "[-] " -ForegroundColor Green -NoNewline; Write-Host "Importing data into database..." -ForegroundColor Yellow 856 | Write-Output " " 857 | 858 | $autorun = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Autoruns.csv 859 | $disk = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Disk.csv 860 | $drivers = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Drivers.csv 861 | $envVar = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Environment_Variables.csv 862 | $evtApp = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-Application.csv 863 | $evtSec = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-Security.csv 864 | $evtSys = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-System.csv 865 | $groups = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Groups.csv 866 | $loggedon = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Logged_on_User.csv 867 | $mapped = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Mapped_Drives.csv 868 | $netlogon = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\NetLogon.csv 869 | $net = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Network_Configs.csv 870 | $patch = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Patches.csv 871 | $process = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Processes.csv 872 | $sched = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Scheduled_Tasks.csv 873 | $serv = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Services.csv 874 | $shares = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Shares.csv 875 | $software = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Software.csv 876 | $sysInfo = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\System_Info.csv 877 | $users = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\Users.csv 878 | $connects = import-csv $PSScriptRoot\PoSh-R2_data\$dirDate\connections.csv 879 | 880 | $autorunQuery = 'INSERT INTO autorun (date, computername, name, location, command, user) 881 | VALUES (@date, @computername, @name, @location, @command, @user)' 882 | 883 | $diskQuery = 'INSERT INTO disk (date, computername, deviceid, description, providername) 884 | VALUES (@date, @computername, @deviceid, @description, @providername)' 885 | 886 | $driversQuery = 'INSERT INTO drivers (date, computername, name, installdate, displayname, pathname, state, startmode) 887 | VALUES (@date, @computername, @name, @installdate, @displayname, @pathname, @state, @startmode)' 888 | 889 | $envQuery = 'INSERT INTO env (date, computername, username, name, variablevalue) 890 | VALUES (@date, @computername, @username, @name, @variablevalue)' 891 | 892 | $appevtQuery = 'INSERT INTO appevt (date, computername, logfile, eventcode, timegenerated, message, type) 893 | VALUES (@date, @computername, @logfile, @eventcode, @timegenerated, @message, @type)' 894 | 895 | $secevtQuery = 'INSERT INTO secevt (date, computername, logfile, eventcode, timegenerated, message, type) 896 | VALUES (@date, @computername, @logfile, @eventcode, @timegenerated, @message, @type)' 897 | 898 | $sysevtQuery = 'INSERT INTO sysevt (date, computername, logfile, eventcode, timegenerated, message, type) 899 | VALUES (@date, @computername, @logfile, @eventcode, @timegenerated, @message, @type)' 900 | 901 | $groupsQuery = 'INSERT INTO groups (date, computername, caption, domain, name, sid) 902 | VALUES (@date, @computername, @caption, @domain, @name, @sid)' 903 | 904 | $loggedinuserQuery = 'INSERT INTO loggedinuser (date, computername, username) 905 | VALUES (@date, @computername, @username)' 906 | 907 | $netlogonQuery = 'INSERT INTO netlogon (date, computername, name, lastlogon, lastlogoff, numberoflogons, passwordage) 908 | VALUES (@date, @computername, @name, @lastlogon, @lastlogoff, @numberoflogons, @passwordage)' 909 | 910 | $mappeddrivesQuery = 'INSERT INTO mappeddrives (date, computername, providername) 911 | VALUES (@date, @computername, @providername)' 912 | 913 | $processQuery = 'INSERT INTO process (date, computername, name, path, commandline, description, processid, parentprocessid, handle, handlecount, threadcount, creationdate) 914 | VALUES (@date, @computername, @name, @path, @commandline, @description, @processid, @parentprocessid, @handle, @handlecount, @threadcount, @creationdate)' 915 | 916 | $schedtaskQuery = 'INSERT INTO schedtask (date, computername, name, owner, jobid, command, runrepeatedly, interactwithdesktop) 917 | VALUES (@date, @computername, @name, @owner, @jobid, @command, @runrepeatedly, @interactwithdesktop)' 918 | 919 | $servicesQuery = 'INSERT INTO services (date, computername, processid, name, description, pathname, started, startmode, startname, state) 920 | VALUES (@date, @computername, @processid, @name, @description, @pathname, @started, @startmode, @startname, @state)' 921 | 922 | $useraccountQuery = 'INSERT INTO useraccount (date, computername, accounttype, fullname, domain, disabled, localaccount, lockedout, passwordchangeable, passwordexpires, sid) 923 | VALUES (@date, @computername, @accounttype, @fullname, @domain, @disabled, @localaccount, @lockedout, @passwordchangeable, @passwordexpires, @sid)' 924 | 925 | $networksQuery = 'INSERT INTO networks (date, computername, ipaddress, ipsubnet, defaultipgateway, dhcpserver, dnshostname, dnsserversearchorder, macaddress, description) 926 | VALUES (@date, @computername, @ipaddress, @ipsubnet, @defaultipgateway, @dhcpserver, @dnshostname, @dnsserversearchorder, @macaddress, @description)' 927 | 928 | $sharesQuery = 'INSERT INTO shares (date, computername, name, path, description) 929 | VALUES (@date, @computername, @name, @path, @description)' 930 | 931 | $computersystemQuery = 'INSERT INTO computersystem (date, computername, domain, model, manufacturer, enabledaylightsavingstime, partofdomain, roles, systemtype, numberofprocessors, totalphysicalmemory, username) 932 | VALUES (@date, @computername, @domain, @model, @manufacturer, @enabledaylightsavingstime, @partofdomain, @roles, @systemtype, @numberofprocessors, @totalphysicalmemory, @username)' 933 | 934 | $patchQuery = 'INSERT INTO patch (date, computername, hotfixid, description, installedby, installedon) 935 | VALUES (@date, @computername, @hotfixid, @description, @installedby, @installedon)' 936 | 937 | $softwareQuery = 'INSERT INTO software (date, computername, name, packetcache, vendor, version, identifyingnumber) 938 | VALUES (@date, @computername, @name, @packetcache, @vendor, @version, @identifyingnumber)' 939 | 940 | $connectionsQuery = 'INSERT INTO connections (date, computername, protocol, version, localaddress, localport, remoteaddress, remoteport, state, processid, processname, processpath) 941 | VALUES (@date, @computername, @protocol, @version, @localaddress, @localport, @remoteaddress, @remoteport, @state, @processid, @processname, @processpath)' 942 | 943 | 944 | foreach($item in $autorun){ 945 | 946 | Invoke-SqliteQuery -DataSource $poshDB -Query $autorunQuery -SqlParameters @{ 947 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Autoruns.csv).CreationTimeUtc 948 | computername = $item.pscomputername 949 | name = $item.name 950 | location = $item.location 951 | command = $item.command 952 | user = $item.user 953 | } | Out-Null 954 | 955 | } 956 | 957 | foreach($item in $disk){ 958 | 959 | Invoke-SqliteQuery -DataSource $poshDB -Query $diskQuery -SqlParameters @{ 960 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\disk.csv).CreationTimeUtc 961 | computername = $item.pscomputername 962 | deviceid = $item.deviceid 963 | description = $item.description 964 | providername = $item.providername 965 | } | Out-Null 966 | 967 | } 968 | 969 | foreach($item in $drivers){ 970 | 971 | Invoke-SqliteQuery -DataSource $poshDB -Query $driversQuery -SqlParameters @{ 972 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\drivers.csv).CreationTimeUtc 973 | computername = $item.pscomputername 974 | name = $item.name 975 | installdate = $item.installdate 976 | displayname = $item.displayname 977 | pathname = $item.pathname 978 | state = $item.state 979 | startmode = $item.startmode 980 | } | Out-Null 981 | 982 | } 983 | 984 | foreach($item in $envVar){ 985 | 986 | Invoke-SqliteQuery -DataSource $poshDB -Query $envQuery -SqlParameters @{ 987 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Environment_Variables.csv).CreationTimeUtc 988 | computername = $item.pscomputername 989 | username = $item.username 990 | name = $item.name 991 | variablevalue = $item.variablevalue 992 | } | Out-Null 993 | 994 | } 995 | 996 | foreach($item in $evtApp){ 997 | 998 | Invoke-SqliteQuery -DataSource $poshDB -Query $appevtQuery -SqlParameters @{ 999 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-Application.csv).CreationTimeUtc 1000 | computername = $item.pscomputername 1001 | logfile = $item.logfile 1002 | eventcode = $item.eventcode 1003 | timegenerated = $item.timegenerated 1004 | message = $item.Message 1005 | type = $item.type 1006 | } | Out-Null 1007 | 1008 | } 1009 | 1010 | foreach($item in $evtSec){ 1011 | 1012 | Invoke-SqliteQuery -DataSource $poshDB -Query $secevtQuery -SqlParameters @{ 1013 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-Security.csv).CreationTimeUtc 1014 | computername = $item.pscomputername 1015 | logfile = $item.logfile 1016 | eventcode = $item.eventcode 1017 | timegenerated = $item.timegenerated 1018 | message = $item.Message 1019 | type = $item.type 1020 | } | Out-Null 1021 | 1022 | } 1023 | 1024 | foreach($item in $evtSys){ 1025 | 1026 | Invoke-SqliteQuery -DataSource $poshDB -Query $sysevtQuery -SqlParameters @{ 1027 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Eventlogs-System.csv).CreationTimeUtc 1028 | computername = $item.pscomputername 1029 | logfile = $item.logfile 1030 | eventcode = $item.eventcode 1031 | timegenerated = $item.timegenerated 1032 | message = $item.Message 1033 | type = $item.type 1034 | } | Out-Null 1035 | 1036 | } 1037 | 1038 | foreach($item in $groups){ 1039 | 1040 | Invoke-SqliteQuery -DataSource $poshDB -Query $groupsQuery -SqlParameters @{ 1041 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Groups.csv).CreationTimeUtc 1042 | computername = $item.pscomputername 1043 | caption = $item.caption 1044 | domain = $item.domain 1045 | name = $item.name 1046 | sid = $item.sid 1047 | } | Out-Null 1048 | 1049 | } 1050 | 1051 | 1052 | foreach($item in $loggedon){ 1053 | 1054 | Invoke-SqliteQuery -DataSource $poshDB -Query $loggedinuserQuery -SqlParameters @{ 1055 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Logged_on_User.csv).CreationTimeUtc 1056 | computername = $item.pscomputername 1057 | username = $item.username 1058 | } | Out-Null 1059 | 1060 | } 1061 | 1062 | foreach($item in $mapped){ 1063 | 1064 | Invoke-SqliteQuery -DataSource $poshDB -Query $mappeddrivesQuery -SqlParameters @{ 1065 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Mapped_Drives.csv).CreationTimeUtc 1066 | computername = $item.pscomputername 1067 | providername = $item.providername 1068 | } | Out-Null 1069 | 1070 | } 1071 | 1072 | foreach($item in $process){ 1073 | 1074 | Invoke-SqliteQuery -DataSource $poshDB -Query $processQuery -SqlParameters @{ 1075 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Processes.csv).CreationTimeUtc 1076 | computername = $item.pscomputername 1077 | name = $item.name 1078 | path = $item.path 1079 | commandline = $item.commandline 1080 | description = $item.description 1081 | processid = $item.processid 1082 | parentprocessid = $item.parentprocessid 1083 | handle = $item.handle 1084 | handlecount = $item.handlecount 1085 | threadcount = $item.threadcount 1086 | creationdate = $item.creationdate 1087 | } | Out-Null 1088 | 1089 | } 1090 | 1091 | foreach($item in $sched){ 1092 | 1093 | Invoke-SqliteQuery -DataSource $poshDB -Query $schedtaskQuery -SqlParameters @{ 1094 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Scheduled_Tasks.csv).CreationTimeUtc 1095 | computername = $item.pscomputername 1096 | name = $item.name 1097 | owner = $item.owner 1098 | jobid = $item.jobid 1099 | command = $item.command 1100 | runrepeatedly = $item.runrepeatedly 1101 | interactwithdesktop = $item.interactwithdesktop 1102 | } | Out-Null 1103 | 1104 | } 1105 | 1106 | 1107 | foreach($item in $serv){ 1108 | 1109 | Invoke-SqliteQuery -DataSource $poshDB -Query $servicesQuery -SqlParameters @{ 1110 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Services.csv).CreationTimeUtc 1111 | computername = $item.pscomputername 1112 | processid = $item.processid 1113 | name = $item.name 1114 | description = $item.description 1115 | pathname = $item.pathname 1116 | started = $item.started 1117 | startmode = $item.startmode 1118 | startname = $item.startname 1119 | state = $item.state 1120 | } | Out-Null 1121 | 1122 | } 1123 | 1124 | foreach($item in $users){ 1125 | 1126 | Invoke-SqliteQuery -DataSource $poshDB -Query $useraccountQuery -SqlParameters @{ 1127 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Users.csv).CreationTimeUtc 1128 | computername = $item.pscomputername 1129 | accounttype = $item.accounttype 1130 | fullname = $item.fullname 1131 | domain = $item.domain 1132 | disabled = $item.disabled 1133 | localaccount = $item.localaccount 1134 | lockedout = $item.lockedout 1135 | passwordchangeable = $item.passwordchangeable 1136 | passwordexpires = $item.passwordexpires 1137 | sid = $item.sid 1138 | } | Out-Null 1139 | 1140 | } 1141 | 1142 | 1143 | foreach($item in $net){ 1144 | 1145 | Invoke-SqliteQuery -DataSource $poshDB -Query $networksQuery -SqlParameters @{ 1146 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Network_Configs.csv).CreationTimeUtc 1147 | computername = $item.pscomputername 1148 | ipaddress = $item.ipaddress 1149 | ipsubnet = $item.ipsubnet 1150 | defaultipgateway = $item.defaultipgateway 1151 | dhcpserver = $item.dhcpserver 1152 | dnshostname = $item.dnshostname 1153 | dnsserversearchorder = $item.dnsserversearchorder 1154 | macaddress = $item.macaddress 1155 | description = $item.description 1156 | } | Out-Null 1157 | } 1158 | 1159 | foreach($item in $netlogon){ 1160 | 1161 | Invoke-SqliteQuery -DataSource $poshDB -Query $netlogonQuery -SqlParameters @{ 1162 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\NetLogon.csv).CreationTimeUtc 1163 | computername = $item.pscomputername 1164 | name = $item.name 1165 | lastlogon = $item.lastlogon 1166 | lastlogoff = $item.lastlogoff 1167 | numberoflogons = $item.numberoflogons 1168 | passwordage = $item.passwordage 1169 | } | Out-Null 1170 | } 1171 | foreach($item in $shares){ 1172 | 1173 | Invoke-SqliteQuery -DataSource $poshDB -Query $sharesQuery -SqlParameters @{ 1174 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Shares.csv).CreationTimeUtc 1175 | computername = $item.pscomputername 1176 | name = $item.name 1177 | path = $item.path 1178 | description = $item.description 1179 | } | Out-Null 1180 | } 1181 | 1182 | 1183 | foreach($item in $sysInfo){ 1184 | 1185 | Invoke-SqliteQuery -DataSource $poshDB -Query $computersystemQuery -SqlParameters @{ 1186 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\System_Info.csv).CreationTimeUtc 1187 | computername = $item.pscomputername 1188 | domain = $item.domain 1189 | model = $item.model 1190 | manufacturer = $item.manufacturer 1191 | enabledaylightsavingstime = $item.enabledaylightsavingstime 1192 | partofdomain = $item.partofdomain 1193 | roles =$item.roles 1194 | systemtype = $item.systemtype 1195 | numberofprocessors = $item.numberofprocessors 1196 | totalphysicalmemory = $item.totalphysicalmemory 1197 | username = $item.username 1198 | } | Out-Null 1199 | } 1200 | 1201 | foreach($item in $patch){ 1202 | 1203 | Invoke-SqliteQuery -DataSource $poshDB -Query $patchQuery -SqlParameters @{ 1204 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Patches.csv).CreationTimeUtc 1205 | computername = $item.pscomputername 1206 | hotfixid = $item.hotfixid 1207 | description = $item.description 1208 | installedby = $item.installedby 1209 | installedon = $item.installedon 1210 | } | Out-Null 1211 | } 1212 | 1213 | foreach($item in $software){ 1214 | 1215 | Invoke-SqliteQuery -DataSource $poshDB -Query $softwareQuery -SqlParameters @{ 1216 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\Software.csv).CreationTimeUtc 1217 | computername = $item.pscomputername 1218 | name = $item.name 1219 | packetcache = $item.packetcache 1220 | vendor = $item.vendor 1221 | version = $item.version 1222 | identifyingnumber = $item.identifyingnumber 1223 | } | Out-Null 1224 | } 1225 | 1226 | foreach($item in $connects){ 1227 | 1228 | Invoke-SqliteQuery -DataSource $poshDB -Query $connectionsQuery -SqlParameters @{ 1229 | date = (get-item $PSScriptRoot\PoSh-R2_data\$dirDate\connections.csv).CreationTimeUtc 1230 | computername = $item.pscomputername 1231 | protocol = $item.protocol 1232 | version = $item.version 1233 | localaddress = $item.localaddress 1234 | localport = $item.localport 1235 | remoteaddress = $item.remoteaddress 1236 | remoteport = $item.remoteport 1237 | state = $item.state 1238 | processid = $item.processid 1239 | processname = $item.processname 1240 | processpath = $item.processpath 1241 | 1242 | } | Out-Null 1243 | } 1244 | 1245 | Write-host "Done!"-ForegroundColor Cyan -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PoSh-R2PowerShell - Rapid Response (PoSH-R2)... For the incident responder in you! 2 | 3 | PoSH-R2 is a set of Windows Management Instrumentation (WMI) scripts that investigators and forensic analysts can use to retrieve information from a compromised (or potentially compromised) Windows system. The scripts use WMI to pull this information from the operating system. Therefore, this script will need to be executed with a user that has the necessary privileges and authentication is done via a Network logon. Retreived data is written to CSVs and SQLite databases on the system running the script. 4 |
5 |
6 | In a single execution, PoSH-R2 will retrieve the following data from an individual machine or a group of systems: 7 |
8 |
9 |     - Autorun entries
10 |     - Disk info
11 |     - Environment variables
12 |     - Event logs (50 lastest)
13 |     - Installed Software
14 |     - Logon sessions
15 |     - List of drivers
16 |     - List of mapped network drives
17 |     - List of running processes
18 |     - Logged in user
19 |     - Local groups
20 |     - Local user accounts
21 |     - Network configuration
22 |     - Network connections
23 |     - Patches
24 |     - Scheduled tasks with AT command
25 |     - Shares
26 |     - Services
27 |     - System Information
28 | 29 | # Usage
30 | 1. Call upon the script from a PowerShell window with applicable rights for WMI and follow the prompts.
31 | 2. Data will be saved to a new directory called "PoSH_R2--Results" within the same directory from which this script was executed from.
32 | # Additional Notes
33 | - This script will work with PowerShell version 2 and above 34 | 35 | # Screenshots
36 |
37 | 38 | Running the script
39 | ![Alt text](https://github.com/WiredPulse/PoSh-R2/blob/master/Screenshots/1-Script_Execution.png?raw=true "Optional Title")
40 |
41 | A listing of the results written to csv files
42 | ![Alt text](https://github.com/WiredPulse/PoSh-R2/blob/master/Screenshots/2.1-Results.png?raw=true "Optional Title")
43 |
44 |
45 | A listing of the databases
46 | ![Alt text](https://github.com/WiredPulse/PoSh-R2/blob/master/Screenshots/2-Results.png?raw=true "Optional Title")
47 |
48 |
49 | Reading the data back into PowerShell using out-gridview (import-csv .\ | out-gridview)
50 | ![Alt text](https://github.com/WiredPulse/PoSh-R2/blob/master/Screenshots/3-Results2.png?raw=true "Optional Title")
51 |
52 | Filtering only on splunk.exe. From the screenshot, we see it is running on six systems
53 | ![Alt text](https://github.com/WiredPulse/PoSh-R2/blob/master/Screenshots/4-Filter.PNG?raw=true "Optional Title") 54 | -------------------------------------------------------------------------------- /Screenshots/1-Script_Execution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/Screenshots/1-Script_Execution.png -------------------------------------------------------------------------------- /Screenshots/2-Results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/Screenshots/2-Results.png -------------------------------------------------------------------------------- /Screenshots/2.1-Results.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/Screenshots/2.1-Results.png -------------------------------------------------------------------------------- /Screenshots/3-Results2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/Screenshots/3-Results2.png -------------------------------------------------------------------------------- /Screenshots/4-Filter.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WiredPulse/PoSh-R2/c9eb5a22113046ceeccad8c631f266c79ee8306a/Screenshots/4-Filter.PNG --------------------------------------------------------------------------------