Create a list of FileInfo in PowerShell script for testing

191 Views Asked by At

I have a PowerShell script that I want to test using Pester. For that I want to mock the Get-ChildItem like that

$expected = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
$expected.Add([System.IO.FileInfo]::new('SmokeTest.txt'))

Now, I want to try a filter based on the CreationTime. I tried to create a file like that

$expected.Add([System.IO.FileInfo]::new({ 
    Name = 'Smoke Test.txt'
    CreationTime = [DateTime]::ParseExact('2023-01-01 22:00', 
        "yyyy-MM-dd HH:mm", $null) 
}))

but I get an error

Validate files to delete.validate files with date.should return a list of expected files (mock) 8ms (8ms|1ms) ArgumentException: Illegal characters in path. MethodInvocationException: Exception calling ".ctor" with "1" argument(s): "Illegal characters in path."

I googled but I can't find how to create a System.IO.FileInfo with the CreationTime.

2

There are 2 best solutions below

0
jdweng On

I usually write code in Visual Studio in c# and then convert. The issue with you code is FileInfo new only has one constructor with the filename.

            List<FileInfo> expected = new List<FileInfo>();
            FileInfo smokeTest = new FileInfo("Smoketest.txt");
            expected.Add(smokeTest);
            smokeTest.CreationTime = DateTime.ParseExact("2023-01-01 22:00", "yyyy-MM-dd HH:mm", null);
0
Frode F. On

The error is thrown because the constructor only supports specifying filename as @iRon and @jdweng explained. Also, attempting to modify CreationTime after creating the object would fail while trying to write it to the non-existing file.

There's two ways I'd approach this:

  1. Create real files in ex TestDrive: and modify CreationTime.
  2. Mock using: New-MockObject -Type 'System.IO.FileInfo' -Properties @{ Name = '1_TMP.txt'; CreationTime = [datetime]'2020-01-01 21:00:00' }

Originally answered on GitHub: https://github.com/pester/Pester/discussions/2344#discussioncomment-5818176