0

I have a function that receives a parameter which contains the file it should work on ($archivo). That same value should be passed on to another function that is called within the same function. But for some reason on the second function I'm getting a blank value.

function EXTRAER_DATA_COMIDA_Y_CREAR_WORD ($archivo) {
    
    write-host "EXTRAER_DATA_COMIDA" -foreground green
    $FILE = Join-Path -Path $root\UNB\FACTURA_FINAL\ -ChildPath $archivo
    $result = switch -Regex -File $FILE {
        '^([\d,.]+)\s+([\w\s]+)\s+([\d,.]+)' { 
            [PsCustomObject]@{
                Quantity = $matches[1].Trim()
                Product  = $matches[2].Trim()
                Price    = $matches[3].Trim()
            }
        }
    }
    
     ,$result
     CREAR_DOCWORD($result,$archivo)
    
} 

Which is the correct way to do it?

Thanks in advance !

EDIT: This is the new code as far as I can go

$results =function EXTRAER_DATA_COMIDA_Y_CREAR_WORD($archivo) 
{

write-host "EXTRAER_DATA_COMIDA" -fore green
$FILE = Join-Path -Path $root\UNB\FACTURA_FINAL\ -ChildPath $archivo
$result = switch -Regex -File $FILE {
    '^([\d,.]+)\s+([\w\s]+)\s+([\d,.]+)' { 
        [PsCustomObject]@{
            Quantity = $matches[1].Trim()
            Product  = $matches[2].Trim()
            Price    = $matches[3].Trim()
        }
    }
}
 ,@($result)
 Write-Host "variables que entran a docword" $results $results.GetType() $archivo
 CREAR_DOCWORD $results $archivo

}

FUNCTION CREAR_DOCWORD($COMIDA,$archivo) {

$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$Path = "$root\UNB\script\Tiquete_UnBilling.docx"
$objDoc = $objWord.Documents.Open("$Path")
$objSelection = $objWord.Selection

Write-Host "variables docword" $COMIDA $COMIDA.GetType() $archivo
   
    ## ESTA FUNCION CREA LA TABLA CON LOS DATOS DE COMIDA

    Write-Host "TAMAÑO ARRAY" $COMIDA.Length
    Write-Host "NOMBRE ARCHIVO" $archivo

    $table = $objDoc.Tables(1)
    
    for ($i=0; $i -le $comida.Count; $i++){
    Write-Host "contador" $i
    $table.rows.add() | out-null
    $table.cell(($i+2),1).Range.Text = $comida[$i].Quantity
    $table.cell(($i+2),2).Range.Text = $comida[$i].Product
    $table.cell(($i+2),3).Range.Text = $comida[$i].Price
    }
}

Even using ,@($result) I get a type object that looks like System.Management.Automation.PSCustomObject so it cant be use in the for loop because it has no size.

  • 1
    You don’t wrap parameters in ```( … )``` for a function call - that is, ```CREAR_DOCWORD($result,$archivo)``` should be ```CREAR_DOCWORD $result $archivo``` (assuming the function accepts positional parameters in the expected order). There are other answers on this site that explain what your code is actually doing… – mclayton Dec 06 '22 at 09:12
  • Here’s an example duplicate - https://stackoverflow.com/questions/4988226/how-do-i-pass-multiple-parameters-into-a-function-in-powershell – mclayton Dec 06 '22 at 09:19
  • You might want to look into [MS Learn - Approved Verbs for PowerShell Commands](https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands) – Dennis Dec 06 '22 at 11:42
  • Use two lines [1] get the results: `$result = EXTRAER_DATA_COMIDA_Y_CREAR_WORD $archivo` [2] use these results for the next function `CREAR_DOCWORD $result $archivo` – Theo Dec 06 '22 at 13:09
  • For some reason its not working at all. Im editing the code so you can have a better idea – Juan Manuel Sanchez Dec 06 '22 at 20:00

1 Answers1

0

Got it to work... the code is as following.

