Powershell: Export a custom object to a CSV file - extract a single property value with Select-Object












1















I wrote a script that constructs a custom object and exports it to a CSV file:



$reg = Get-ItemProperty HKLM:SOFTWAREMcAfeeDLPAgent | Select-Object agentversion

$date = Get-ItemProperty 'C:Program FilesMcAfee' | Select-Object {$_.LastWriteTime}

$date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'| Select-Object {$_.LastWriteTime}

New-Object -TypeName pscustomobject -Property @{
"Number1"=$reg
"Number2"=$date86
"Number3"=$date } | export-csv -Path C:****desktopstuff.csv -NoTypeInformation


and the data row in the resulting CSV file is:




"@{AgentVersion=9.4.112.22}","@{$.LastWriteTime=5/6/2016 6:02:32 AM}","@{$.LastWriteTime=7/5/2016 8:34:01 PM}"




Is it possible to get rid of the unwanted @{<name>=...} wrappers?










share|improve this question





























    1















    I wrote a script that constructs a custom object and exports it to a CSV file:



    $reg = Get-ItemProperty HKLM:SOFTWAREMcAfeeDLPAgent | Select-Object agentversion

    $date = Get-ItemProperty 'C:Program FilesMcAfee' | Select-Object {$_.LastWriteTime}

    $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'| Select-Object {$_.LastWriteTime}

    New-Object -TypeName pscustomobject -Property @{
    "Number1"=$reg
    "Number2"=$date86
    "Number3"=$date } | export-csv -Path C:****desktopstuff.csv -NoTypeInformation


    and the data row in the resulting CSV file is:




    "@{AgentVersion=9.4.112.22}","@{$.LastWriteTime=5/6/2016 6:02:32 AM}","@{$.LastWriteTime=7/5/2016 8:34:01 PM}"




    Is it possible to get rid of the unwanted @{<name>=...} wrappers?










    share|improve this question



























      1












      1








      1








      I wrote a script that constructs a custom object and exports it to a CSV file:



      $reg = Get-ItemProperty HKLM:SOFTWAREMcAfeeDLPAgent | Select-Object agentversion

      $date = Get-ItemProperty 'C:Program FilesMcAfee' | Select-Object {$_.LastWriteTime}

      $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'| Select-Object {$_.LastWriteTime}

      New-Object -TypeName pscustomobject -Property @{
      "Number1"=$reg
      "Number2"=$date86
      "Number3"=$date } | export-csv -Path C:****desktopstuff.csv -NoTypeInformation


      and the data row in the resulting CSV file is:




      "@{AgentVersion=9.4.112.22}","@{$.LastWriteTime=5/6/2016 6:02:32 AM}","@{$.LastWriteTime=7/5/2016 8:34:01 PM}"




      Is it possible to get rid of the unwanted @{<name>=...} wrappers?










      share|improve this question
















      I wrote a script that constructs a custom object and exports it to a CSV file:



      $reg = Get-ItemProperty HKLM:SOFTWAREMcAfeeDLPAgent | Select-Object agentversion

      $date = Get-ItemProperty 'C:Program FilesMcAfee' | Select-Object {$_.LastWriteTime}

      $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'| Select-Object {$_.LastWriteTime}

      New-Object -TypeName pscustomobject -Property @{
      "Number1"=$reg
      "Number2"=$date86
      "Number3"=$date } | export-csv -Path C:****desktopstuff.csv -NoTypeInformation


      and the data row in the resulting CSV file is:




      "@{AgentVersion=9.4.112.22}","@{$.LastWriteTime=5/6/2016 6:02:32 AM}","@{$.LastWriteTime=7/5/2016 8:34:01 PM}"




      Is it possible to get rid of the unwanted @{<name>=...} wrappers?







      powershell export-to-csv select-object






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 17 '18 at 18:59









      mklement0

      134k21250288




      134k21250288










      asked Jul 11 '16 at 23:44









      C.KellyC.Kelly

      612




      612
























          2 Answers
          2






          active

          oldest

          votes


















          1














          The expression:



          Select-Object {$_.LastWriteTime}


          outputs an object with a single property with name $_.LastWriteTime. The simplest way to fix it is to use the -ExpandProperty parameter which will only output the value that you are interested in. e.g.:



          $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'|
          Select-Object -ExpandProperty LastWriteTime


          Note that I've also removed the script block from the Select-Object command, as it wasn't necessary.






          share|improve this answer

































            1














            To complement zdan's helpful answer[1]
            with alternatives:



            If you just want the value of a given object's property, simply wrap the command in (...) and use .<propertyName>:



            (Get-ItemProperty 'C:Program FilesMcAfee').LastWriteTime # returns a [datetime] instance


            In PSv3+, the above also works with commands returning multiple items (arrays), in which case an array of the input items' individual property values is output - this feature is called member enumeration.





            PSv3 introduced a shortcut syntax for % / ForEach-Object (and also ? / Where-Object) that can be leveraged here as well :



            Get-ItemProperty 'C:Program FilesMcAfee' | % LastWriteTime # ditto


            This is the equivalent of the more verbose (which also works in PSv2-):



            Get-ItemProperty 'C:Program FilesMcAfee' | % { $_.LastWriteTime }


            These two pipeline-based syntax forms are slower, but have two advantages:




            • Large input collections are better processed in pipelines one by one in order to keep memory use constant (if feasible; if you need to collect the entire output in memory, there is no advantage).



            • This syntax unambiguously references an individual item's property rather than a property of the collection as a whole.




              • E.g., (Get-ChildItem -File C:Windows).Length returns the count of files in C:Windows, because Length is interpreted as the collection's (array's) property;

                by contrast, Get-ChildItem -File C:Windows | % Length returns an array of the individual files' .Length (file-size) property values.




            Finally, in PSv4+, you may also use the .ForEach() collection method, which doesn't use the pipeline and is therefore faster (though slightly slower than member enumeration), but, like member enumeration, requires that the input collection be in memory in full:



            (Get-ItemProperty 'C:Program FilesMcAfee').ForEach('LastWriteTime')




            [1] A quick overview of Select-Object's behavior:




            • Select-Object [-Property] <string> returns a custom object for each input object, containing only the specified properties; even with only a single property specified, the results are custom objects with that single property, not the property values themselves.


            • By contrast, using -ExpandProperty <string> returns the given, single property's value from each input object (typed as-is) instead.



            A simple example: extract the Year property value from a Get-Date call:



            # WRONG: with (implied) -Property
            PS> $val = Get-Date | Select-Object Year; "$val"
            @{Year=2018} # !!
            # A custom object with a Year property was returned and the above is its
            # string representation, the equivalent of:
            # "$([pscustomobject] @{ Year = 2018 })"

            # CORRECT: with -ExpandProperty
            PS> $val = Get-Date | Select-Object -ExpandProperty Year; "$val"
            2018 # OK: -ExpandProperty extracted just the property's *value*





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38317882%2fpowershell-export-a-custom-object-to-a-csv-file-extract-a-single-property-val%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              The expression:



              Select-Object {$_.LastWriteTime}


              outputs an object with a single property with name $_.LastWriteTime. The simplest way to fix it is to use the -ExpandProperty parameter which will only output the value that you are interested in. e.g.:



              $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'|
              Select-Object -ExpandProperty LastWriteTime


              Note that I've also removed the script block from the Select-Object command, as it wasn't necessary.






              share|improve this answer






























                1














                The expression:



                Select-Object {$_.LastWriteTime}


                outputs an object with a single property with name $_.LastWriteTime. The simplest way to fix it is to use the -ExpandProperty parameter which will only output the value that you are interested in. e.g.:



                $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'|
                Select-Object -ExpandProperty LastWriteTime


                Note that I've also removed the script block from the Select-Object command, as it wasn't necessary.






                share|improve this answer




























                  1












                  1








                  1







                  The expression:



                  Select-Object {$_.LastWriteTime}


                  outputs an object with a single property with name $_.LastWriteTime. The simplest way to fix it is to use the -ExpandProperty parameter which will only output the value that you are interested in. e.g.:



                  $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'|
                  Select-Object -ExpandProperty LastWriteTime


                  Note that I've also removed the script block from the Select-Object command, as it wasn't necessary.






                  share|improve this answer















                  The expression:



                  Select-Object {$_.LastWriteTime}


                  outputs an object with a single property with name $_.LastWriteTime. The simplest way to fix it is to use the -ExpandProperty parameter which will only output the value that you are interested in. e.g.:



                  $date86 = Get-ItemProperty 'C:Program Files (x86)McAfee'|
                  Select-Object -ExpandProperty LastWriteTime


                  Note that I've also removed the script block from the Select-Object command, as it wasn't necessary.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 17 '18 at 19:01









                  mklement0

                  134k21250288




                  134k21250288










                  answered Jul 12 '16 at 0:06









                  zdanzdan

                  21.9k34764




                  21.9k34764

























                      1














                      To complement zdan's helpful answer[1]
                      with alternatives:



                      If you just want the value of a given object's property, simply wrap the command in (...) and use .<propertyName>:



                      (Get-ItemProperty 'C:Program FilesMcAfee').LastWriteTime # returns a [datetime] instance


                      In PSv3+, the above also works with commands returning multiple items (arrays), in which case an array of the input items' individual property values is output - this feature is called member enumeration.





                      PSv3 introduced a shortcut syntax for % / ForEach-Object (and also ? / Where-Object) that can be leveraged here as well :



                      Get-ItemProperty 'C:Program FilesMcAfee' | % LastWriteTime # ditto


                      This is the equivalent of the more verbose (which also works in PSv2-):



                      Get-ItemProperty 'C:Program FilesMcAfee' | % { $_.LastWriteTime }


                      These two pipeline-based syntax forms are slower, but have two advantages:




                      • Large input collections are better processed in pipelines one by one in order to keep memory use constant (if feasible; if you need to collect the entire output in memory, there is no advantage).



                      • This syntax unambiguously references an individual item's property rather than a property of the collection as a whole.




                        • E.g., (Get-ChildItem -File C:Windows).Length returns the count of files in C:Windows, because Length is interpreted as the collection's (array's) property;

                          by contrast, Get-ChildItem -File C:Windows | % Length returns an array of the individual files' .Length (file-size) property values.




                      Finally, in PSv4+, you may also use the .ForEach() collection method, which doesn't use the pipeline and is therefore faster (though slightly slower than member enumeration), but, like member enumeration, requires that the input collection be in memory in full:



                      (Get-ItemProperty 'C:Program FilesMcAfee').ForEach('LastWriteTime')




                      [1] A quick overview of Select-Object's behavior:




                      • Select-Object [-Property] <string> returns a custom object for each input object, containing only the specified properties; even with only a single property specified, the results are custom objects with that single property, not the property values themselves.


                      • By contrast, using -ExpandProperty <string> returns the given, single property's value from each input object (typed as-is) instead.



                      A simple example: extract the Year property value from a Get-Date call:



                      # WRONG: with (implied) -Property
                      PS> $val = Get-Date | Select-Object Year; "$val"
                      @{Year=2018} # !!
                      # A custom object with a Year property was returned and the above is its
                      # string representation, the equivalent of:
                      # "$([pscustomobject] @{ Year = 2018 })"

                      # CORRECT: with -ExpandProperty
                      PS> $val = Get-Date | Select-Object -ExpandProperty Year; "$val"
                      2018 # OK: -ExpandProperty extracted just the property's *value*





                      share|improve this answer






























                        1














                        To complement zdan's helpful answer[1]
                        with alternatives:



                        If you just want the value of a given object's property, simply wrap the command in (...) and use .<propertyName>:



                        (Get-ItemProperty 'C:Program FilesMcAfee').LastWriteTime # returns a [datetime] instance


                        In PSv3+, the above also works with commands returning multiple items (arrays), in which case an array of the input items' individual property values is output - this feature is called member enumeration.





                        PSv3 introduced a shortcut syntax for % / ForEach-Object (and also ? / Where-Object) that can be leveraged here as well :



                        Get-ItemProperty 'C:Program FilesMcAfee' | % LastWriteTime # ditto


                        This is the equivalent of the more verbose (which also works in PSv2-):



                        Get-ItemProperty 'C:Program FilesMcAfee' | % { $_.LastWriteTime }


                        These two pipeline-based syntax forms are slower, but have two advantages:




                        • Large input collections are better processed in pipelines one by one in order to keep memory use constant (if feasible; if you need to collect the entire output in memory, there is no advantage).



                        • This syntax unambiguously references an individual item's property rather than a property of the collection as a whole.




                          • E.g., (Get-ChildItem -File C:Windows).Length returns the count of files in C:Windows, because Length is interpreted as the collection's (array's) property;

                            by contrast, Get-ChildItem -File C:Windows | % Length returns an array of the individual files' .Length (file-size) property values.




                        Finally, in PSv4+, you may also use the .ForEach() collection method, which doesn't use the pipeline and is therefore faster (though slightly slower than member enumeration), but, like member enumeration, requires that the input collection be in memory in full:



                        (Get-ItemProperty 'C:Program FilesMcAfee').ForEach('LastWriteTime')




                        [1] A quick overview of Select-Object's behavior:




                        • Select-Object [-Property] <string> returns a custom object for each input object, containing only the specified properties; even with only a single property specified, the results are custom objects with that single property, not the property values themselves.


                        • By contrast, using -ExpandProperty <string> returns the given, single property's value from each input object (typed as-is) instead.



                        A simple example: extract the Year property value from a Get-Date call:



                        # WRONG: with (implied) -Property
                        PS> $val = Get-Date | Select-Object Year; "$val"
                        @{Year=2018} # !!
                        # A custom object with a Year property was returned and the above is its
                        # string representation, the equivalent of:
                        # "$([pscustomobject] @{ Year = 2018 })"

                        # CORRECT: with -ExpandProperty
                        PS> $val = Get-Date | Select-Object -ExpandProperty Year; "$val"
                        2018 # OK: -ExpandProperty extracted just the property's *value*





                        share|improve this answer




























                          1












                          1








                          1







                          To complement zdan's helpful answer[1]
                          with alternatives:



                          If you just want the value of a given object's property, simply wrap the command in (...) and use .<propertyName>:



                          (Get-ItemProperty 'C:Program FilesMcAfee').LastWriteTime # returns a [datetime] instance


                          In PSv3+, the above also works with commands returning multiple items (arrays), in which case an array of the input items' individual property values is output - this feature is called member enumeration.





                          PSv3 introduced a shortcut syntax for % / ForEach-Object (and also ? / Where-Object) that can be leveraged here as well :



                          Get-ItemProperty 'C:Program FilesMcAfee' | % LastWriteTime # ditto


                          This is the equivalent of the more verbose (which also works in PSv2-):



                          Get-ItemProperty 'C:Program FilesMcAfee' | % { $_.LastWriteTime }


                          These two pipeline-based syntax forms are slower, but have two advantages:




                          • Large input collections are better processed in pipelines one by one in order to keep memory use constant (if feasible; if you need to collect the entire output in memory, there is no advantage).



                          • This syntax unambiguously references an individual item's property rather than a property of the collection as a whole.




                            • E.g., (Get-ChildItem -File C:Windows).Length returns the count of files in C:Windows, because Length is interpreted as the collection's (array's) property;

                              by contrast, Get-ChildItem -File C:Windows | % Length returns an array of the individual files' .Length (file-size) property values.




                          Finally, in PSv4+, you may also use the .ForEach() collection method, which doesn't use the pipeline and is therefore faster (though slightly slower than member enumeration), but, like member enumeration, requires that the input collection be in memory in full:



                          (Get-ItemProperty 'C:Program FilesMcAfee').ForEach('LastWriteTime')




                          [1] A quick overview of Select-Object's behavior:




                          • Select-Object [-Property] <string> returns a custom object for each input object, containing only the specified properties; even with only a single property specified, the results are custom objects with that single property, not the property values themselves.


                          • By contrast, using -ExpandProperty <string> returns the given, single property's value from each input object (typed as-is) instead.



                          A simple example: extract the Year property value from a Get-Date call:



                          # WRONG: with (implied) -Property
                          PS> $val = Get-Date | Select-Object Year; "$val"
                          @{Year=2018} # !!
                          # A custom object with a Year property was returned and the above is its
                          # string representation, the equivalent of:
                          # "$([pscustomobject] @{ Year = 2018 })"

                          # CORRECT: with -ExpandProperty
                          PS> $val = Get-Date | Select-Object -ExpandProperty Year; "$val"
                          2018 # OK: -ExpandProperty extracted just the property's *value*





                          share|improve this answer















                          To complement zdan's helpful answer[1]
                          with alternatives:



                          If you just want the value of a given object's property, simply wrap the command in (...) and use .<propertyName>:



                          (Get-ItemProperty 'C:Program FilesMcAfee').LastWriteTime # returns a [datetime] instance


                          In PSv3+, the above also works with commands returning multiple items (arrays), in which case an array of the input items' individual property values is output - this feature is called member enumeration.





                          PSv3 introduced a shortcut syntax for % / ForEach-Object (and also ? / Where-Object) that can be leveraged here as well :



                          Get-ItemProperty 'C:Program FilesMcAfee' | % LastWriteTime # ditto


                          This is the equivalent of the more verbose (which also works in PSv2-):



                          Get-ItemProperty 'C:Program FilesMcAfee' | % { $_.LastWriteTime }


                          These two pipeline-based syntax forms are slower, but have two advantages:




                          • Large input collections are better processed in pipelines one by one in order to keep memory use constant (if feasible; if you need to collect the entire output in memory, there is no advantage).



                          • This syntax unambiguously references an individual item's property rather than a property of the collection as a whole.




                            • E.g., (Get-ChildItem -File C:Windows).Length returns the count of files in C:Windows, because Length is interpreted as the collection's (array's) property;

                              by contrast, Get-ChildItem -File C:Windows | % Length returns an array of the individual files' .Length (file-size) property values.




                          Finally, in PSv4+, you may also use the .ForEach() collection method, which doesn't use the pipeline and is therefore faster (though slightly slower than member enumeration), but, like member enumeration, requires that the input collection be in memory in full:



                          (Get-ItemProperty 'C:Program FilesMcAfee').ForEach('LastWriteTime')




                          [1] A quick overview of Select-Object's behavior:




                          • Select-Object [-Property] <string> returns a custom object for each input object, containing only the specified properties; even with only a single property specified, the results are custom objects with that single property, not the property values themselves.


                          • By contrast, using -ExpandProperty <string> returns the given, single property's value from each input object (typed as-is) instead.



                          A simple example: extract the Year property value from a Get-Date call:



                          # WRONG: with (implied) -Property
                          PS> $val = Get-Date | Select-Object Year; "$val"
                          @{Year=2018} # !!
                          # A custom object with a Year property was returned and the above is its
                          # string representation, the equivalent of:
                          # "$([pscustomobject] @{ Year = 2018 })"

                          # CORRECT: with -ExpandProperty
                          PS> $val = Get-Date | Select-Object -ExpandProperty Year; "$val"
                          2018 # OK: -ExpandProperty extracted just the property's *value*






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 26 '18 at 3:19

























                          answered Jul 12 '16 at 2:23









                          mklement0mklement0

                          134k21250288




                          134k21250288






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38317882%2fpowershell-export-a-custom-object-to-a-csv-file-extract-a-single-property-val%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              404 Error Contact Form 7 ajax form submitting

                              How to know if a Active Directory user can login interactively

                              Refactoring coordinates for Minecraft Pi buildings written in Python