Home > Software design >  Script to parse from CSV to txt file using powershel
Script to parse from CSV to txt file using powershel

Time:10-12

I have a .csv file with data that I am trying to parse into a txt file.

The contents of the .csv file looks like this

Name,Tag,Description
ServerA,BOH,Scheduling
ServerB,FOH,PrintServer
ServerC,BOH,DC

I am working on a script to import the data from that .csv and write to a txt file. Here is what I am trying to have the output look like.

ServerA:
    nodename: ServerA
    description: Scheduling
    Tag: BOH
    username: svc_act
    osFamily: windows
ServerB:
    nodename: ServerB
    description: PrintServer
    Tag: FOH
    username: svc_act
    osFamily: windows
ServerC:
    nodename: ServerC
    description: DC
    Tag: BOH
    username: svc_act
    osFamily: windows

I am missing something in my following code to get that result but cant figure it out. Thank you for any help

$servers = import-csv -path C:\Temp\Servers.csv -UseCulture | ft   

$output = $Servers | ForEach {
          foreach($server in $servers){
                "{$Server.name}"
                "nodename    = {$Server.name}"
                "description = {$Server.description}"
                "tag         = {$Server.tag}"
                "username: svc_act"
                "osFamily: windows"
                 }
             }    
    
$output | Out-File -FilePath C:\temp\Serverstagdesc.txt

CodePudding user response:

The output you are expecting looks like Yaml, therefore I recommend you a dedicated parser as: PowerShell-Yaml:

Install-Module powershell-yaml

$HashTable = [Ordered]@{}
import-csv -path C:\Temp\Servers.csv |ForEach-Object {
    $HashTable[$_.Name] = [Ordered]@{
        nodename    = 'BOERPT01'
        description = $_.Description
        tag         = $_.Tag
    }
}

$HashTable |ConvertTo-Yaml
Server1:
  nodename: BOERPT01
  description: Scheduling
  tag: BOH
Server2:
  nodename: BOERPT01
  description: PrintServer
  tag: FOH
Server3:
  nodename: BOERPT01
  description: DC
  tag: BOH

CodePudding user response:

$input = @'
Name,Tag,Description
Server,BOH,Scheduling
Server2,FOH,PrintServer
Server3,BOH,DC
'@ | 
    ConvertFrom-Csv 

$template = "Server{0}:`r`n`tnodename: {1}`r`n`tdescription: {2}`r`n`tTag: {3}`r`n"
$counter = 0;

$formatedItems = $input | 
    ForEach-Object {
        $counter  ; 
        return [String]::Format($template, $counter, $_.Name, $_.Description, $_.Tag) 
        }

$output = [String]::Join('', $formatedItems)
$output | Out-File -FilePath ...
  • Related