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 
      { 
         hearts,
         clubs,
         diamonds,
         spades
      } 
   }
";

try {
  [myspace.cards]
} catch {
  Add-Type -TypeDefinition $myenum -Language CSharpVersion3;
}

Write-Host "Assigning fred an enum value";
$fred=[myspace.cards]::hearts;

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:

[cmdletbinding()]
Param (

        [parameter(Mandatory=$true,
                   HelpMessage="Enter the PDF file title",
                   ParameterSetName="pp1",
                   Position=1)]
        [ValidateNotNullOrEmpty()]
        [String]
        $PdfTitle

      ) #end param

Reference

Parameter Attribute Declaration

See also

about_Functions_Advanced

Posted in powershell | Tagged , | Leave a comment

Reading/writing files

Overview

I can’t remember why now, but recently I had reason to do some file input/output using PowerShell. I guess there are different ways of achieving this, but chose to practice using .NET from PowerShell. 

The following code simply reads an input file and writes the data out to an output file. No other processing is involved.

I started off with four variables.

  • $inrec – a string variable used to receive data from the input file and write to the output file.
  • $counter – an integer to count the lines processed.
  • $infile – a string variable representing the absolute path of the input file.
  • $outfile – a string variable representing the absolute path of the output file.

Input

From this, I created my input file object.

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

The StreamReader Class constructor is overridden 11 times but the version I used was simply:

public StreamReader(string path)

which initializes a new instance of the StreamReader class for the specified file name supplied, i.e., variable $infile.

Output

The other side of the coin is the StreamWriter Class. Because I chose to use the constructor:

public StreamWriter(Stream, Encoding)

I had to create a stream object for the first parameter. This was done via:

public FileStream(path, FileMode, FileAccess)

The documentation for Constructor (String, FileMode, FileAccess), tells us these parameters are:

  1. path – A relative or absolute path for the file. In our example, variable $outfile.
  2. FileMode – How to open the file. It could be that you want to append to an existing file or create a new one. With the code I’ve used, I’m creating a new file each time round, thus overwriting the file if it exists.
  3. FileAccess – How we’re going to access the file, i.e., read, write or read and write to the file. I’ve chosen to just write to the file.

This was achieved with the code:

$outStream = New-Object -TypeName System.IO.FileStream(
 $outfile,
 [System.IO.FileMode]::Create,
 [System.IO.FileAccess]::Write);

Types System.IO.FileMode and System.IO.FileAccess are enumerated objects in which the documentation will tell you the members of these objects. Another way of finding out the members is to run the following statements at the PowerShell prompt:

PS> [Enum]::GetNames( [System.IO.FileMode] )
PS> [Enum]::GetNames( [System.IO.FileAccess] )

Now we’ve created the output stream, we can create the StreamWriter object with:

$output = New-Object -TypeName System.IO.StreamWriter(
 $outStream,
 [System.Text.Encoding]::ASCII);

In other words we’ve created a FileStream object in order to create a StreamWriterobject.

I’ve used a WHILE loop to read from the input file.

$inrec = $input.ReadLine();
while ($inrec -ne $null) {
$output.WriteLine($inrec);
$counter++;

$inrec = $input.ReadLine();
}

The StreamReader.ReadLine Method $input.ReadLine() reads the next line from the input stream, or null if the end of the input stream is reached.

To tidy up at the end of the file, I’ve done:


$input.Close();
$input.Dispose();
$output.Flush();
$output.Close();
$output.Dispose();

For good measure, I’ve used the System.IO.FileInfo object to see what the length of the output file is in bytes.

$filelen = New-Object -TypeName System.IO.FileInfo($outfile);
Write-Host "File $($outfile.ToString()) has length $($filelen.length) bytes";

I always forget where I’ve my files are, so I use the following to remind me:

Write-Host "Lines written: $counter";
Write-Host "Files used:";
Write-Host ("Input file: {0}`nOutput file: {1}" -f $infile, $outfile);
cat $outfile | Measure-Object -Line;
Write-Host "All done now";

