Using Appropriate DataTypes (Part 1)

by Feb 28, 2023

Windows is an API-driven operating system, and PowerShell is, too. Compared to other shells that use plain text as a common denominator and leave it to the user to give structure to the data via grep and regular expressions, PowerShell (and the underlying .NET framework) provides a rich set of data types that you can choose from to store data in a perfect way.

By default, PowerShell uses only basic data types such as [string] (text), [int] (numbers), [double] (floating point numbers), [datetime] (date and time) and [bool] (true and false).

You however can pick any other data type that you find more suitable:

 
PS> [System.IO.FileInfo]'c:\test\somefile.txt'

Mode                 LastWriteTime         Length Name 
----                 -------------         ------ ----
darhsl        01.01.1601     01:00             () somefile.txt



PS> [System.IO.FileInfo]'c:\test\somefile.txt' | Select-Object -Property *


Mode              : darhsl
VersionInfo       : 
BaseName          : somefile
Target            : 
LinkType          : 
Name              : somefile.txt
Length            : 
DirectoryName     : c:\test
Directory         : c:\test
IsReadOnly        : True
Exists            : False
FullName          : c:\test\somefile.txt
Extension         : .txt
CreationTime      : 01.01.1601 01:00:00
CreationTimeUtc   : 01.01.1601 00:00:00
LastAccessTime    : 01.01.1601 01:00:00
LastAccessTimeUtc : 01.01.1601 00:00:00
LastWriteTime     : 01.01.1601 01:00:00
LastWriteTimeUtc  : 01.01.1601 00:00:00
Attributes        : -1 

By converting generic data types such as string to a more appropriate data type, it becomes much easier to access individual pieces of information. For example, if you’d like to parse a file path, by converting the string to [System.Io.FileInfo], you can easily split a path and extract drive, parent folder, file name, file name without extension, or the extension:

 
PS> $path = [System.IO.FileInfo]'c:\test\somefile.txt'

PS> $path.DirectoryName
c:\test

PS> $path.FullName
c:\test\somefile.txt

PS> $path.Name 
somefile.txt

PS> $path.BaseName
somefile

PS> $path.Extension
.txt

PS> $path.Directory.Parent

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d--hs-        15.02.2023     17:33                c:\ 



PS> $path.Directory.Parent.Name
c:\ 
 


Tweet this Tip! Tweet this Tip!