Question:
I’ve written a script that will be used for archiving log files from a server. I’m in pretty good shape with everything but the recursiveness or not of Get-ChildItem…
The issue I seem to be having is that when Get-ChildItem is not recursive and -Include
is present with only one filter, it is ignored! Or, I’m doing something wrong (likely).
I’ve cleaned up the output a little…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
PS C:\foo> Get-childitem -path "c:\foo" Name ---- bar1.doc bar2.doc bar3.doc foo1.txt foo2.txt foo3.txt PS C:\foo> Get-childitem -path "c:\foo" -Include *.txt PS C:\foo> Get-childitem -path "c:\foo" -Include *.txt -recurse Name ---- foo1.txt foo2.txt foo3.txt |
Sooo??? I had a fantasy where all I had to do was branch to a path of the script that did not have the recurse switch. (By the way, is it possible to variably apply parameters so as to avoid duplicated code paths where the only variability is the parameters to a cmdlet?)
Anyway, here is my script for completeness, in addition to my issue with Get-ChildItem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function MoveFiles() { Get-ChildItem -Path $source -Recurse -Include $ext | where { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } | foreach { $SourceDirectory = $_.DirectoryName; $SourceFile = $_.FullName; $DestinationDirectory = $SourceDirectory -replace [regex]::Escape($source), $dest; $DestionationFile = $SourceFile -replace [regex]::Escape($source), $dest; if ($WhatIf){ #Write-Host $SourceDirectory; #Write-Host $DestinationDirectory; Write-Host $SourceFile -NoNewline Write-Host " moved to " -NoNewline Write-Host $DestionationFile; } else{ if ($DestinationDirectory) { if ( -not [System.IO.Directory]::Exists($DestinationDirectory)) { [void](New-Item $DestinationDirectory -ItemType directory -Force); } Move-Item -Path $SourceFile -Destination $DestionationFile -Force; } } } } |
Answer:
The answer is in the full description of the command (get-help get-childitem -full):
The Include parameter is effective
only when the command includes the
Recurse parameter or the path leads to
the contents of a directory, such as
C:\Windows\*, where the wildcard
character specifies the contents of
the C:\Windows directory.
So the following would work without recurse.
1 2 |
PS C:\foo> Get-childitem -path "c:\foo\*" -Include *.txt |