0

I have a function with a returned value at the end but the returned value is not the right one ($createFolderResult took the value of $Destination), yet I initialize it to empty each time I use it. I don't understand why i have this behavior.

I tried with return or with Write-Output.

My code :

I call the function like this :

$serverResult = CreateFolder

Function :

    ####################
    ### CreateFolder ###
    ####################
    function CreateFolder {
        Invoke-Command -Session $session -ArgumentList $Destination, $serv -ScriptBlock {
            param (
                [string] $Destination,
                [string] $serv
            )
            
            [string] $createFolderResult = ''
            
            try {

                    if (-not ($Destination | Test-Path)) {
                    
                        Write-Host "INFO : Création du répertoire suivant en cours (fonction CreateFolder)... :" $Destination
                        New-Item -ItemType directory -Path $Destination
                        Write-Host "INFO : La création du répertoire a été réalisée avec succès (fonction CreateFolder):" $Destination

                    } else {

                        Write-Host "INFO : Le répertoire :" $Destination "existe déjà (fonction CreateFolder)!"

                    }
                
                } catch {
                    Write-Host "ERREUR : La création du répertoire n'a pas fonctionné (fonction CreateFolder) : "$_
                    $createFolderResult = $serv +" : ERREUR : La création du répertoire n'a pas fonctionné (fonction CreateFolder) : " +$_
            }
            
            #return $createFolderResult
            Write-Output $createFolderResult
            
        }

    }




Flincorp
  • 751
  • 9
  • 22
  • In short: any output - be it from a PowerShell command, an operator-based expression, or a .NET method call - that is neither captured in a variable nor redirected (sent through the pipeline or to a file) is _implicitly output_ from a script or function. To simply _discard_ such output, use `$null = ...`. If you don't discard such output, it becomes part of a script or function's "return value" (stream of output objects). See the linked duplicate for more information. – mklement0 Mar 07 '23 at 13:08
  • In your specific case: `New-Item -ItemType directory -Path $Destination` -> `$null = New-Item -ItemType directory -Path $Destination` – mklement0 Mar 07 '23 at 13:08

0 Answers0