Summary

Putting all this together gives us:


$inrec="";
$counter=0;
$infile="C:\junk\gashinputfile.txt";
$outfile="C:\junk\gashoutputfile.txt";

$input = New-Object -TypeName System.IO.StreamReader($infile);
$outStream = New-Object -TypeName System.IO.FileStream(
 $outfile,
 [System.IO.FileMode]::Create,
 [System.IO.FileAccess]::Write);
$output = New-Object -TypeName System.IO.StreamWriter(
 $outStream,
 [System.Text.Encoding]::ASCII);

$inrec = $input.ReadLine();
while ($inrec -ne $null) {
 $output.WriteLine($inrec);
 $counter++;

$inrec = $input.ReadLine();
}

$input.Close();
$input.Dispose();
$output.Flush();
$output.Close();
$output.Dispose();

$filelen = New-Object -TypeName System.IO.FileInfo($outfile);
Write-Host "File $($outfile.ToString()) has length $($filelen.length) bytes";

Write-Host "Lines written: $counter";
Write-Host "Files used:";
Write-Host ("Input file: {0}`nOutput file: {1}" -f $infile, $outfile);
cat $outfile | Measure-Object -Line;
Write-Host "All done now";

What you won’t see in this program is any error handling. As this was a learning exercise, I can come back to this subject at a later date.

See also

StreamReader Class

FileStream Class

StreamWriter Class

Posted in powershell | Tagged , | 1 Comment

Grep in PowerShell

I did some Oracle work recently which meant running some scripts on a test database, spooling the output to a log file in a local directory. Afterwards I realised it would be helpful if I could check all of the log files for any error messages.

Oracle error messages come in the form of, for example:

ORA-21300: objects option not installed

Using the PowerShell Select-String Cmdlet would allow me to emulate the Unix grep command and do a search through my log files for a search pattern of “ORA-“.

Code 1

The first variant of code used, gives a listing of the files found that contain the search pattern and a count of how many times it appears in each file.

Using the code:

$startDir="C:\test_a";

Get-ChildItem –Path $startDir -Include *.tmp -Recurse |
    Select-String –Pattern "ORA-" -CaseSensitive |
    Group-Object path | Select-Object name, count |
    Format-Table -AutoSize;

gives an output something like:


Name                          Count
----                          -----
C:\test_a\test_d\test_d01.tmp     1
C:\test_a\test_h\ian2.tmp         3
C:\test_a\test_k\ian.tmp          1

File ian2.tmp for example, contains the search pattern three times.

Code 2

The next piece of code used, will give an output of:

  • Path and filename
  • Line number at which the search pattern was found.
  • The text of the line found.
$startDir="C:\test_a";

Get-ChildItem -Path $startDir -Include *.tmp -Recurse |
    Select-String -Pattern "ORA-" -CaseSensitive

Sample output


C:\test_a\test_d\test_d01.tmp:2:ORA-21300: objects option not installed
C:\test_a\test_h\ian2.tmp:4:ORA-hello world ora
C:\test_a\test_h\ian2.tmp:6:ORA-helen message
C:\test_a\test_h\ian2.tmp:8:ORA-another ora message
C:\test_a\test_k\ian.tmp:2:ORA-32803: value for string cannot be altered

The class Microsoft.PowerShell.Commands.MatchInfo is returned by the Select-String cmdlet and provides information about the results of a match.

Keywords: powershell grep search string

Posted in powershell | Tagged , | Leave a comment

Purging files

Overview

The following chunk of code shows how to identify files over X days old using Java. With this, we can do things such as delete them if they’re over 30 days old for example.

Code

// With this variable we can identify files over X days.
// In this example, anything over 30 days.
int daysBack = 30;

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, daysBack * -1);
long purgeTime = cal.getTimeInMillis();
System.out.format("purgeTime is now %d%n", purgeTime);

