Enumerating over objects

Looping Through a Collection of Objects.

There are two ways of enumerating over objects. One may be considered easier than the other. Nevertheless the two ways are shown below.


Using a WHILE loop and GetEnumerator.

$lines = @('a', 'b', 'c', 'd', 'e', 'f');
$enumerator = $lines.GetEnumerator();

while ($enumerator.MoveNext()) {


Using a foreach loop.

$lines = @('a', 'b', 'c', 'd', 'e');
foreach ($item in $lines) {
   Write-Host $item;

See also

Foreach-Object Cmdlet

Posted in powershell | Tagged , | Leave a comment

Creating CSV files for use with Excel

CSV files

Working on a recent project, I was using PowerShell to manipulate a list of MS Word documents that I had to process. Reading other articles on the Internet, I realised how useful it would be if I could create a list of files of interest in a CSV file and import this into Microsoft Excel in the usual way.

Although the example given is looking at PDF files, the principle is the same.


Get-ChildItem -Path $inputPath -Filter *.pdf -Recurse |
    Select-Object DirectoryName, Name, LastWriteTime |
    Export-Csv -Path $outputCsv -Encoding ascii -NoTypeInformation;

The Select-Object Cmdlet is used to select the file attributes I want in my CSV file.


See also

Use PowerShell to Create CSV File to Open in Excel

Using the Select-Object Cmdlet

Select-Object Cmdlet

Keywords: powershell csv import

Posted in powershell | Tagged , | Leave a comment

PowerShell and Unix crontables

Recently, I working on ways of documenting crontables we had on the various Unix servers we had a responsibility for. In the end I opted for a PowerShell solution to create an XML file for each of the crontables.

The program looks as follows:

# Creates an XML file from the output of the Unix command
# $ crontab -l > cron.txt.
# This program is also an example of creating XML files from PowerShell.

function Write-Dataline($xwriter, $cronbits, $id) {

  $xwriter.WriteAttributeString("ID", "$id");




write-output ("error thing = $($cronbits.ErrorRedirect)");
  $xwriter.WriteFullEndElement();     # <-- Close element ''Line''.

} #end function Write-Dataline

function Close-XmlFile($xwriter) {

  Write-Host "Closing the xml file";
  # The closing bits of the XML file
  $xwriter.WriteEndElement();     # <-- Close root element
  $xwriter.WriteEndDocument();    # <-- Close the document

  # Finish The Document

} #end function Close-XmlFile

function Get-Lineparts([String]$str) {
  begin {
    $props = [ordered]@{
       DateTime = "";
       Executable = "";
       Logfile = "";
       ErrorRedirect = "";
    $cronbits = New-Object psobject -Property $props;

    $props = [ordered]@{
       Start = 0;
       End = 0;
    $pos = New-Object psobject -Property $props;
  } #end begin

  process {

    # Get the date/time part of the cron line.

    # Get the executable, i.e. the shell script bit.
    $pos.End=$str.IndexOf('>', $pos.End);

    # Get the logfile name.
    $pos.Start=$str.IndexOf('/', $pos.End);
    $pos.End=$str.IndexOf('2>&1', $pos.End);

    # Get the error redirect.

  } #end process

  end {
    return $cronbits;
  } #end end

} #end function Get-Lineparts

function Set-XmlWriterSettings {

  $xsettings = New-Object -TypeName System.Xml.XmlWriterSettings;
  $xsettings.CloseOutput = $true;
  $xsettings.Encoding = [System.Text.Encoding]::UTF8;
  $xsettings.Indent = $true;
  $xsettings.IndentChars = "    "; # 4 spaces
  $xsettings.WriteEndDocumentOnClose = $true;
  $xsettings.CheckCharacters = $true;
  #$xsettings.NewLineChars = "0xoa";
  $xsettings.NewLineOnAttributes = $true;
  $xsettings.OmitXmlDeclaration = $false;
  $xsettings.ConformanceLevel = [System.Xml.ConformanceLevel]::Auto;

  return $xsettings;

} #end function Set-XmlWriterSettings

function Set-XmlFile {

  # Do some initialising
  $filePath = "C:\ian\PowerShell\good03.xml";
  $xset = Set-XmlWriterSettings;
  [System.Xml.XmlWriter]$xwriter = [System.Xml.XmlWriter]::Create($filePath,$xset);

  # Write the header elements to our XML file
  $xwriter.WriteStartDocument();               # <-- Start the document
  $xwriter.WriteStartElement("CronTable");     # <-- Important root element





  return $xwriter;

} #end function Set-XmlFile

# ------------------------
# Main routine starts here
# ------------------------

$input = New-Object -TypeName System.IO.StreamReader -ArgumentList $infile;

#Create and write the header to the XmlFile.

$inrec = $input.ReadLine();
while ($inrec -ne $null) {
   Write-Output ($inrec);
   $cronbits=Get-Lineparts $inrec;
   Write-Dataline $xwriter $cronbits $counter;
   $cronbits | Format-list;

   $inrec = $input.ReadLine();



Write-Host "`nRecords read: $counter";
Write-Host "The date is $ymd";

Input and output files are hard coded so the program could be more flexible.

Input file – is at line 148.

Output file – is at line 113.

The input file is created on the Unix server with the command:

$ crontab -l > inputfile.txt

The man page will cover this command. The input file I used was:

15,30,45,0 * * * * /u01/Acer/MorrisGarages/exec/GreenBank.sh > /u01/Acer/MorrisGarages/GreenBank.log 2>&1
45 19 * * * /u04/Acer/Minolta/exec/Hartung–Boothroyd.sh > /u04/Acer/Minolta/logs/Hartung–Boothroyd.log 2>&1
25 04 * * * /u04/Boeing/Digital/Jodrell-Bank.sh > /u04/Boeing/Digital/Jodrell-Bank.log 2>&1

The output XML file will look like this:

<?xml version="1.0" encoding="utf-8"?>
            <CronTime>15,30,45,0 * * * *</CronTime>
            <CronTime>45 19 * * *</CronTime>
            <CronTime>25 04 * * *</CronTime>

The XML tag CronLines contain details of each of the lines in my example input file. The ID attribute indicating which line in particular. So the tag <Line ID=”3″> gives the detail for line 3 of my input file, Jodrell-Bank.sh.

Lines 156-165 is the main processing loop in which each line is read in from the input file.

Line 160 invokes function Get-Lineparts passing to it, an input record.

Funtion Set-XmlWriterSettings specifies a set of features to support on the XmlWriter object. See XmlWriterSettings Class for further details. This is really initialising my XML object. How many character spaces to indent and so on.

Function Write-Dataline writes data to the tags CronTime, Executable, Logfile and ErrorRedirect.

Function Get-Lineparts tokenizes the input string record into its constituent parts.

Posted in powershell | Tagged , | Leave a comment

.NET List Class

The .NET List Class represents a strongly typed list of objects. It also provides methods to search, sort, and manipulate lists.

The following code gives an example on how the List Class can be used.

#Initialize a new instance of the List<T> class that is empty
#and has the specified initial capacity of 10. The type of
#elements in the list will be strings.
$mylist = New-Object -TypeName System.Collections.Generic.List[System.String](10);

#Create a string containing some words for us to play with.
$fox="the quick brown fox jumps over the lazy dog";

#Split the words up and place them into an array.
$words=$fox.Split(' ');

#Show the capacity of the list object.
Write-Host "mylist has capacity $($mylist.Capacity)";

#Clear the object just before we use it.

#Loop through the array and place the words into the 'List' object.
foreach ($w in $words) {

#Show how many items we have in the 'List' object.
Write-Host "mylist has $($mylist.Count) items";

#See if we can find a fox in the list.
if ($mylist.Contains($searchWord)) {
   Write-Host "We have a $($searchWord) in the list";
} else {
   Write-Host "The $($searchWord) isn't around";

#List the words as entered into the list.
Write-Host "`nUnsorted list output";
$mylist.GetEnumerator() | Foreach-Object {
    Write-Host ("Word number {0} = {1}" -f ++$num, $_);

#Produce a sorted list of words.
Write-Host "`nSorted list output";
$mylist.GetEnumerator() | Sort-Object | Foreach-Object {
    Write-Host ("Word number {0} = {1}" -f ++$num, $_);

Lines 41-46 produced a sorted output to the console. The contents of mylist are not really sorted as we used the Sort-Object cmdlet to display the contents in a sorted order. If you really want to sort the contents of your list, then Sort() method can be used. i.e.


Posted in powershell | Tagged , | Leave a comment

Scripting with Windows PowerShell

Windows PowerShell® is a task-based command-line shell and scripting language designed especially for system administration. Built on the .NET Framework, Windows PowerShell helps IT professionals and power users control and automate the administration of the Windows operating system and applications that run on Windows.

Applies To: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0

A collection of useful TechNet articles and resources can be seen here.

Posted in powershell | Tagged | Leave a comment

PowerShell enumerated types

The following code shows how to create your own enumerated types and a possible way of using the type.

$myenum = " 
   Namespace myspace 
      public enum cards 

try {
} catch {
  Add-Type -TypeDefinition $myenum -Language CSharpVersion3;

Write-Host "Assigning fred an enum value";

switch ($fred)
    ([myspace.cards]::hearts) {"Fred is now hearts"; Break}
    ([myspace.cards]::clubs) {"Fred is now clubs"; Break}
    ([myspace.cards]::diamonds) {"Fred is now diamonds"; Break}
    ([myspace.cards]::spades) {"Fred is now spades"; Break}

Write-Host "All done now!";

For the example above, the following code can be used to look at the definitions for the enumerated type.

foreach ($m in [System.Enum]::GetValues([System.Windows.Forms.MessageBoxButtons]))
{ Write-Host ([int]$m): $m }

Posted in powershell | Tagged , | Leave a comment

Parameter Attribute Declaration

The (PowerShell) Parameter attribute identifies a public property of the cmdlet class as a cmdlet parameter.

This article is a useful reference to the keywords that can be used in a Param block of a function or script.

For example:

Param (

                   HelpMessage="Enter the PDF file title",

      ) #end param


Parameter Attribute Declaration

See also


Posted in powershell | Tagged , | Leave a comment