Question on building an object

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

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.

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

https://stackoverflow.com/questions/30145539/openfiles-query-to-see-open-files

Well it might not be the best solution.

  • Declare $objectarray as an array before your. For Loop
<li>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.

    This may be helpful:

    https://cdn-powershell.pressidium.com/wp-content/uploads/2018/02/Iron-Scripter-Prequel-Puzzle-4-A-commentary.pdf

    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'
    		$OpenFiles
    	}
    }