Value is not returned by function

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Guido Langendorff Guido Langendorff 12 months ago.

  • Author
  • #31378
    Profile photo of Guido Langendorff
    Guido Langendorff

    So, I am rebuilding all my scripts with the use of a library of functions. I call my library using the . DOT notation.
    All "migrated" functions run fine except for this one (part of it):
    # Create LogFolder for present run
    $LogFolder = $SwFolder + "\" + [string]$(get-date -f yyMMddHHmm)
    Write-Host "LogFolderInFunc = "$LogFolder
    New-Item -ItemType Directory -Force -Path $LogFolder
    $LogFolder is created, so this part is working.

    But returning to the main script $LogFolder only holds the value of:
    "\" + [string]$(get-date -f yyMMddHHmm).
    Strangly $SwFolder is vanished

    Where am I going wrong?

  • #31385
    Profile photo of Tore Groneng
    Tore Groneng

    You have a variable scoping issue. Please read up on about_scoping. Solution is to create a function that returns a folder object (directoryinfo) or a string. Create an example for you:

    Alternative is to use scoping when you declare variables like $global:VariableName however global declarations like this is not best practice. Better to use $script:VariableName.



  • #31392
    Profile photo of Guido Langendorff
    Guido Langendorff

    Did not know I was looking for this 😉
    It does make sense and I now know all about it!
    And it is working like a charm
    Thx Tore...

You must be logged in to reply to this topic.