powershell - Please explain, function to add string to first line of a file -
would explain happing in powershell code @ bottom of post?
i got first, lets "hello world" in powershell, , needed these lines of code. works charm, not sure does, exactly.
the questions starts at
$( ,$_; get-content $path -ea silentlycontinue) | out-file $path
so understand far.
we create function called insert-content
. params (input interpeted string , added $path
).
function insert-content { param ( [string]$path )
this function does/processes:
process { $( ,$_;
i not sure does, guess gets "the input" (the "hello world" before |
in "hello world" | insert-content test.txt
).
and got -ea silentylycontinue
, do?
process { $( ,$_; get-content $path -ea silentlycontinue) | out-file $path
it appreciated if explain these 2 parts
$( ,$_;
-ea silentylycontinue
code needed/used: add string first line of doc.
function insert-content { param ( [string]$path ) process { $( ,$_;get-content $path -ea silentlycontinue) | out-file $path } } "hello world" | insert-content test.txt
process {...}
used applying code inside scriptblock (the {...}
) each parameter argument function reads pipeline.
$_
automatic variable containing current object. comma operator ,
preceding $_
converts string value string array single element. it's not required, though. code work $_
instead of ,$_
.
get-content $path
reads content of file $path
, echoes success output stream array of strings (each line separate string).
the ;
separates 2 statements ,$_
, get-content $path
each other.
| out-file $path
writes output file $path
.
the subexpression operator $()
required decouple reading file writing it. can't write file when process reading it, subexpression ensures reading completed before writing starts.
basically whole construct
$( ,$_;get-content $path -ea silentlycontinue) | out-file $path
echoes input pipeline (i.e. "hello world"
) followed current content of file $path
(effectively prepending input string file content) , writes file.
the -ea silentlycontinue
(or -erroraction silentlycontinue
) suppresses error thrown when $path
doesn't exist.
Comments
Post a Comment