1

I want to get the instanceID of a device just as a string and assign it to a variable

I only know the device name, so when I do:

Get-PnpDevice -FriendlyName 'TSP100'

It displays:

Status     Class           FriendlyName       InstanceId                                                              
------     -----           ------------      ------------                                                               
OK         PrintQueue      TSP100            SWD\PRIN...                                                               

so ideally it would look something like this:

$env:tsp100id = (Get-PnpDevice -FriendlyName 'TSP100' *some stuff*)
Cybergenik
  • 130
  • 1
  • 5
  • 11

1 Answers1

5

Why not just ask for the property, like this...

# Assign the first instanceId of the target device to a variable
$env:tsp100id = Get-PnpDevice -FriendlyName 'Generic USB Hub' | 
Select-Object -Property InstanceId | 
Select-Object -First 1
$env:tsp100id

# Results
<#
@{InstanceId=USB\VID_05E3&PID_0610\8&26FFBCBB&0&1}
#>

# Assign and output to the screen
($env:tsp100id = (Get-PnpDevice -FriendlyName 'Generic USB Hub').InstanceId[0])

# Results
<#
USB\VID_05E3&PID_0610\8&26FFBCBB&0&1
#>

Also, just curious. Why are you assigning this as an environment entry?

As for ...

Also how would I go about removing the USB\VID_05E3&PID_0610\ and just getting the 8&26FFBCBB&0&1

The simplest way in this case is just split on the backslash. For example:

(($env:tsp100id = (Get-PnpDevice -FriendlyName 'Generic USB Hub').InstanceId[0]) -split '\\')[-1]
# Results
<#
8&26FFBCBB&0&1
#>

This just says split on the backslash and take action on the last one first.

postanote
  • 15,138
  • 2
  • 14
  • 25
  • This will work perfectly, thank you! We have a few services that need to have that device id for the TSP100 printer and a few of the bootstrapping scripts would use that env variable when first setting up that printer. – Cybergenik Feb 02 '20 at 04:44
  • Also how would I go about removing the `USB\VID_05E3&PID_0610\ ` and just getting the `8&26FFBCBB&0&1` – Cybergenik Feb 02 '20 at 04:51
  • Hey postanote, the script has been failing ever so often because sometimes the FriendlyName isn't always just 'TSP100', sometimes its got other stuff. Is there any way I can use Regex to solve this issue? something like '*TSP100*' – Cybergenik Feb 06 '20 at 18:40
  • Yep, just try '*TSP100*' – postanote Feb 06 '20 at 23:25