5

How do I do the equivalent in PowerShell? Note that I require the full path to each file.

# ksh
for f in $(find /app/foo -type f -name "*.txt" -mtime +7); do
   mv ${f} ${f}.old
done

I played around with Get-ChildItem for a bit and I am sure the answer is there someplace.

Ethan Post
  • 3,020
  • 3
  • 27
  • 27

2 Answers2

6

I'm not sure what mtime does here is the code to do everything else

gci -re -in *.txt "some\path\to\search" | 
  ?{ -not $_.PSIsContainer } |
  %{ mv $_.FullName "$($_.FullName).old" }
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • mtime - File data was last modified n*24 hours ago. – Ethan Post Feb 23 '10 at 22:56
  • 1
    `?{ $_.LastWriteTime -le (Get-Date).AddDays(-8) }` – ephemient Feb 23 '10 at 23:03
  • No sure how to format a comment here so I can't paste the code and output. But I get the error "Move-Item : Cannot bind argument to parameter 'Path' because it is null." when I try the original answer. I am using PowerShell 1, perhaps that is an issue? – Ethan Post Feb 23 '10 at 23:05
  • @Ethan, sorry I missed a pipeline operator when I formatted my code, please try again – JaredPar Feb 23 '10 at 23:16
  • 1
    You don't need to explicitly give `$_.FullName` as the first argument to `Move-Item`, though. It can figure it out from `$_` as well. – Joey Feb 24 '10 at 03:11
  • 3
    You can optimize this even further since Move-Item -destination parameter takes input by pipeline you can do this: ` ... | Move-Item -Dest {$_.FullName + '.old'}`. – Keith Hill Feb 24 '10 at 16:29
2

This seems to get me close to what I need. I was able to combine some of the information from Jared's answer with this question to figure it out.

foreach($f in $(gci -re -in hoot.txt "C:\temp")) {
   mv $f.FullName "$($f.FullName).old"
}

In the interest of sharing the wealth here is my function to simulate *nix find.

function unix-find (
   $path,
   $name="*.*",
   $mtime=0) 
   {
   gci -recurse -include "$name" "$path" | 
      where-object { -not $_.PSIsContainer -and ($_.LastWriteTime -le (Get-Date).AddDays(-$mtime)) } |
      foreach { $_.FullName }
   }
Community
  • 1
  • 1
Ethan Post
  • 3,020
  • 3
  • 27
  • 27