This is my first time writing a script on PowerShell, and I want to move it
·Return assigned drive when USB is inserted
That's what it means.I use two USBs, so depending on the order of insertion, it can be D or E, so
This is the script that you will check then.
This is the first process of the whole thing you want to do, so you can't solve it externally (check it when a person inserts it).
Also, when I touched it for the first time, I watched videos and websites, but there was nothing I wanted, so I would appreciate it if you could send me a sample code.
windows-10 powershell
You can get a list of logical drives in Get-WmiObject
and CIM_LogicalDisk
.
Removable disks are listed with DriveType=2
.
Search the Win32_LogicalDisk document for DriveType.
How to display attached USB devices with drive letter using powershell
Get-WmiObject CIM_LogicalDisk | Where-Object DriveType-eq2 | Select-Object DeviceID
# a rewriting of the above description using aliases
gwmicim_logicaldisk | ?drivetype-eq2 | select deviceid
You can also monitor events using Register-WmiEvent
if you want to take any action when USB is inserted.
Receiving a WMI Event
By rewriting -Action
by referring to the answers below, you can run any function when inserting a USB.
Start PowerShell script when USB drive is inserted
Answer code excerpt (comment translation)
# Defines a query for WMI events.Here we detect the addition of Win32_LogicalDisk with DriveType "2".
# # http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx
$Query="select* from__InstanceCreationEvent with in 5where TargetInstanceISA'Win32_LogicalDisk' and TargetInstance.DriveType=2";
# Defines the Powershell script to run when an event occurs.
$Action={&C:\test\script.ps1;};
# Register an event.
Register-WmiEvent-Query $Query-Action $Action-SourceIdentifier USBFlashDrive;
© 2024 OneMinuteCode. All rights reserved.