Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Sunday, January 27, 2019

Import-Csv and Export-Csv PowerShell cmdlets


Many times we need to export data in CSV files and read specific information from it. Best example would be log files which contain lots of data but we want to read some specific information from it like Errors, Warnings etc.

In this small article I’ll explain how we can export data to csv files using Export-CSV cmdlets and import csv files and read specific information from it using Import-CSV cmdlets.

Export-Csv


This command will export data into csv file. In below example I exported latest 100 Application event log entries to logs.csv file.

Get-EventLog Application -Newest 100 | Export-Csv logs.csv








You can verify data inside csv file using below command.

Get-Content logs.csv












Import-Csv


This command will import data from CSV file. You can specify delimiter and headers to load only selected columns from csv file.

Script –

#specify path
$path = "C:\PowerShell\logs.csv"
#import csv file and specify specific columns you want to import using -Header
$file = Import-Csv $path -Delimiter ","
#$file
#loop all the rows in file
foreach ($row in $file)
{
    #condition to read only Errors
    if ($row.EntryType -like '*Error*')
    {
        Write-Host "---------------------------------------------"
        Write-Host $row.EntryType
        Write-Host $row.TimeGenerated
        Write-Host $row.Message
        Write-Host "---------------------------------------------"
    }
}

Output –



You can download code from Gist.

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See Also –

Saturday, September 22, 2018

Date Time operations with PowerShell


In this article, I’ll go through various date time operations you can perform using PowerShell.

Get-Date

You can use Get-Date cmdlet to get today’s date.




Below commands can be used to display only Date or Time.

Get-Date -DisplayHint Time
Get-Date -DisplayHint Date


You can also specify format to display date and time. You can use –Format parameter with Get-Date and specify ‘G’ format specifier to get General short date and short time.

Get-Date -Format G

You can use –UFormat parameter to specify custom format of date time.

Get-Date -UFormat "%d, %B, %Y, %A %r %t"

You can use foreach with get-date to get format as per your need.

Get-Date -Format F
Get-Date -Format F | foreach {$_ -replace ":", "-"}

You can find for all the properties of DateTime using Get-Member cmdlets.

Get-Date | Get-Member -MemberType Properties

You can get date time values as per your need using properties and methods of Date Time object.

Get-Date).TimeOfDay


Below are some output of Get-Date properties and methods can be used as per your requirements.

Properties/Methods
Output
(Get-Date).Date
02 March 2018 00:00:00
(Get-Date).Day
2
(Get-Date).DayOfWeek
Friday
(Get-Date).DayOfYear
61
(Get-Date).Hour
18
(Get-Date).Minute
48
(Get-Date).Month
3
(Get-Date).Second
5
(Get-Date).Millisecond
227
(Get-Date).IsDaylightSavingTime()
False
(Get-Date).ToShortDateString()
02-03-2018
(Get-Date).ToShortTimeString()
06:54 PM
(Get-Date).ToUniversalTime()
02 March 2018 13:26:17

You can add or remove date or time to current display date time using below various methods.

Methods
Output
(Get-Date).AddDays(10)
12 March 2018 19:01:09
(Get-Date).AddDays(-10)
20 February 2018 19:01:52
(Get-Date).AddYears(2)
02 March 2020 19:07:18
(Get-Date).AddMonths(3)
02 June 2018 19:04:48
(Get-Date).AddHours(3)
02 March 2018 22:03:48
(Get-Date).AddMinutes(23)
02 March 2018 19:28:54
(Get-Date).AddSeconds(40)
02 March 2018 19:06:58

You can find difference between two dates using below command.

(Get-Date).DayOfYear - (Get-Date -year 2018 -month 11 -date 20).DayOfYear



You can also create New-TimeSpan object to represent date at some interval of days or time. You can also check date time of that timespan.

(Get-Date) - (New-TimeSpan -Days 20)
(Get-Date) - (New-TimeSpan -Days -20)

Set-Date

You can change system date and time using Set-Date cmdlet. You can specify new date and time to Set-Date and it will change your system date and time. You need administrator privileges to execute Set-Date command.

Set-Date -Date (Get-Date).AddDays(5)
Set-Date -Date (Get-Date).AddDays(-5)

I hope you have now some knowledge about some basic date and time operations that you can perform in PowerShell. Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See Also –

Sunday, July 29, 2018

How to execute PowerShell script or cmdlets from C# code?


Sometimes you need to execute PowerShell script or commands from C# code. In this article I’ll explain various methods to execute PowerShell scripts and commands from C# code.

You can execute PowerShell scripts using PowerShell object available in ‘System.Management.Automation’ namespace. This assembly is available in Nuget for download. You can create PowerShell instance and assign script file or command which you would like to execute. You can also get output from PowerShell command after execution and read data from PSObject object.

