Get Devicename as String from MTP-Device - powershell

I try to automatically copy files from MTP-Devices (Smartphones) to my PC. I took several little code snippets from the internet for that and a lot of trial and error (several days), because I have no idea about powershell. But now everything works fine so far. The only problem is, that I have to manually put the name in for a device in my script, every time I took an other device. So I'm searching for a solution to automatically get the name from the actual device and save it in a variable.
I have tried this code:
Get-WmiObject -class win32_pnpentity -computername localhost | where-object {$_.HardwareID -like "*MTP*"} | format-list
As result i get:
__GENUS : 2
__CLASS : Win32_PnPEntity
__SUPERCLASS : CIM_LogicalDevice
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_PnPEntity.DeviceID="USB\\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_ANDROID\\6&5F679FC&0
&0000"
__PROPERTY_COUNT : 26
__DERIVATION : {CIM_LogicalDevice, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : EXO-SURFACE
__NAMESPACE : root\cimv2
__PATH : \\EXO-SURFACE\root\cimv2:Win32_PnPEntity.DeviceID="USB\\VID_04E8&PID_6860&MS_COMP_MTP&SAM
SUNG_ANDROID\\6&5F679FC&0&0000"
Availability :
Caption : Galaxy S9+
ClassGuid : {eec5ad98-8080-425f-922a-dabf3de3f69a}
CompatibleID : {USB\MS_COMP_MTP, USB\Class_06&SubClass_01&Prot_01, USB\Class_06&SubClass_01,
USB\Class_06...}
ConfigManagerErrorCode : 0
ConfigManagerUserConfig : False
CreationClassName : Win32_PnPEntity
Description : SM-G965F
DeviceID : USB\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_ANDROID\6&5F679FC&0&0000
ErrorCleared :
ErrorDescription :
HardwareID : {USB\VID_04E8&PID_6860&REV_0400&MS_COMP_MTP&SAMSUNG_Android,
USB\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_Android,
USB\SAMSUNG_MOBILE&MS_COMP_MTP&SAMSUNG_Android, USB\SAMSUNG_MOBILE&MI_00...}
InstallDate :
LastErrorCode :
Manufacturer : Samsung Electronics Co., Ltd.
Name : Galaxy S9+
PNPClass : WPD
PNPDeviceID : USB\VID_04E8&PID_6860&MS_COMP_MTP&SAMSUNG_ANDROID\6&5F679FC&0&0000
PowerManagementCapabilities :
PowerManagementSupported :
Present : True
Service : WUDFWpdMtp
Status : OK
StatusInfo :
SystemCreationClassName : Win32_ComputerSystem
SystemName : EXO-SURFACE
PSComputerName : EXO-SURFACE
This looks very fine, because for the Name it's recognized as "Galaxy S9+" like it should. So do anyone here know, how to extract this Device Name into an variable? I would be very thankful, because I am a real noob in powershell and it's a project to help my parents, who have their problems with technology.

Related

How Get All Camera Devices ID From PowerShell

I am trying to get all camera devices ID and respective names using PowerShell command line. I tried several commands, but nothing has done what I am aiming. Below my "best" approach:
Get-CimInstance Win32_PnPEntity | where caption -match 'camera'
output
Caption : Remote Desktop Camera Bus
Description : UMBus Enumerator
InstallDate :
Name : Remote Desktop Camera Bus
Status : OK
Availability :
ConfigManagerErrorCode : 0
ConfigManagerUserConfig : False
CreationClassName : Win32_PnPEntity
DeviceID : UMB\UMB\1&841921D&0&RDCAMERA_BUS
ErrorCleared :
ErrorDescription :
LastErrorCode :
PNPDeviceID : UMB\UMB\1&841921D&0&RDCAMERA_BUS
PowerManagementCapabilities :
PowerManagementSupported :
StatusInfo :
SystemCreationClassName : Win32_ComputerSystem
SystemName : DESKTOP
ClassGuid : {4d36e97d-e325-11ce-bfc1-08002be10318}
CompatibleID :
HardwareID : {UMB\UMBUS}
Manufacturer : Microsoft
PNPClass : System
Present : True
Service : umbus
PSComputerName :
I know, for example, that generally the integrated camera has a name "integrated camera" with a ID "0". But this is not what is being shown.
Get-CimInstance Win32_PnPEntity | ? { $_.service -eq "usbvideo" } | Select-Object -Property PNPDeviceID, Name

Get ADUser attributes without Get-ADUser

Is it possible to get current users AD attributes without Get-ADUser?
Am new to powershell. I need to get few attributes like title, email & department for user.
I tried use :
get-wmiobject -Class win32_useraccount -Filter "name='John.Doe'" | select *
PSComputerName : NY-Z343
Status : OK
Caption : BEAZL-INC\john.doe
PasswordExpires : False
__GENUS : 2
__CLASS : Win32_UserAccount
__SUPERCLASS : Win32_Account
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
__PROPERTY_COUNT : 16
__DERIVATION : {Win32_Account, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : NY-Z343
__NAMESPACE : rootcimv2
__PATH : \BEAZL-INCrootcimv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
AccountType : 512
Description : Dude account for gaming
Disabled : False
Domain : BEAZL-INC
FullName : John Doe
InstallDate :
LocalAccount : False
Lockout : False
Name : john.doe
PasswordChangeable : True
PasswordRequired : False
SID : S-1-5-21-3384058-193304-10174538-501
SIDType : 1
Scope : System.Management.ManagementScope
Path : \\NY-Z343\root\clmv2:Win32_UserAccount.Domain="BEAZL-INC",Name="john.doe"
Options : System.Management.ObjectGetOptions
ClassPath : \\NY-Z34\root\clmv2:Win32_UserAccount
Properties : {AccountType, Caption, Description, Disabled...}
SystemProperties : {__GENUS, __CLASS, __SUPERCLASS, __DYNASTY...}
Qualifiers : {dynamic, Locale, provider, UUID}
Site :
Container :
Yes, you can use [adsisearcher], which is a type accelerator for .NET's DirectorySearcher class. This doesn't require installing anything additional.
Here's an example that will search for a user by the name attribute and return the title, mail, and department attributes:
# This is the search filter
$searcher = [adsisearcher]"(&(objectClass=user)(objectCategory=person)(name=John.Doe))"
# List all the propterties you want to use
$searcher.PropertiesToLoad.AddRange(#("title", "mail", "department"))
# By default, it will search the same domain as the logged in user.
# If you need to search a different domain, uncomment and edit this line.
# $searcher.SearchRoot = [adsi]"LDAP://example.com"
$user = $searcher.FindOne()
$title = $user.Properties["title"][0]

Powershell WMI trigger - action when specific device is plugged in

I want to trigger a script when a specific USB Device is plugged in, I've researched Register-WmiEvent but I'm really confused at how to approach it correctly.
So far I have successfully isolated the device as such :
Get-WmiObject win32_PNPEntity | where {$_.Caption -eq "Lexar USB Flash Drive USB Device"}
This is the WMI object returned :
_GENUS : 2
__CLASS : Win32_PnPEntity
__SUPERCLASS : CIM_LogicalDevice
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : Win32_PnPEntity.DeviceID="USBSTOR\\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\\AAEDZZ5RVJ47QS4K&0"
__PROPERTY_COUNT : 26
__DERIVATION : {CIM_LogicalDevice, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : P7409
__NAMESPACE : root\cimv2
__PATH : \\P7409\root\cimv2:Win32_PnPEntity.DeviceID="USBSTOR\\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\\AAEDZZ5RVJ47QS4K&0"
Availability :
Caption : Lexar USB Flash Drive USB Device
ClassGuid : {4d36e967-e325-11ce-bfc1-08002be10318}
CompatibleID : {USBSTOR\Disk, USBSTOR\RAW, GenDisk}
ConfigManagerErrorCode : 0
ConfigManagerUserConfig : False
CreationClassName : Win32_PnPEntity
Description : Lecteur de disque
DeviceID : USBSTOR\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\AAEDZZ5RVJ47QS4K&0
ErrorCleared :
ErrorDescription :
HardwareID : {USBSTOR\DiskLexar___USB_Flash_Drive_1100, USBSTOR\DiskLexar___USB_Flash_Drive_, USBSTOR\DiskLexar___, USBSTOR\Lexar___USB_Flash_Drive_1...}
InstallDate :
LastErrorCode :
Manufacturer : (Lecteurs de disque standard)
Name : Lexar USB Flash Drive USB Device
PNPClass : DiskDrive
PNPDeviceID : USBSTOR\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\AAEDZZ5RVJ47QS4K&0
PowerManagementCapabilities :
PowerManagementSupported :
Present : True
Service : disk
Status : OK
StatusInfo :
SystemCreationClassName : Win32_ComputerSystem
SystemName : P7409
PSComputerName : P7409
How should I approach the event part?
Is there a way to write it so it works like "When the instance containing that Caption exists...do this" ?
I'm trying :
$query = "Select * FROM __InstanceModificationEvent WITHIN 1 WHERE TargetInstance ISA 'win32_PNPEntity' and TargetInstance.Caption = 'Lexar USB Flash Drive USB Device'"
Register-WMIEvent -Query $query -Action { Write-Host "LEXAR FLASH DRIVE CONNECTED"} -SourceIdentifier TEST
But nothing happens when I plug/unplug it.
I experimented with:
$query = "SELECT * FROM win32_DeviceChangeEvent"
Register-WMIEvent -Query $query -Action {Write-Host "ALERT"}
This work but it triggers when ANY device is connected/disconnected. I want to be able to isolate just that device with the Lexar caption.
Much appreciated.
There is a lot of documentation online about WMI events but nothing really clear for something like this so here is how I got it working, I'm sure it'll be useful for many others.
What you want to do is register an event when the instance of your device is CREATED and when it's DELETED. (in our case this is synonymous to PLUGGED IN and UNPLUGGED)
So you have to first find the ID of the instance that gets created when you plug in the device. Mine is:
Win32_PnPEntity.DeviceID="USBSTOR\\DISK&VEN_LEXAR&PROD_USB_FLASH_DRIVE&REV_1100\\AAEDZZ5RVJ47QS4K&0"
*That device ID was causing me trouble (I think because of all the sepcial characters in it) so I did a match with parts of the string instead of the whole thing, it works just as well.
Here is how to create the two events:
#Event when plugged in (InstanceCreationEvent)
$query = "Select * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'win32_PNPEntity' and TargetInstance.DeviceID like 'USBSTOR%LEXAR%AAEDZZ5RVJ47QS4K%'"
Register-WMIEvent -Query $query -Action { msg * lexar connected} -SourceIdentifier LexarConnect
#Event when disconnected (InstanceDeletionEvent)
$query = "Select * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'win32_PNPEntity' and TargetInstance.DeviceID like 'USBSTOR%LEXAR%AAEDZZ5RVJ47QS4K%'"
Register-WMIEvent -Query $query -Action { msg * lexar disconnected} -SourceIdentifier LexarDisconnect
Like I said above, the DeviceID was creating errors so I used parts of the string with the WQL wildcard character "%" (using : like USBSTOR%LEXAR%AAEDZZ5RVJ47QS4K% matches the good DeviceID without having to use the whole string)
WMI Events are powerful stuff! Enjoy!

Receiving invalid data via WMI

I've had a script running for the better half of a year now that checks for disk space, should it be low it sends out an email been working just fine.
Today I received an alert saying that that Disk space was at 0gb.. I logged into the server and had about 30gbs available.
Part of code that checks the space.
[decimal]$thresholdspace = 5
$tableFragment= Get-WMIObject -ComputerName $computer Win32_LogicalDisk `
| select __SERVER, DriveType, VolumeName, Name, #{n='Size (Gb)' ;e={"{0:n2}" -f ($_.size/1gb)}},#{n='FreeSpace (Gb)';e={"{0:n2}" -f ($_.freespace/1gb)}}, #{n='PercentFree';e={"{0:n2}" -f ($_.freespace/$_.size*100)}} `
| Where-Object {$_.DriveType -eq 3 -and [decimal]$_.PercentFree -lt [decimal]$thresholdspace}
So I opened up an ISE session and did the following.
$computer = 'Server_01'
Get-WMIObject -ComputerName $computer Win32_LogicalDisk | select __SERVER, DriveType, VolumeName, Name,FreeSpace
and it responded with:
__SERVER : Server_01
DriveType : 2
VolumeName :
Name : A:
FreeSpace :
__SERVER : Server_01
DriveType : 3
VolumeName :
Name : C:
FreeSpace : 31372767232
__SERVER : Server_01
DriveType : 5
VolumeName :
Name : E:
FreeSpace :
So I then ran the part of my code that is getting space and it returned with the following:
__SERVER : Server_01
DriveType : 3
VolumeName :
Name : C:
Size (Gb) : 0.00
FreeSpace (Gb) : 0.00
PercentFree :
So I ran the simple WMI query and it responded with no data..
__SERVER : Server_01
DriveType : 2
VolumeName :
Name : A:
FreeSpace :
__SERVER : Server_01
DriveType : 3
VolumeName :
Name : C:
FreeSpace :
__SERVER : Server_01
DriveType : 5
VolumeName :
Name : E:
FreeSpace :
Any idea as to why I'm getting invalid or what appears to be incomplete data? I've never seen anything like this, and have not ran into this issue at all before. Nothing has changed on either server it is running from.

hot to get network adapters names except microsoft's ones

Hi I want to get the name of all the network adapters from my computer except the Microsoft ones.
ServiceName : RTL8168
MACAddress : ---------------
AdapterType : Ethernet 802.3
DeviceID : 0
Name : D-Link DGE-528T Gigabit Ethernet Adapter
NetworkAddresses :
Speed : 1000000000
ServiceName : kdnic
MACAddress :
AdapterType :
DeviceID : 1
Name : Microsoft Kernel Debug Network Adapter
NetworkAddresses :
Speed :
ServiceName : e1express
MACAddress : ---------------
AdapterType : Ethernet 802.3
DeviceID : 2
Name : Intel(R) 82562V-2 10/100 Network Connection
NetworkAddresses :
Speed : 9223372036854775807
ServiceName : tunnel
MACAddress :
AdapterType : Tunnel
DeviceID : 3
Name : Microsoft ISATAP Adapter
NetworkAddresses :
Speed : 100000
ServiceName :
MACAddress :
AdapterType :
DeviceID : 4
Name : Microsoft Teredo Tunneling Adapter
NetworkAddresses :
Speed :
This is what I have so far (I don't know the correct regular expression that shows only the adapters that doesn't contain "Microsoft" on its Name object)
get-wmiobject win32_networkadapter | Where-Object {$_.Name -match "^[^M]"}
I want to get this output:
ServiceName : RTL8168
MACAddress : ---------
AdapterType : Ethernet 802.3
DeviceID : 0
Name : D-Link DGE-528T Gigabit Ethernet Adapter
NetworkAddresses :
Speed : 1000000000
ServiceName : e1express
MACAddress : -------------
AdapterType : Ethernet 802.3
DeviceID : 2
Name : Intel(R) 82562V-2 10/100 Network Connection
NetworkAddresses :
Speed : 9223372036854775807
Thank you guys in advance, I know this one is easy :)
In powershell something like
Get-NetAdapter | where-object Name -NotContains Microsoft
upd.: in comments already answered