Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through files (full path) in PowerShell

Tags:

powershell

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.

like image 409
Ethan Post Avatar asked Feb 23 '10 22:02

Ethan Post


People also ask

How do I get the full path of a file in PowerShell?

To get the full path of the file in PowerShell, use the Get-ChildItem to get files in the directory and pass the output to foreach-object to iterate over the file and get the full name of the file.

How do I read all files in a directory in PowerShell?

Like the Windows command line, Windows PowerShell can use the dir command to list files in the current directory. PowerShell can also use the ls and gci commands to list files in a different format.

How do I run a path in PowerShell?

You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).


2 Answers

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" }
like image 145
JaredPar Avatar answered Sep 28 '22 02:09

JaredPar


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 }
   }
like image 36
Ethan Post Avatar answered Sep 28 '22 00:09

Ethan Post