Small Tricks and Tips – PowerShell – CSV file – writing string / append string – exploring New-Object PSObject

fig : PowerShell - Exploring New-Object - Help on New-Object
fig : PowerShell - Exploring New-Object - Help on New-Object

Hi All,

Greetings for the day!!!

Today new small learning for me so sharing . SHARING IS CARING 🙂

Use Case / Scenario

  • I was writing PowerShell script for doing some my SharePoint online operation
  • I am using Try-Catch block for handling exceptions
  • I need to log exceptions in CSV file so that later we could go through exceptions and verify
  • I know how to write / export our SharePoint result in CSV but when I need to write single string I need to google
  • Bit googled and found the solution. So as usual sharing 🙂

Detailed steps to write a string to CSV file

  • Create a object of type PSObject
  • Specify the column name and string while creating PSObject
  • Use CMDLET Export-Csv method to append object to CSV file
  • We already have very good article for writing objects / arrays to CSV file, please have a look – Write a CSV file with PowerShell using the Export-CSV

Example 1 Writing simple string to CSV / TXT file

#writing simple string to CSV file
$str1 = "Life Is Beautiful"


$objStr = New-Object PSObject -Property @{ MotivationalText = $str1 }

Export-Csv -InputObject $objStr -Path "C:\Prasham\Articles\PowerShell\CSVfileoperations\csvfiledemo.csv" -NoTypeInformation

  • Here in above example we are writing string – “Life Is Beautiful” to csv file – csvfiledemo.csv
  • When script is executed CSV file is generated on given path
fig : PowerShell - using Export-CSV to write the string in CSV / TEXT file
fig : PowerShell – using Export-CSV to write the string in CSV / TEXT file
  • What is New-Object
    • New-Object CMDLET is used to create new object
    • New-Object cmdlet was introduced in PowerShell v1.0
    • Creates an instance of a Microsoft .NET Framework or COM object

New-Object
   [-TypeName] <String>
   [[-ArgumentList] <Object[]>]
   [-Property <IDictionary>]
   [<CommonParameters>]


New-Object
   [-ComObject] <String>
   [-Strict]
   [-Property <IDictionary>]
   [<CommonParameters>]

  • We can get help on New-Object using Get-Help CMDLET
Get-Help New-Object

PS C:\> C:\Prasham\Articles\PowerShell\csvfileoperations\newobject.ps1

NAME
    New-Object
    
SYNOPSIS
    Creates an instance of a Microsoft .NET Framework or COM object.
    
    
SYNTAX
    New-Object [-TypeName] <System.String> [[-ArgumentList] <System.Object[]>] [-Property <System.Collections.IDictionary>] 
    [<CommonParameters>]
    
    New-Object [-ComObject] <System.String> [-Property <System.Collections.IDictionary>] [-Strict] [<CommonParameters>]
    
    
DESCRIPTION
    The `New-Object` cmdlet creates an instance of a .NET Framework or COM object.
    
    You can specify either the type of a .NET Framework class or a ProgID of a COM object. By default, you type the fully qualified name of 
    a .NET Framework class and the cmdlet returns a reference to an instance of that class. To create an instance of a COM object, use the 
    ComObject parameter and specify the ProgID of the object as its value.
    

RELATED LINKS
    Online Version: 
    https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/new-object?view=powershell-5.1&WT.mc_id=ps-gethelp
    about_Object_Creation 
    Compare-Object 
    Group-Object 
    Measure-Object 
    Select-Object 
    Sort-Object 
    Tee-Object 

REMARKS
    To see the examples, type: "get-help New-Object -examples".
    For more information, type: "get-help New-Object -detailed".
    For technical information, type: "get-help New-Object -full".
    For online help, type: "get-help New-Object -online"

PowerShell - Exploring New-Object - Help on New-Object
fig : PowerShell – Exploring New-Object – Help on New-Object
  • Namespace: System.Management.Automation
  • Assembly:System.Management.Automation.dll
  • Package:System.Management.Automation v7.2.7
  • New-Object PSObject creates hashtable like object where data is stored in Key-Value pair

Example 2 – Demo of New-Object PSObject – creating simple two columns / keys

$_PSObject = New-Object -TypeName psobject -Property @{AFFIRMATION1 = 'LIFE IS BEAUTIFUL';AFFIRMATION2 = 'WE ARE VERY RICH'}

$_PSObject

OUTPUT - 
PS C:\> C:\Prasham\Articles\PowerShell\csvfileoperations\newobject.ps1

AFFIRMATION2     AFFIRMATION1     
------------     ------------     
WE ARE VERY RICH LIFE IS BEAUTIFUL

  • Here in above example we have created two keys (columns)

Example 3 – Writing exception message string to CSV file

Try {
    #code block goes here
}
catch{
        write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
        $error1 = New-Object PSObject -Property @{ Exceptions = "Error: $($_.Exception.Message)"}
        $error1 | Export-Csv -Append -Path "C:\ErrorLogs.csv" -NoTypeInformation
}

  • In above example we are creating object with key – “Exceptions” and value – “Exception message” and appending to CSV file
  • Here please note, as a key – Heading of column in CSV file – once it is created it wont get created again

REFERENCES

If you want to explore more on PowerShell with Microsoft 365 or want to prepare interview for PowerShell for Microsoft 365 – please refer my book – Microsoft 365 Power Shell hand book for Administrators and Beginners and 100 Power Shell Interview Questions

 Microsoft 365 Power Shell hand book for Administrators and Beginners and 100 Power Shell Interview Questions

Thanks for reading! HAVE A FANTASTIC TIME AHEAD!!!

Prasham Sabadra

LIFE IS VERY BEAUTIFUL :) ENJOY THE WHOLE JOURNEY :) Founder of Knowledge Junction and live-beautiful-life.com, Author, Learner, Passionate Techie, avid reader. Certified Professional Workshop Facilitator / Public Speaker. Scrum Foundation Professional certificated. Motivational, Behavioral , Technical speaker. Speaks in various events including SharePoint Saturdays, Boot camps, Collages / Schools, local chapter. Can reach me for Microsoft 365, Azure, DevOps, SharePoint, Teams, Power Platform, JavaScript.

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: