Author Posts

February 12, 2018 at 8:20 pm

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

February 12, 2018 at 8:22 pm

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.

February 12, 2018 at 9:13 pm

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

February 13, 2018 at 12:41 pm

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.

February 13, 2018 at 2:44 pm

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'