I can only say that using PowerShell to read a text file is simply too simple a matter.
Get-content, gets the contents of the item at the specified location.
Syntax: get-content [-path] < file path >
[-path] is caused by square brackets, indicating that it can be written, or not written; The default is the file path after writing, the name of which is the file path behind.
Run this command directly, PowerShell will output the contents of the file to the console, if you want to see the contents of the file, then do so perfect!
But sometimes, you want to play a bit of a difficult operation-you want to open the file to change the contents of the inside, then you can use the pipe to send it out, or directly assign it to a variable. Examples are as follows:
Copy Code code as follows:
$file = get-content "D:\1.txt"
Get-content "D:\1.txt" | %{write-host $_. Replace ("Day", "Sun")} #这样就可以实现把d: \1.txt content, output, and the "Day" word, replaced by the sun.
Getting the first n rows of the file is also an interesting thing. It can be done with a PowerShell. Examples are as follows:
Copy Code code as follows:
Get-content D:\1.txt-totalcount 100 | Set-content Top100.txt
Description: Here the Set-content Top100.txt is to put the result of a previous statement, write a new file--top100.txt
If at this time you want to get the 100th line of the file, would you think of doing a very complex loop? If so, that means you have a good programming literacy. But PowerShell told you not to be so troublesome. Examples are as follows:
Copy Code code as follows:
(get-content D:\1.txt-TotalCount 100) [-1]
Description: What! What did you see?! If you simply look () [-1], is that not like an array? -1 represents the last array element, which means the last line of the first 100 lines, is that the 100th line?!
Finally, the command returns an array of objects that can be traversed using foreach-object (the alias is%). Very convenient, before you should have seen the example of the "sun"!