KeePass Password Manager and PowerShell

After reading an article on the SANS Cyber Defense site on the subject of accessing KeePass with PowerShell, I thought I’d have a go. I didn’t get very far but what I did do is listed below.

 

Set-location C:\family\powershell

$ff = 'C:\Program Files (x86)\KeePass Password Safe2\KeePass.exe';
[Reflection.Assembly]::LoadFile($ff)

# $CompositeKey represents a key, possibly constructed from multiple sources of data.
# The other key-related objects are added to this composite key.
$CompositeKey = New-Object -TypeName KeePassLib.Keys.CompositeKey #From KeePass.exe

# The currently logged-on Windows user account can be added to a composite key.
$KcpUserAccount = New-Object -TypeName KeePassLib.Keys.KcpUserAccount #From KeePass.exe
$ff = mypassword
$KcpPassword = New-Object -TypeName KeePassLib.Keys.KcpPassword($ff)

# Add the Windows user account key to the $CompositeKey, if necessary:
#$CompositeKey.AddUserKey( $KcpUserAccount )
$CompositeKey.AddUserKey( $KcpPassword )

$ff = 'C:\Family\Ianpass.kdbx';
$IOConnectionInfo = New-Object KeePassLib.Serialization.IOConnectionInfo
$IOConnectionInfo.Path = $ff

$StatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger

$PwDatabase = New-Object -TypeName KeePassLib.PwDatabase #From KeePass.exe
$PwDatabase.Open($IOConnectionInfo, $CompositeKey, $StatusLogger)

# $PwDatabase.RootGroup.Groups
# $PwDatabase.RootGroup.Groups | Format-Table Name,LastModificationTime,Groups -AutoSize

Write-Output 'trying to list Library';
$ff = 'Library';
$Group = $PwDatabase.RootGroup.Groups | Where-Object { $_.Name -eq $ff }
$Group.Name
$Group.Notes
$Group.GetEntriesCount($True) #Count of all entries, including in subgroups.
Write-Output 'Library done';

$tempObj = '' | Select-Object Title,UserName,Password,URL

$Group.GetEntries($True) | ForEach-Object {
  $tempObj.Title = $_.Strings.ReadSafe("Title")
  $tempObj.UserName = $_.Strings.ReadSafe("UserName")
  $tempObj.Password = $_.Strings.ReadSafe("Password")
  $tempObj.URL = $_.Strings.ReadSafe("URL")
  $tempObj
}

$PwDatabase.Close();

 

I may well return to this project, but for now, this is as far as I’ve got.

With thanks to “PowerShell for KeePass Password Manager” as SANS Cyber Defense.

 

See also

 

KeePass Password Safe

 

Keywords: powershell keepass security

 

Advertisements
Posted in powershell | Tagged | Leave a comment

Text file with line numbers

For some time now I’ve wanted to create text files with line numbers. An example of this could be:

00001 the
00002 quick
00003 brown
00004 fox
00005 jumps
00006 over
00007 the
00008 lazy
00009 dog

This can be useful if I want to use the line numbers to refer to. For example, having a text file such as this with Java or PowerShell code would enable to me to refer to various lines in the file.

When I started out trying to do this, I had PowerShell code such as:

$num = 15;
$textline = "the quick brown fox {";
$newline = [System.String]::Format("{0:D5} {1}" -f ($num, $textline));
Write-Output $newline;

 

This worked fine until I had a string with a curly brace in it. At this point I was getting the error:

 

Exception calling “Format” with “1” argument(s): “Input string was not in a correct format.”

 

I tried various ways to avoid this error. Even to trying to ‘escape’ the curly braces but to no avail. In the end, instead of formatting the string I went for the double quotes approach. This allowed me to expand my variables inside the quotes. The code was something like:

 

#
Set-Location C:\Family\powershell;
[String]$outputFile = 'ian.ian';
[UInt16]$num = 0;  # provides a line number for each line of text.
[String]$n = ''; # holds the line number with leading zeros.
[String]$t = ''; # holds the text line.

Write-Output 'Start of test';

if (Test-Path -Path $outputFile) {
    Clear-Content -Path $outputFile
}

Get-Content -Path 'gash.ps1'  |
ForEach-Object {
    $num++;
    $n = ("{0:D5}" -f ($num));
    $t = $_;
    Add-Content -Path $outputFile -Value "$n $t";
}

# Get an idea how much data is in the file.
Get-ChildItem $outputFile;

 

I can now use the above code on Java and PowerShell files. Both of which have curly braces.

 

Posted in powershell | Tagged | Leave a comment

Function template

The following code can be used as a function template. I’ve found that using  BEGIN, PROCESS and END blocks makes the function more structured and my life a lot easier.

#region ***** function Example-Function *****
Function Example-Function {
  [CmdletBinding()]
  [OutputType([System.Object[]])]
  param(
    [Parameter(Mandatory=$True,
    ValueFromPipeline=$True)]
    [string[]]$computername
  ) #end param

  BEGIN {}
  PROCESS {}
  END {}

}
#endregion ***** end of function Example-Function *****

 

Posted in powershell | Tagged | Leave a comment

Using $PSBoundParameters

$PSBoundParameters is one example of a PowerShell automatic variable. As the documentation tells us:

… variables that store state information for PowerShell. These variables are created and maintained by PowerShell.

Some basic examples of using this variable are as follows:

if ($PSBoundParameters['Verbose'])
{
    # do verbose stuff
}

or

param (
    $x
)

