PowerShell query: how to process a file -


I often want to process a file, which in turn leads to a modified output file. To do this, I can not find the method of PowerShell - it is always an example of a liner, like code in IWSWIM, this is an example.

I have an LMHOSTS file. Do not ask why! I want to get a new LMHOSTS file which contains only ping-paging servers

Comment rows begin with #.

Data lines are something like this (different from space):

  10.123.177.1 SVRDS1 #PRE #DOM: DOM1  

Or this:

  10.241.177.30 SVRDS30 #PRE  

I have it (thanks for the help with ping-host):

  gc 'c: \ work \ lmhosts.txt' | % {If ($ _-like '# *') {$ _ | Out-file 'C: \ work \ lmhosts2.txt' -append} and {if ($ (ping-host $ _ substrings (0, $ _ index ('')) -cute 1-time 10). 1) {$ _ | Out-File 'C: \ Work \ lmhosts2.txt' -append}}}  

This works but it is not good. I have taken the view of a programmer but have done it as a one-liner. Is there a better way to do this, is it a more 'open' and 'less' code?

In this special example, you are filtering the contents of 1 file and output it to another are doing. Usually this is a good option for you then you can simplify the one-liner a bit:

  gc 'C: \ work \ lmhosts.txt' | ? {($ _-Like '# *') -or ($ (ping-host $ _. Split ('') [0]) -based 1 -support 10) .received -q 1)} & gt; 'C: \ work \ lmhosts2.txt'  

Some notes:

  • "?" Where there is an alias for the object
  • - Or the operator will be a short circuit, i.e., if the result of the first transaction is in True, then the second execution will not be disturbed.
  • You can use
  • I changed the substrings with split, it looked a bit, is not sure that it works normally with your input.

Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -