Key takeaways
- USB device monitoring: The script is vital for detecting and alerting IT professionals about USB device connections.
- Security enhancement: Helps in preventing unauthorized data access and transfer through USB drives.
- Customizable alerting: Offers flexibility with optional custom field logging for tailored alerting and recording.
- Cross-version compatibility: Works with PowerShell 5 and later, ensuring broad compatibility across Windows systems.
- Real-time alerts: Provides immediate notifications upon USB connection, enabling swift security responses.
- Minimized dependency: Eliminates the need for third-party monitoring software, integrating directly into system operations.
- Data collection: Gathers comprehensive information about connected USB devices, aiding in security analysis and decision-making.
- Simple yet effective: The script is straightforward in its approach but powerful in its application for IT security.
- Integration with management tools: Can be seamlessly integrated with management frameworks like NinjaOne for enhanced IT operations.
- Essential for IT infrastructure: A crucial tool in the arsenal of IT professionals and MSPs for maintaining network security and integrity.
Background
USB devices are ubiquitous, convenient, and, unfortunately, a common vector for security threats. For IT professionals and MSPs, monitoring USB device connections is critical to prevent unauthorized data access or transfer. The PowerShell script in question is designed for this purpose. It alerts administrators when a USB drive is connected to a system and optionally records the event, enhancing security and oversight in network environments.
The script:
<# .SYNOPSIS Alerts when a USB drive is detected and optionally saves the results to a Custom Field. .DESCRIPTION Alerts when a USB drive is detected and optionally saves the results to a Custom Field. .EXAMPLE (No Parameters) No USB Drives are present. .EXAMPLE (No Parameters) C:\Users\KyleBohlander\Documents\bitbucket_clientscripts\client_scripts\src\Test-USBDrive.ps1 : A USB Drive has been detected! At line:1 char:1 + .\src\Test-USBDrive.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : LimitsExceeded: (:) [Write-Error], Exception + FullyQualifiedErrorId : System.Exception,Test-USBDrive.ps1 Index Caption SerialNumber Partitions ----- ------- ------------ ---------- 1 Samsung Flash Drive USB Device AA00000000000489 1 PARAMETER: -CustomFieldName "replaceMeWithACustomFieldName" Name of a custom field to save the results to. This is optional; results will also output to the activity log. .OUTPUTS None .NOTES Minimum supported OS: Windows 10, Server 2012 R2 Release Notes: Initial Release By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use. Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA). #> [CmdletBinding()] param ( [Parameter()] [String]$CustomFieldName ) begin { # Grab CustomFieldName from dynamic script form if ($env:customFieldName -and $env:customFieldName -notlike "null") { $CustomFieldName = $env:customFieldName } # Initialize exit code $ExitCode = 0 # Initialize generic list for the report $Report = New-Object System.Collections.Generic.List[String] $CustomFieldReport = New-Object System.Collections.Generic.List[String] } process { # Get a list of USB drives $USBDrives = if ($PSVersionTable.PSVersion.Major -ge 5) { Get-CimInstance win32_diskdrive | Where-Object { $_.InterfaceType -eq 'USB' } } else { Get-WmiObject win32_diskdrive | Where-Object { $_.InterfaceType -eq 'USB' } } # Alert if a USB drive is detected if ($USBDrives) { Write-Error -Message "A USB Drive has been detected!" -Category LimitsExceeded -Exception (New-Object -TypeName System.Exception) # Grab relevant information about the USB Drive $USBDrives | ForEach-Object { $Report.Add( ($_ | Format-Table Index, Caption, SerialNumber, Partitions | Out-String) ) if ($CustomFieldName) { $CustomFieldReport.Add( ($_ | Format-List Index, Caption, SerialNumber, Partitions | Out-String) ) } $Report.Add( (Get-Partition -DiskNumber $_.Index | Get-Volume | Format-Table DriveLetter, FriendlyName, DriveType, HealthStatus, SizeRemaining, Size | Out-String) ) if ($CustomFieldName) { $CustomFieldReport.Add( (Get-Partition -DiskNumber $_.Index | Get-Volume | Format-List DriveLetter, FriendlyName, DriveType, HealthStatus, SizeRemaining, Size | Out-String) ) } } # Change exit code to indicate failure/alert $ExitCode = 1 } else { # If no drives were found we'll need to indicate that. $Report.Add("No USB Drives are present.") if ($CustomFieldName) { $CustomFieldReport.Add("No USB Drives are present.") } } # Write to the activity log Write-Host $Report # Save to custom field if given one if ($CustomFieldName) { Write-Host "" Ninja-Property-Set -Name $CustomFieldName -Value $CustomFieldReport } # Exit with appropriate exit code Exit $ExitCode } end { }
Access over 300+ scripts in the NinjaOne Dojo
Detailed breakdown
The script operates in three phases: Initialization, Processing, and Termination.
- Initialization: It begins by checking if a custom field name is provided through the environment variable $env:customFieldName. This custom field name is used for logging purposes. The script initializes two lists, $Report and $CustomFieldReport, to store information about detected USB drives.
- Processing: The script uses Get-CimInstance or Get-WmiObject (depending on the PowerShell version) to list USB drives connected to the system. If any are found, it triggers an error with a message indicating the detection of a USB drive. The script then collects detailed information about each drive, including index, caption, serial number, partitions, and other volume details. This data is added to the $Report and $CustomFieldReport lists.
- Termination: The script concludes by outputting the contents of $Report to the activity log. If a custom field name is provided, it also sets this information in the specified custom field using Ninja-Property-Set.
Potential use cases
Imagine an IT administrator at a financial institution. They need to ensure sensitive data isn’t leaked via USB devices. By deploying this script, they can receive immediate alerts upon USB device connections, enabling swift action to mitigate potential security risks.
Comparisons
Traditional methods of monitoring USB activities involve manual checks or using third-party software. This PowerShell script offers a more integrated and customizable approach, providing real-time alerts without the need for additional software installations.
FAQs
Q: Can this script run on any Windows system?
A: The script is designed for Windows 10 and Server 2012 R2 or newer.
Q: What happens if no USB drive is detected?
A: The script will simply report that no USB drives are present, avoiding false alarms.
Q: Is it possible to modify the script for specific needs?
A: Absolutely. PowerShell scripts are highly customizable.
Implications
The script’s ability to detect USB devices in real-time is crucial for maintaining data integrity and security. Unauthorized USB devices can be vectors for malware or tools for data exfiltration. Early detection enables IT teams to respond quickly to potential threats.
Recommendations
- Regular Updates: Keep the script and PowerShell environment updated to ensure compatibility and security.
- Customization: Tailor the script to fit specific organizational needs and policies.
- Testing: Regularly test the script in a controlled environment to ensure its effectiveness.
Final thoughts
In the context of IT security and management, NinjaOne offers robust solutions that complement PowerShell scripts like this one. By integrating such scripts into broader IT management frameworks, NinjaOne helps streamline operations, enhance security, and ensure the seamless functioning of IT infrastructures. This script is a testament to the power of PowerShell in the modern IT toolkit, providing critical capabilities for monitoring and securing IT environments.