Question on building an object

This topic contains 5 replies, has 5 voices, and was last updated by  Aaron 3 months ago.

  • Author
  • #93502


    I want to create an object based on the cmd command

    (openfiles /query /s SERVERNAME)

    I can get all the properties in the fashion I want by doing a split, and the below works on adding the last item in the array to the object...but how can i get them all listed in the object so i could do a command like...

    $object | ? {$_.'accessed by' -eq "Username"}
    foreach($line in (openfiles /query /s SERVERNAME))
    	$props = @{
    	ID = ($line.Split(" ") | ?{$_ -notlike ""})[0]
    	'Accessed By' = ($line.Split(" ") | ?{$_ -notlike ""})[1]
    	Type = ($line.Split(" ") | ?{$_ -notlike ""})[2]
    	'Open File (Path\executable)' = ($line.Split(" ") | ?{$_ -notlike ""})[3]
    $object = new-object psobject -Property $props
  • #93504

    Don Jones

    You're on the right track. You're not trying to create AN objects, though, you need to create MULTIPLE OBJECTS. One object for each whatever it is you want.

    You'd normally do this in a function, and the function uses Write-Output to emit each object, as it's created, to the pipeline. You could then pipe them to something else.

  • #93507


    Some ways to do it here, like either exporting to csv or using get-smbopenfile instead:

  • #93529


    Well it might not be the best solution.

    • Declare $objectarray as an array before your. For Loop
    • Move $object = New-Object PSobject -properties $prop
      within the closing brace } of the for loop
    • Then use $objectarray += $object inside the loop as well
    • In the end $objectarray will have an array of objects.

    **This is the way I used to do things too, but no longer ** Since being on this forum, and reading a lot about Powershell I now write functions as Don Jones suggested. Maybe look into this solution when you have the time.

  • #93531

  • #93544


    Thanks Jon! That article was very helpful. I was able to complete the task using the below code:

    function Get-OpenFiles
    	(openfiles /query /s SERVERNAME) |
    	Select-Object -Skip 3 |
    	ForEach-Object {
    		$OpenFiles = $_.Trim() |
    		ConvertFrom-String -PropertyNames 'ID','Accessed By','Type','Open File (Path\executable)'
    		$OpenFiles.PSTypeNames[0] ='SMB.OpenFiles'

You must be logged in to reply to this topic.