Freigeben über


Do Your Own Thing - Creating a New Object from Scratch in Powershell V1 to Populate and have your Script Output a nice Object Instead of just Strings

I use PSObject all the time. Now when I write scripts I nearly always output an object and unless I can just add to an existing type that is close, I create my own. I copied from one of my recent ones below to show how I do it. Now this isn’t a complete script. $arrobjects would obvisouly be full of object that have the properties I used. You can though see how I build up the object to be used as the “template”, give it null properties, then each time through the loop use that template to create a temp object with that instances actual value. Then I simply put that object into a new array which will be the final output of this code…an array of my custom objects. I hope this is useful to you.

 

#We want this script to output a real, useful object, so lets create a template object to use to create out result

#objects to add to our array result

$objTemplateObject = New-Object psobject

$objTemplateObject | Add-Member -MemberType NoteProperty -Name EffectiveDate -Value $null

$objTemplateObject | Add-Member -MemberType NoteProperty -Name FullPath -Value $null

$objTemplateObject | Add-Member -MemberType NoteProperty -Name Name -Value $null

$objTemplateObject | Add-Member -MemberType NoteProperty -Name FileDateLastModified -Value $null

 

#Create the Blank array which will ultimately become the output object

$objResult = @()

 

 

foreach($objcurrent in $arrobjects)

{

#create an instance of our new object to prepare it with data and later add it to the result array

#The select-object changes the object from a ref to a value..there is likely a better way to do this, but this works only because I am already using a PSObject which is what this will produce.

$objTemp = $objTemplateObject | Select-Object *

    

#lets now populate our custom properties

$objTemp.Name = $objcurrent.Name

$objTemp.FullPath = $objcurrent.FullName

$objTemp.FileDateLastModified = $objcurrent.LastWriteTime

$objTemp.EffectiveDate = $dtmDateTaken

 

    

#Our temp object is ready, lets add it to our output array and get ready to loop back around

$objResult += $objTemp

}

 

$objResult

 

 

This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm.

Comments

  • Anonymous
    October 29, 2010
    Thank you so much! Just like you I want my output to be in an object. I tried to write directly to, what would be in your script, $objTemplateObject but kept getting errors. By doing it exactly like you did it finally works, after 2 hours of trial and error.

  • Anonymous
    September 19, 2014
    Thank you very much. Glad that I found this thumbs up