Othor
Othor

Reputation: 25

Powershell Function Not Working With Return

   function Get-CHPEL-Report
        {
            Clear-Host
            Write-Output "Finding Newest CHPEL Report"
            $PathCHPEL = Get-ChildItem -Path S:\CHPEL | Sort-Object LastWriteTime | Select-Object -last 1 | Select-Object FullName | ForEach-Object{$_.FullName}
            Write-Output "Loading - $PathCHPEL"
            #$global:CHPEL = Get-Content -Path $PathCHPEL | Select-Object -Skip 1 | ConvertFrom-Csv -Delimiter "`t"
            $CHPEL = Get-Content -Path $PathCHPEL | Select-Object -Skip 1 | ConvertFrom-Csv -Delimiter "`t"
            return $CHPEL
            Clear-Host
        }
        
    $CHPEL = Get-CHPEL-Report

If i run this code I don't get anything written out to the screen and $CHPEL is empty. But the code does work if I make the variable global in the function and just call the function. How can I make this work with Return so I don't have to have a global variable?

   function Get-CHPEL-Report
        {
            Clear-Host
            Write-Output "Finding Newest CHPEL Report"
            $PathCHPEL = Get-ChildItem -Path S:\CHPEL | Sort-Object LastWriteTime | Select-Object -last 1 | Select-Object FullName | ForEach-Object{$_.FullName}
            Write-Output "Loading - $PathCHPEL"
            $global:CHPEL = Get-Content -Path $PathCHPEL | Select-Object -Skip 1 | ConvertFrom-Csv -Delimiter "`t"
            Clear-Host
        }

Get-CHPEL-Report

Upvotes: 0

Views: 159

Answers (1)

Damien
Damien

Reputation: 156

Try this:

function Get-CHPEL-Report {
    Clear-Host
    Write-Host "Finding Newest CHPEL Report"
    $PathCHPEL = Get-ChildItem -Path D:\Temp\stackoverflw | Sort-Object LastWriteTime | Select-Object -last 1 | Select-Object FullName | ForEach-Object{$_.FullName}
    Write-Host "Loading - $PathCHPEL"
    $CHPEL = Get-Content -Path $PathCHPEL | Select-Object -Skip 1 | ConvertFrom-Csv -Delimiter "`t"
    return $CHPEL
    #Clear-Host #Never executed
}
$CHPEL = Get-CHPEL-Report
Write-Host $CHPEL

I have replaced "Write-Output" by "Write-Host" because it was include in the $CHPEL variable. You can also remove the last "Clear-Host", it is after the "return" and will never be executed.

Upvotes: 1

Related Questions