Powershell ,Read from a txt file and Format Data(

2020-07-18 03:13发布

问题:

I am really very new to powershell. I want to use powershell to read a txt file and change it to another format.

  1. Read from a txt file.
  2. Format Data( remove lines, remove blank spaces in between)
  3. Count of records ( "T 000000002" 9 chars)

and then write the output to a new file.

I just started powershell two days ago so I don't know how to do this yet.

回答1:

  1. Reading from a file:

    Get-Content file.txt
    
  2. Not quite sure what you want here. Get-Content returns an array of strings. You can then manipulate what you get and pass it on. The most helpful cmdlets here are probably Where-Object (for filtering) and ForEach-Object (for manipulating).

    For example, to remove all blank lines you can do

    Get-Content file.txt | Where-Object { $_ -ne '' } > file2.txt
    

    This can be shortened to

    Get-Content file.txt | Where-Object { $_ } > file2.txt
    

    since an empty string in a boolean context evaluates to false.

    Or to remove spaces in every line:

    Get-Content file.txt | ForEach-Object-Object { $_ -replace ' ' } > file2.txt
    
  3. Again, not quite sure what you're after here. Possible things I could think of from your overly elaborate description are something along the lines of

    $_.Substring(2).Length
    

    or

    $_ -match '(\d+)' | Out-Null
    $Matches[1].Length
    


回答2:

function Count-Object() {
    begin {
        $count = 0
    }
    process {
        $count += 1
    }
    end {
        $count
    }
}

$a= get-content .\members.txt |  
Foreach-Object { ($_  -replace '\s','') } |
Foreach-Object { ($_ -replace '-','') } |
Foreach-Object { ($_ -replace 'OP_ID','') } | 
Foreach-Object { ($_ -replace 'EFF_DT','') } |
Where-Object { $_ -ne '' }|
set-content  .\newmembers.txt

 $b = Get-Content  .\newmembers.txt |
Count-Object $b 
 "T {0:D9}" -f $b | add-content  .\newmembers.txt


回答3:

I also like the ? used in place of the where-object to trim it down just that much more.

Get-Content file.txt | ?{ $_ } > file2.txt


标签: powershell