简体   繁体   中英

Powershell and some simple string manipulation

need some help with building a powershell script to help with some basic string manipulation. I know just enough powershell to get in trouble, but can't figure out the syntax or coding to make this work.

I have a text file that looks like this -

Here is your list of servers:
server1
server2.domain.local
server3
Total number of servers: 3

I need to take that text file and drop the first and last lines (Always first and last.) Then I need to take every other line and basically turn it into a CSV file.

The final output should be a text file that looks like this -

server1,server2.domain.local,server3

Any suggestions on where to start? Thanks!

You can try :

$a = Get-Content C:\temp\M.TXT # Where M.TXT is your original file
$a[1..($a.count-2)] | % {$s=""} {$s+=$_+","}{$s.trim(",") | Out-File m.csv} # M.CSV is the result file

Here's a couple of other ways.

(Get-Content foo.txt | Where {$_ -notmatch '^\s*$'} | Select -Skip 1 | 
     Select -Skip 1 -Last 2E9) -join ',' > foo.csv

And if you happen to have the PowerShell Community Extensions (for Skip-Object):

(Get-Content foo.txt | Where {$_ -notmatch '^\s*$'} | 
     Skip-Object -First 1 -Last 1) -join ',' > foo.csv

Note that the Where {$_ -notmatch '^\\s*$'} eliminates any blank lines.

You can use the range operator:

$content = Get-Content D:\Scripts\Temp\test1.txt
$content[1..($content.count-2)] -join ',' | Out-File servers.txt

It would be better to export to a csv file so you can import it back and operate on the server names:

$content = Get-Content D:\Scripts\Temp\test1.txt
$content[1..($content.count-2)] | Select-Object @{Name='ComputerName';e={$_}} | Export-Csv servers.csv -NoTypeInformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM