Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate over files with powershell?

Tags:

powershell

I want to iterate over files in a folder using powershell script;

like image 906
pinei Avatar asked Aug 31 '10 01:08

pinei


People also ask

How do I iterate through a file in PowerShell?

If you have a text file with data you wish to use, you can use PowerShell Get-Content to list the contents of the file. Then use the PowerShell ForEach loop to iterate through the file line by line.

How do I enumerate a file in PowerShell?

List the files in a Windows PowerShell directory. 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 get a list of files in a directory and subfolders using PowerShell?

PowerShell utilizes the “Get-ChildItem” command for listing files of a directory. The “dir” in the Windows command prompt and “Get-ChildItem” in PowerShell perform the same function.

How do I search for a file in PowerShell?

Get-ChildItem cmdlet in PowerShell is used to get items in one or more specified locations. Using Get-ChildItem, you can find files. You can easily find files by name, and location, search file for string, or find file locations using a match pattern.


1 Answers

Get-ChildItem | ForEach-Object { <# do what you need to do #> }

or shorter:

gci | % { <# ... #> }

or if you want an explicit looping construct:

foreach ($file in Get-ChildItem) {
    # ...
}

Note however, that foreach will only run once all output from Get-ChildItem is collected. In my opinion most Powershell code should use the pipeline as much as possible.

like image 179
Joey Avatar answered Oct 14 '22 07:10

Joey