if (myfile.lastModified() < purgeTime) {
     // do something, maybe delete file?
}

Posted in java | Tagged , | Leave a comment

Walking through a file tree

I’ve recently been looking at classes in the java.nio.file package. In particular I’ve been learning how to use Class SimpleFileVisitor in order to visit each file in a file tree. This provides a way of walking through a file tree enabling one to look at files and directories, carrying out whatever actions are required depending upons ones needs.

One interesting caveat is that the method ‘postVisitDirectory’ is:

Invoked for a directory after entries in the directory, and all of their descendants, have been visited.

So if you have lots of subdirectories under a particular directory, this method isn’t executed until you reach the bottom of that part of the branch and then start to come up again.

To test this out, in the preVisitDirectory and postVisitDirectory methods, I placed print statements to give me an idea of what was going on.

preVisitDirectory
msg = String.format("in --> We're just about to look in directory %s%n",
dir.toAbsolutePath().toString());

i.e. "in --> We're just about to look in directory C:\test_a\test_e"

and

postVisitDirectory
msg = String.format("out ++> %s done%n", dir.toAbsolutePath().toString());

i.e. "out ++> C:\test_a\test_e done"

This way I could see where when I went into a directory and when I left it again.

If we have a directory tree such as:


C:\TEST_A
+---test_b
¦   +---test_c
¦       +---test_d
+---test_e

the outcome of my program will be:

in --> We're just about to look in directory C:\test_a

Looked at file: temp_files.ps1

in --> We're just about to look in directory C:\test_a\test_b

Looked at file: test_b01.tmp

Looked at file: test_b02.tmp

in --> We're just about to look in directory C:\test_a\test_b\test_c

Looked at file: test_c01.tmp

Looked at file: test_c02.tmp

in --> We're just about to look in directory C:\test_a\test_b\test_c\test_d

Looked at file: test_d01.tmp

Looked at file: test_d02.tmp

out ++> C:\test_a\test_b\test_c\test_d done

out ++> C:\test_a\test_b\test_c done

out ++> C:\test_a\test_b done

in --> We're just about to look in directory C:\test_a\test_e

Looked at file: test_e01.tmp

Looked at file: test_e02.tmp

out ++> C:\test_a\test_e done

out ++> C:\test_a done

The postVisitDirectory for C:\test_a\test_b\test_c for example, is not mentioned until we leave C:\test_a\test_b\test_c\test_d and start on our way back up.

Directory C:\test_a is the first and last to be visited.
 

The program that I came up with is shown below.


// Copyright (c) 2002 MyHouse
//package ian;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import static java.nio.file.FileVisitResult.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
/**
 * @author Ian Molloy March 2013
 * @version (#)coreJava.java        1.05 2013-02-27
 */
public class coreJava {
private byte dummy;
private List<String> pathTaken;
private String msg;
private int fileCount;
private int dirCount;
  /**
   * Constructor
   */
  public coreJava() {
    this.dummy = 99;
    this.fileCount = 0;
    this.dirCount = 0;
    this.pathTaken = new ArrayList<String>(100);
    this.msg = "";
System.out.println("blob constructor for coreJava complete");
    launchFrame();
  }

  /**
   * Adds an item to variable pathTaken.
   */
  private void append2Pathtaken(String item) {
     this.pathTaken.add(item);
  }

  /**
   * Working test method.
   * Floating point formatting to decimal places: %.2f
   * A format of %03d will pad, for example, a 5 to 005.
   * topLevel.setLocationRelativeTo(null);
   */
  public void launchFrame() {
    System.out.printf("Start of test on %tc%n", new java.util.Date());
    // ---------------------------------------------------------------

    Path startDir = Paths.get("C:\\test_a");
    PrintFiles pfiles = new PrintFiles();

    try {
      Files.walkFileTree(startDir, pfiles);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      System.out.println("Should be all done now");
    }

/**
    if (pathTaken.size() > 0) {
       System.out.println("\nListing the contents of variable pathTaken");
       for (Iterator<String> iter = pathTaken.iterator(); iter.hasNext(); ) {
          System.out.println(iter.next());
       }
    }
*/

    System.out.printf("%nvariable dummy is now %d%n", dummy);

    // ---------------------------------------------------------------
    System.out.printf("End of test on %tc%n", new java.util.Date());
  }//end of launchFrame

