Home > front end >  PowerShell ForEach-Object within Pipeline
PowerShell ForEach-Object within Pipeline

Time:10-04

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

CodePudding user response:

Please use select-object instead of For-each object

Get-CimInstance -ClassName Win32_DiskDrive | where{$.InterfaceType -eq 'USB'} |Select-object -Property DeviceId,Model,Size

CodePudding user response:

#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
  • Related