if ($PSBoundParameters.ContainsKey('x'))
{
    write-host 'X Bound!'
}

or

switch ($PSBoundParameters.Keys) {
    'Verbose' { do verbose stuff }
}

or

# Loop through the parameters used.
foreach ($item in $PSBoundParameters.GetEnumerator()) {
     Write-Host ("Key={0}, Value={1}" -f $item.Key, $item.Value);
}

or

if ($PSBoundParameters.ContainsKey('ElapsedTime')) {
    Write-Host "The elapsed time has been supplied";
    $t1 = [DateTime]::ParseExact($StartTime, $timeFormat, $null);
}

See also

 

About Automatic Variables

Contains a list of the automatic variables in PowerShell.

 

Posted in powershell | Tagged | Leave a comment

Files and file lengths

A hashtable can be used to help present file names and their lengths in a more meaningful manner rather than the default output from using the cmdlet Get-ChildItem.

$size = @{
    Name = 'Size'
    Expression = { '{0:#,##0.0###} Kb' -f ($_.Length / 1KB) }
  }

Get-ChildItem -File | Select-Object name, $size;

 

Sample output:

Name               Size
----               ----
gash.txt           0.0 Kb
gashinput01.txt    14.7764 Kb
gashinput02.txt    14.7764 Kb
gashOutput.txt     14.7764 Kb
ian.ian            0.0 Kb

 

Of course, if you were working with larger files, adjust the line containing Expression accordingly. i.e.

    Expression = { '{0:#,##0.0###} Gb' -f ($_.Length / 1GB) }

 

Posted in powershell | Leave a comment

Create numbered test files

I often have the need to create numbered test files such as for example:

myfile.txt.001

myfile.txt.002

:

myfile.txt.099

or whatever the maximum numbered test file is. It doesn’t have to be 99 of course. In this example, I’m going to create seven files with the name of test_file.txt.001 to test_file.txt.007.

 

The first part of the code will be to set things up.

Set-Location C:\test;
$basename = 'test_file.txt';
$newname = '';

 

By using the Set-Location cmdlet, I can set current working location to a specified location where I want to work with my files and thus avoid the need to use absolute path names. I’ll use a foreach loop to create the seven files I need.

foreach ($num in 1..7) {
    $newname = [System.String]::Format('{0}.{1}', $basename, $num.ToString('000'))
    Write-Host "Creating file $($newname)";
    New-Item -Path '.' -ItemType file -Name $newname | Out-Null;
}
Get-ChildItem -File |
Where-Object {$_.CreationTime -gt (Get-Date).AddMinutes(-5)}
Write-Host 'All done now';

 

By default, the New-Item cmdlet displays output when it’s created the file. As we’re creating multiple files, I didn’t want to see output as each individual file is created so I’ve piped the output to Out-Null. When the loop has finished, we see what files have been created in the last five minutes by the use of Get-ChildItem and Where-Object cmdlets.

 

 

Posted in powershell | Tagged | Leave a comment

Exploring Photographic EXIF data

I was doing some work recently learning how to extract Exif data from digital photographs. The requirement went away so I’m not doing any more learning on the subject for the present time.

The web site “Exploring Photographic EXIF data (using PowerShell, of course)” is an excellent place for beginners such as myself to start. It takes you into the PowerShell code used to extract Exif data. The main .NET class used is:

Bitmap Class
Namespace: System.Drawing

The Bitmap class encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attributes. A Bitmap is an object used to work with images defined by pixel data. The documentation for the class gives code examples to demonstrate how to construct a new Bitmap from a file, using the GetPixel and SetPixel methods to recolor the image. It also uses the PixelFormat, Width, and Height properties. This is a good class to use if you wish to write your own (PowerShell) code to work with Exif data.

Just in case I return to the subject, the following code is as far as I got.

 

# Property Item Descriptions
# Source: https://msdn.microsoft.com/en-us/library/ms534416.aspx
#
# https://blogs.technet.microsoft.com/jamesone/2007/07/13/exploring-photographic-exif-data-using-powershell-of-course/
#
# Reading and Writing Metadata
# Source: https://msdn.microsoft.com/en-us/library/ms533832.aspx
#
# Keywords: exif image metadata
#
$ff='C:\family\ian\DSCF0106.JPG';
$fred=New-Object -TypeName System.Drawing.Bitmap -ArgumentList $ff;

Write-Host 'Looking at some stuff';

"*" * 35;
Write-Host ('Image {0}' -f $ff);
Write-Host ('attribute flags for the pixel data of this Image: {0}' -f $fred.Flags);
$size = $fred.Size;
Write-Host ('Width {0}, Height {1}' -f $size.Width, $size.Height);
$tag = 0X5090
$propitem = $fred.GetPropertyItem($tag);
$propitem = $fred.GetPropertyItem(0x213);

# List of Property Tags for this image.
Write-Host 'Looking at idlist';
$idlist = $fred.PropertyIdList;
$idlist | ForEach-Object {“{0:X2}” -f $_}
#$idlist

$fred.Dispose();

Write-Host 'End of test';

 

See also

 

What EXIF Photo Data Is, How to Find It & How to Understand It

The article goes on to talk about The EXIF (Exchangeable Image File) Format and how it’s embedded in to digital photographs.

 

What EXIF Photo Data Is, How to Find It & How to Understand It

This article is about the Exchangeable Image File Format (EXIF) and the methods of reading EXIF Data from photographs.

 

Keywords: powershell exif image photograph

 

Posted in powershell | Leave a comment