I want to create a PowerShell script that can delete a bunch of file in a given paths following a particular match (in the following example all the files that contain TMP). This is the function:
function CheckFilesToDelete([string[]]$fList) {
[System.Collections.Generic.List[System.IO.DirectoryInfo]]$fileList
foreach($folderName in $fList)
{
$path = "$folderName"
($list = @(Get-ChildItem "$path" -File -Recurse |
Where-Object { $_.Name -match '.*TMP.*' })) > null
if($list.Count -gt 0) { $fileList.AddRange($list) }
}
return $fileList
}
Now, I want to create the test for this function. I mock the Get-ChildItem so I can verify what files the function has to return. I like to have all the details of the files (such as name, creation date and so on)
Describe "Validate files to delete" {
Context "validate files" {
It "should return a list of expected files" {
[string[]]$folderList = "Tests"
$tmpPath = Join-Path $path $_
[System.Collections.Generic.List[System.IO.DirectoryInfo]]
$expected = @('1_TMP.txt','2_TMP.txt')
Mock Get-ChildItem {
[PSCustomObject]@{ Name = '1_TMP.txt' },
[PSCustomObject]@{ Name = 'SmokeTest.txt' },
[PSCustomObject]@{ Name = '2_TMP.txt' },
[PSCustomObject]@{ Name = 'qq02000.doc' }
}
$list = CheckFilesToDelete -EnvPath $path
-fList $folderList -ErrorAction Stop
}
}
}
The problems I'm facing are:
- how can I display the
$listto check the list of files - how to compare
$listwith$expected
You can display
$listby setting a breakpoint and debugging it, or addingWrite-Host $listin the test temporaryYou can compare using the assertion below which matches count and filenames. Sort first to avoid order-issues:
$expected.Name | Sort-Object | Should -Be ($list.Name | Sort-Object)Tip: For a simple filename-filter I'd recommend using
$list = @(Get-ChildItem -Path "$path" -File -Recurse -Filter '*TMP*'). It will process the filter in the filesystem-provider which is a lot faster than returning every file and filter in PowerShell likeWhere-ObjectandGet-ChildItem -Include '*TMP*'would.Example:
Originally answered here: https://github.com/pester/Pester/discussions/2344#discussioncomment-5783009