  /**
   * main
   * @param args
   */
  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        new coreJava();
      }
    });
  }//end of main

// ==============================================
// Start of inner class
// ==============================================

public class PrintFiles extends SimpleFileVisitor<Path> {
private int dirCount;
private boolean printFilecount;
private String msg;
  /**
   * Constructor
   */
  public PrintFiles() {
    super();
    this.msg = "";
    this.printFilecount = true;
  }//end of constructor

  private void printBklanklines(int blanks) {

     for (int m = 0; m < blanks; m++) {
         System.out.println("");
     }
  }

  /**
   * Invoked for a directory before entries in the
   * directory are visited.
   */
  @Override
  public FileVisitResult preVisitDirectory(
           Path dir,
           BasicFileAttributes attrs) throws IOException
  {
      //printBklanklines(1);
//      msg = String.format("in --> We're just about to look in directory %s%n",
//                 dir.getFileName().toString());
      msg = String.format("in --> We're just about to look in directory %s%n",
                 dir.toAbsolutePath().toString());
      System.out.println(msg);
      append2Pathtaken(msg);
      //append2Pathtaken(msg);

      //resetFileCount();
      return CONTINUE;
  }// end of preVisitDirectory

  /**
   * Invoked for a file in a directory.
   */
  @Override
  public FileVisitResult visitFile(
           Path file,
           BasicFileAttributes attrs) throws IOException
  {

      msg = String.format("Looked at file: %s%n", file.getFileName().toString());
      System.out.println(msg);
//      append2Pathtaken(msg);
      //incrementFileCount();

      return CONTINUE;
  }// end of visitFile

  /**
   * Invoked for a directory after entries in the directory,
   * and ALL OF THEIR DESCENDANTS, have been visited.
   */
  @Override
  public FileVisitResult postVisitDirectory(
           Path dir,
           IOException exc) throws IOException
  {

      msg = String.format("out ++> %s done%n", dir.toAbsolutePath().toString());
      System.out.println(msg);
      append2Pathtaken(msg);

      return CONTINUE;
  }// end of postVisitDirectory

  /**
   * Invoked for a file that could not be visited.
   */
  @Override
  public FileVisitResult visitFileFailed(
           Path file,
           IOException exc)
  {
      msg = String.format("Snags with file %s%n", file.getFileName().toString());
      //append2Pathtaken(msg);

      System.err.println(exc);

      return CONTINUE;
  }// end of visitFileFailed

}

// ==============================================
// End of inner class
// ==============================================

}//end of class

I’ve used an inner class for all of the FileVisitor work.

 

See also

Interface java.nio.file.FileVisitor

java.nio.file.SimpleFileVisitor

Posted in java | Tagged , | Leave a comment

User (password) dialog boxes

Overview

This article shows how to create a custom dialog using JComponent and JOptionPane. In this example, we’re creating a password dialog box in which we can enter a username, password and server name.

Code

This is the code used to achieve this.

final JTextField username = new JTextField();
final JPasswordField password = new JPasswordField();
final JTextField server = new JTextField();
final JComponent[] logins = new JComponent[] {
        new JLabel("Username"),
        username,
        new JLabel("Password"),
        password,
        new JLabel("Server"),
        server
};

JOptionPane.showMessageDialog(null, logins, "My custom login", JOptionPane.PLAIN_MESSAGE);
System.out.printf("You could log on to server %s as user %s with password %s%n",
                  server.getText(),
                  username.getText(),
                  String.valueOf(password.getPassword()));

See also

The Java Tutorial How to Make Dialogs.

Posted in java | Tagged , , | Leave a comment