0

I'm just learning powershell and trying to understand how looping works on ForEach Object. I was able to make this script work that detect USB Storage attached to a device

Get-CimInstance -ClassName Win32_DiskDrive | 
    where {$_.InterfaceType -eq 'USB'} | 
    ForEach-Object{"`n`n",$_ } | 
    Format-list -Property DeviceId,Model,Size

Output:

DeviceId : \\.\PHYSICALDRIVE1Model    : WD My Passport 0740 USB DeviceSize     : 1000169372160

DeviceId : \\.\PHYSICALDRIVE2Model    : TOSHIBA TransMemory USB DeviceSize     : 7748213760

However I'm having hardtime targeting the value of each to move it to the next line. the result should be something like this

If I ran the script in Powershell console by using format-list it display perfect however on a webpage it won't display accordingly. How can I use the backtick (`n) so that the result of DeviceID, Model and Size will be on a separate line.

I will appreciate any help. thank you guys

2 Answers 2

2

Please use select-object instead of For-each object

Get-CimInstance -ClassName Win32_DiskDrive | where{$.InterfaceType -eq 'USB'} |Select-object -Property DeviceId,Model,Size
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much @Dilly B. Appreciate it
@RamuMagaranesu - Please mark an answer to close this thread.
0
#You can filter at CIM level, no need to do it at shell level, also you can specify the list of properties to retrieve
$data = Get-CimInstance -query "Select DeviceId,Model,Size from Win32_DiskDrive where InterfaceType='usb'"

#If you want a string with the format: [PropertyName]:[PropertyValue]`n[PropertyName]:[PropertyValue]...
$stringArray = @(
    $data | %{
        "DeviceId: $($_.DeviceId)`nModel: $($_.Model)`nSize: $($_.Size)"
    }
)

Output ($stringArray):

DeviceId: \\.\PHYSICALDRIVE1
Model: Generic USB Flash Disk USB Device
Size: 15512878080


#Maybe convertto-html is of use for you?
$data | ConvertTo-Html

1 Comment

Thank you so much @Toni Appreciate your help h

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.