Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .Synopsis
- Given a file, return a subset of that file.
- .Description
- Restriction is by line number. At least 2 arguments are required:
- - the file name, including path, and
- - the last line to be returned. So if the file contains 1000 lines, and the second
- argument is 500 (and there is no 3rd argument), then lines 1-500 will be returned
- If the argument count is 3, then for simplicity, this last argument is taken to be
- the FIRST line to include. The example below shows how this plays.
- Generate a test file for the examples below thus:
- 1..1000 > d:\scratch\1000_line_file.txt
- .Example
- This will return lines 1-500 from the original
- "d:\scratch\1000_line_file.txt" | Reduce-File 500
- .Example
- This will return lines 3-500 from the original
- "d:\scratch\1000_line_file.txt" | Reduce-File 500 3
- .Example
- This will return lines 3-1000 from the original, because 1000 is the maximum: no exception is thrown:
- "d:\scratch\1000_line_file.txt" | Reduce-File 1500 3
- .Example
- This will write the output to a further file. Note that it is not possible in this function to write back to the same file - a separate function should manage that.
- "d:\scratch\1000_line_file.txt" | Reduce-File 1500 3 | Out-File .\x.txt
- #>
- function Reduce-File
- {
- Param
- (
- [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
- [string]
- $FileNameWithPath,
- [Parameter(Mandatory=$true, Position=1)]
- [int]
- $LastLineNumberToInclude,
- [Parameter(Mandatory=$false, Position=2)]
- [int]
- $FirstLineNumberToInclude
- )
- Process {
- $lines = get-content $FileNameWithPath
- if ($LastLineNumberToInclude -gt $lines.Count) {
- $LastLineNumberToInclude = $lines.Count
- }
- $restrictedFile = $lines |
- select -First $LastLineNumberToInclude |
- select -Last $($LastLineNumberToInclude - ($FirstLineNumberToInclude - 1))
- $restrictedFile
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement