Ads

Wednesday, 5 April 2017

Powershell to create & write result output in CSV file as per need

Write below functions to achieve the same

---------------- Function that will receive CSV file name and create one CSV file -----------
 Function CreateExcelLogFile($LogFileName)  #$LogFileName is the output CSV file name
{
    $Date_Time = Get_DateTime #Call a function to get DateTime to append in output csv file
    $CurrentPath = Get-ScriptDirectory #Call function to get current file path

    Try
    {       
        $JobLogPath = $CurrentPath            
        if(!(Test-Path $JobLogPath))  #Create folder path if not exists
        {
           New-Item -Path $JobLogPath -ItemType directory
        }
        $JobLogPath = $JobLogPath + "\" + $LogFileName + "_" + $Date_Time + ".csv"
    }
    Catch
    { }   
    return $JobLogPath
}
----------------------- Function to get the current execution Script path ---------------------
function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}
----------------------- Function to get date time to append in output file ---------
function Get_DateTime()
{
    $LogFileDayF = Get-Date -Format "s";
    $LogFileDateTime = $LogFileDayF.Replace(":","_")                          
    return $LogFileDateTime;
}
----------------------- Function to write in CSV file -----------
function Write-To-Excel-File($logFilePath, $Column1_Value, $Column2_SiteURL)
{   
    $Column2_SiteURL = $Column2_SiteURL.Replace(',','%2C') #Replace , with %20
    if((Test-Path $logFilePath) -eq $false)
    {
        New-Item $logFilePath -type file | Out-Null
        Add-Content -Path $logFilePath -Value 'Column1 Header,Column2 Header'
    }

    $msg = "$($Column1_Value),$($Column2_SiteURL)"
    Add-Content -path $logFilePath -value $msg
}
---------------------- Main execution point to call different functions functions -------------
#Call Create excel file function with one parameter to create CSV file 
$Excel_FilePath_WithExt = CreateExcelLogFile 'Output_CSV_FileName'

#Call write to excel function with 3 parameter to write in CSV file
Write-To-Excel-File $Excel_FilePath_WithExt "Son of Adam" "Addison"
Write-To-Excel-File $Excel_FilePath_WithExt "Man of Earth" "Adam"
Write-To-Excel-File $Excel_FilePath_WithExt "Father of Light" "Abner"

----------------------- Out put file in CSV format --------------
Output_CSV_FileName.csv

You can also see PowerShell to read rows from excel file

No comments:

Post a Comment

Ads