Let’s have look on below example which executes PowerShell scripts from C# code.

Code –

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;

static void Main(string[] args)
{
    using (PowerShell PowerShellInst = PowerShell.Create())
    {
        string criteria = "system*";
        PowerShellInst.AddScript("Get-Service -DisplayName " + criteria);
        Collection<PSObject> PSOutput = PowerShellInst.Invoke();
        foreach (PSObject obj in PSOutput)
        {
            if (obj != null)
            {
                Console.Write(obj.Properties["Status"].Value.ToString() + " - ");
                Console.WriteLine(obj.Properties["DisplayName"].Value.ToString());
            }
        }
        Console.WriteLine("Done");
        Console.Read();
    }
}

Output –


Now I want to execute below PowerShell script file using C# code.
Code –

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;

static void Main(string[] args)
{
    //Execute PS1 (PowerShell script) file
    using (PowerShell PowerShellInst = PowerShell.Create())
    {
        string path = System.IO.Path.GetDirectoryName(@"C:\Temp\") + "\\Get-EventLog.ps1";
        if (!string.IsNullOrEmpty(path))
            PowerShellInst.AddScript(System.IO.File.ReadAllText(path));

        Collection<PSObject> PSOutput = PowerShellInst.Invoke();
        foreach (PSObject obj in PSOutput)
        {
            if (obj != null)
            {
                Console.Write(obj.Properties["EntryType"].Value.ToString() + " - ");
                Console.Write(obj.Properties["Source"].Value.ToString() + " - ");
                Console.WriteLine(obj.Properties["Message"].Value.ToString() + " - ");
            }
        }
        Console.WriteLine("Done");
        Console.Read();
    }
}

Output –

Command Prompt - You can execute PowerShell scripts and command using PowerShell.exe like below in command prompt.

Similarly you can invoke PowerShell process from C# code and pass command as argument. See below example how execute PowerShell process from code and pass cmdlet as argument.

Code –

using System;
using System.Management.Automation;
using System.Collections.ObjectModel;

static void Main(string[] args)
{
    //execute powershell cmdlets or scripts using command arguments as process
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.FileName = @"powershell.exe";
    //execute powershell script using script file
    //processInfo.Arguments = @"& {c:\temp\Get-EventLog.ps1}";
    //execute powershell command
    processInfo.Arguments = @"& {Get-EventLog -LogName Application -Newest 10 -EntryType Information | Select EntryType, Message}";
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;
    processInfo.UseShellExecute = false;
    processInfo.CreateNoWindow = true;

    //start powershell process using process start info
    Process process = new Process();
    process.StartInfo = processInfo;
    process.Start();

    //read output
    Console.WriteLine("Output - {0}", process.StandardOutput.ReadToEnd());
    //read errors
    Console.WriteLine("Errors - {0}", process.StandardError.ReadToEnd());
    Console.Read();
}

Output –

You can download code from Gist.

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See Also –

Saturday, May 12, 2018

Read Excel file data using PowerShell script

We quite often need to read data from Excel file (.xlsx) and perform some action on it. In this article I’ll explain how to open Excel file in PowerShell and read data from it.

I want read below data available in my sample excel file using PowerShell script.

Let’s have a look on below PowerShell script which reads data from sample excel file.

PS Script - 

#select excel file you want to read
$file = "C:\PowerShell\MyContacts.xlsx"
$sheetName = "Sheet1"

#create new excel COM object
$excel = New-Object -com Excel.Application

#open excel file
$wb = $excel.workbooks.open($file)

#select excel sheet to read data
$sheet = $wb.Worksheets.Item($sheetname)

#select total rows
$rowMax = ($sheet.UsedRange.Rows).Count

#create new object with Name, Address, Email properties.
$myData = New-Object -TypeName psobject
$myData | Add-Member -MemberType NoteProperty -Name Name -Value $null
$myData | Add-Member -MemberType NoteProperty -Name Address -Value $null
$myData | Add-Member -MemberType NoteProperty -Name Email -Value $null

#create empty arraylist
$myArray = @()

for ($i = 2; $i -le $rowMax; $i++)
{
    $objTemp = $myData | Select-Object *
   
    #read data from each cell
    $objTemp.Name = $sheet.Cells.Item($i,1).Text
    $objTemp.Address = $sheet.Cells.Item($i,2).Text
    $objTemp.Email = $sheet.Cells.Item($i,3).Text
    #Write-Host 'Name-' $objTemp.Name 'Address-' $objTemp.Address 'Email-' $objTemp.Email
   
    $myArray += $objTemp
}
#print $myarry object
#$myArray
#print $myarry object with foreach loop
foreach ($x in $myArray)
{
    Echo $x
}

$excel.Quit()

#force stop Excel process
Stop-Process -Name EXCEL -Force

Output –


You can download code from Gist.

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See Also –