Windows PowerShell Files
The biggest danger when you employ PowerShell to manipulate files is ‘over-think’. Just keep in mind that PowerShell opens and closes files automatically. My point is there is no need to waste time looking for non-existent file-open, or file-save commands.
PowerShell File Topics
PowerShell supports a rich selection of cmdlets to deal with every aspect of file handling.
I find that these 'item' commands are the ones that that I use to manipulate 80% of all my file operations.
As usual, note that PowerShell uses singular nouns, for example: File, Content, Item and Location. This observation about singular nouns helps when you build a cmdlet from scratch.
Out-file is an honorary member of the ‘Content’ family.
I prefer Out-File to Add-Content because it formats the data as I would like.
You can search for any group of cmdlet by employing the -Noun (or -Verb) parameter. For example: Get-Command -Noun Location.
Finding Files with Get-ChildItem
Firstly, we can find files with Get-ChildItem, incidentally gci is probably the most used alias for any PowerShell cmdlet, nevertheless I stick with fullname in my scripts. Get-ChildItem is also one of the most interesting and instructive cmdlets because of its wealth of parameters.
Let us use the classic research method of:
Get-Help Get-ChildItem -Full
What help does is give us a list of parameters such as -Recurse, -Force and also examples, which give ideas for our own projects. Both the technique of using Get-Help, and knowledge of parameters such as -Recurse or -Force will carry-over into other cmdlets.
Reading and Writing to Files
I like Out-File for saving data to disk, the main application is outputting the results of a script not to screen, but as a permanent record in a file.
Get-Process | Out-File D:\Process.txt
Result: This saves a list of running process to a file called process.txt. Observe the use of PowerShell's pipe-lining (|).
As for retrieving the information, Get-Content is excellent. What I appreciate is the way that these PowerShell cmdlets take care of the file open and file close operations without us having to add any further explicit instructions.
Result: PowerShell displays the text in the named file.
Summary: PowerShell Files
PowerShell probably has more cmdlets for files than any other object. Take the time to investigate both the file cmdlets and their numerous parameters.
On the other hand, realize that PowerShell opens and closes files automatically; thus there is no need to waste time looking for non-existent file-open, or file-save commands
If you like this page then please share it with your friends
See more Microsoft PowerShell file tutorials:
Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.