function EXTRAER_DATA_COMIDA_Y_CREAR_WORD($archivo) 
{

write-host "EXTRAER_DATA_COMIDA" -fore green
$FILE = Join-Path -Path $root\UNB\FACTURA_FINAL\ -ChildPath $archivo
$result = switch -Regex -File $FILE {
    '^([\d,.]+)\s+([\w\s]+)\s+([\d,.]+)' { 
        [PsCustomObject]@{
            Quantity = $matches[1].Trim()
            Product  = $matches[2].Trim()
            Price    = $matches[3].Trim()
        }
    }
}
 Write-Host "variables que entran a docword" $result $result.GetType() $archivo
 &CREAR_DOCWORD -COMIDA @($result) -archivo $archivo

}

FUNCTION CREAR_DOCWORD {

Param($COMIDA,$archivo)

$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$Path = "$root\UNB\script\Tiquete_UnBilling.docx"
$objDoc = $objWord.Documents.Open("$Path")
$objSelection = $objWord.Selection

Write-Host "variables docword" $COMIDA $COMIDA.GetType() $archivo
   
    ## ESTA FUNCION CREA LA TABLA CON LOS DATOS DE COMIDA

    Write-Host "TAMAÑO ARRAY" $COMIDA.Length
    Write-Host "NOMBRE ARCHIVO" $archivo

    $table = $objDoc.Tables(1)
    
    for ($i=0; $i -le $comida.Count; $i++){
    Write-Host "contador" $i
    $table.rows.add() | out-null
    $table.cell(($i+2),1).Range.Text = $comida[$i].Quantity
    $table.cell(($i+2),2).Range.Text = $comida[$i].Product
    $table.cell(($i+2),3).Range.Text = $comida[$i].Price
    }

    ## ESTA FUNCION SUSTITUYE TEXTO

    Write-Host "ESTA FUNCION SUSTITUYE TEXTO" -fore White
    
    $consecutivo_fact =get-random -maximum 100
    $fecha= Get-Date -Format "dd/MM/yyyy"
    $hora= Get-Date -Format "HH:mm tt"
    $CODIGO_UNBILLING=  -join ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count 8  | % {[char]$_}) 

    Write-Host "ARCHIVO " $archivo -fore White

    $content = Get-Content $root\UNB\FACTURA_FINAL\$archivo

     for($i = 0; $i -lt $content.Count; $i++)
    {
 
     $line = $content[$i]
     Write-Host $line

     if ($line.Contains('%SER'))
       
       {
       $SERVICIO=$line.Split(' ')[-1]
       }

    elseif ($line.Contains('SubTotal'))
    
        {
        $SUBTOTAL=$line.Split(' ')[-1]
        }

    elseif ($line.Contains('Descto'))
    
        {
        $DCTO=$line.Split(' ')[-1]
        }

    elseif ($line.Contains('TOTALES :'))
    
        {
        $TOTALFACTURA=$line.Split(' ')[-1]
        }

    elseif ($line.Contains('%IVA'))
    
        {
        $IVA=$line.Split(' ')[-1]
        }

    elseif ($line.Contains('Mesa #'))
    
        {
        $MESA=$line.Split(' ')[4]
        }

     else {
     $DCTO="0.00"
     }

    }

    $hash = @{"[CONS]" = "$consecutivo_fact"; "[FECHA]"="$fecha"; "[HORA]"="$hora"; "[CODIGO]"="$CODIGO_UNBILLING".ToUpper();"[CarSer]"="$SERVICIO";"[TV]"="$SUBTOTAL";"[TD]"="$DCTO";
    "[TVN]"="$TOTALFACTURA";"[IVA]"="$IVA";"[TOTAL]"="$TOTALFACTURA";"[MESA]"="$MESA"}

    $objSelection = $objWord.Selection
   
    $MatchCase = $false
    $MatchWholeWord = $true
    $MatchWildcards = $false
    $MatchSoundsLike = $false
    $MatchAllWordForms = $false
    $Forward = $true
    $wrap = $wdFindContinue
    $wdFindContinue = 1
    $Format = $false
    
    $ReplaceAll = 2

    foreach($value in $hash.Keys) {
    
    $ReplaceWith = $hash[$value]
    $FindText = $value
    $objSelection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $wrap, $Format, $ReplaceWith, $ReplaceAll)
   
    }

    }
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Please note that we will not be using ChatGPT to post answers here, see [Temporary policy: ChatGPT is banned](https://meta.stackoverflow.com/q/421831), because the chatbot may *sound* convincing, but it doesn't actually know how to code. – Martijn Pieters Dec 07 '22 at 21:18