Powershell Join-Path showing 2 dirs in result instead of 1 - accidental script/function output Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceWhy is Select-String returning a DirectoryInfo object in addition to MatchInfo objects?UTF8 Script in PowerShell outputs incorrect charactersCreating a folder if it does not exists - “Item already exists”Creating subfolders with PowerShell in multiple parent foldersSplit-Path + Join-Path functionalityHow do I write a PowerShell script to test and copy file paths?Copy-Item and Join-Path creates a folder instead of a filePowerShell 5 Copy-Item not workingPowershell Copy-Item -DestinationPowershell running scripts - not looking in relative pathUser input - folder and subfolder creation

How to market an anarchic city as a tourism spot to people living in civilized areas?

Replacing HDD with SSD; what about non-APFS/APFS?

Cold is to Refrigerator as warm is to?

How to say that you spent the night with someone, you were only sleeping and nothing else?

Active filter with series inductor and resistor - do these exist?

What do you call the holes in a flute?

Why does this iterative way of solving of equation work?

Slither Like a Snake

Stars Make Stars

Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?

Typsetting diagram chases (with TikZ?)

Unable to start mainnet node docker container

90's book, teen horror

Can I add database to AWS RDS MySQL without creating new instance?

Area of a 2D convex hull

Why does tar appear to skip file contents when output file is /dev/null?

How do I automatically answer y in bash script?

How can players take actions together that are impossible otherwise?

Do working physicists consider Newtonian mechanics to be "falsified"?

Is there a documented rationale why the House Ways and Means chairman can demand tax info?

Passing functions in C++

Why is "Captain Marvel" translated as male in Portugal?

Was credit for the black hole image misattributed?

How does modal jazz use chord progressions?



Powershell Join-Path showing 2 dirs in result instead of 1 - accidental script/function output



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceWhy is Select-String returning a DirectoryInfo object in addition to MatchInfo objects?UTF8 Script in PowerShell outputs incorrect charactersCreating a folder if it does not exists - “Item already exists”Creating subfolders with PowerShell in multiple parent foldersSplit-Path + Join-Path functionalityHow do I write a PowerShell script to test and copy file paths?Copy-Item and Join-Path creates a folder instead of a filePowerShell 5 Copy-Item not workingPowershell Copy-Item -DestinationPowershell running scripts - not looking in relative pathUser input - folder and subfolder creation



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am constructing incremental directory structures, and for some reason Join-Path is showing 2 dirs. When I later join that with a file I'm sending to copy-item, it causes an error, as shown below. I have shown in the comment for the $to_loc_finalDT1 line, where I first see these two dirs:



Copy-Item : Cannot find path '\T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv \T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv' because it does not exist


So this is the pertinent powershell script:



$T2 = "\T2DisasterBackupLoc" 
$toLocParentDT2 = CreateDatedFolder $parentDirBaseNameDT2
$to_loc_finalDT2 = Join-Path -Path $toLocParentDT2 -ChildPath "Privileges"
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT2 ))

write-output " Creating folder $to_loc_finalDT2 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT2 -force



#second dir save files to
$parentDirBaseNameDT1 = "\T1DisasterBackupLoc"
$toLocParentDT1 = CreateDatedFolder $parentDirBaseNameDT1
$to_loc_finalDT1 = Join-Path -Path $toLocParentDT1 -ChildPath "Privileges" #shows 2 dirs here in debugger: \T2DisasterBackupLoc_2019-03-08Privileges \T2DisasterBackupLoc_2019-03-08Privileges
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT1 ))

write-output " Creating folder $to_loc_finalDT1 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT1 -force



I'm not sure how to get Join_path to just have the one dir, as it should. Right now, I think it's being treated as an array, which is not correct.



I tried searching for related issues, but didn't see anything similar.



Update



Here's the code for CreateDatedFolder:



#create dated folder to put backup files in 
function CreateDatedFolder([string]$name)
$datedDir = ""
$datedDir = "$name" + "_" + "$((Get-Date).ToString('yyyy-MM-dd'))"
New-Item -ItemType Directory -Path $datedDir -force
return $datedDir



The output for that looks fine when it's returned. It appends the date onto the T2DisasterBackupLoc, but the debugger only shows one dir there, not an array or 2 dirs that are separate strings.










share|improve this question



















  • 2





    Is CreateDatedFolder a function? What does it do? To me it looks like CreateDatedFolder creates two outputs that are stored in $toLocParentDT1 and Join-Path processes them both.

    – T-Me
    Mar 8 at 15:22











  • @T-Me - I added CreateDatedFolder to the Update of my question. It appends the date to the folder given. The output shows just one folder correctly, not the two.

    – Michele
    Mar 8 at 15:29

















1















I am constructing incremental directory structures, and for some reason Join-Path is showing 2 dirs. When I later join that with a file I'm sending to copy-item, it causes an error, as shown below. I have shown in the comment for the $to_loc_finalDT1 line, where I first see these two dirs:



Copy-Item : Cannot find path '\T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv \T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv' because it does not exist


So this is the pertinent powershell script:



$T2 = "\T2DisasterBackupLoc" 
$toLocParentDT2 = CreateDatedFolder $parentDirBaseNameDT2
$to_loc_finalDT2 = Join-Path -Path $toLocParentDT2 -ChildPath "Privileges"
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT2 ))

write-output " Creating folder $to_loc_finalDT2 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT2 -force



#second dir save files to
$parentDirBaseNameDT1 = "\T1DisasterBackupLoc"
$toLocParentDT1 = CreateDatedFolder $parentDirBaseNameDT1
$to_loc_finalDT1 = Join-Path -Path $toLocParentDT1 -ChildPath "Privileges" #shows 2 dirs here in debugger: \T2DisasterBackupLoc_2019-03-08Privileges \T2DisasterBackupLoc_2019-03-08Privileges
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT1 ))

write-output " Creating folder $to_loc_finalDT1 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT1 -force



I'm not sure how to get Join_path to just have the one dir, as it should. Right now, I think it's being treated as an array, which is not correct.



I tried searching for related issues, but didn't see anything similar.



Update



Here's the code for CreateDatedFolder:



#create dated folder to put backup files in 
function CreateDatedFolder([string]$name)
$datedDir = ""
$datedDir = "$name" + "_" + "$((Get-Date).ToString('yyyy-MM-dd'))"
New-Item -ItemType Directory -Path $datedDir -force
return $datedDir



The output for that looks fine when it's returned. It appends the date onto the T2DisasterBackupLoc, but the debugger only shows one dir there, not an array or 2 dirs that are separate strings.










share|improve this question



















  • 2





    Is CreateDatedFolder a function? What does it do? To me it looks like CreateDatedFolder creates two outputs that are stored in $toLocParentDT1 and Join-Path processes them both.

    – T-Me
    Mar 8 at 15:22











  • @T-Me - I added CreateDatedFolder to the Update of my question. It appends the date to the folder given. The output shows just one folder correctly, not the two.

    – Michele
    Mar 8 at 15:29













1












1








1


1






I am constructing incremental directory structures, and for some reason Join-Path is showing 2 dirs. When I later join that with a file I'm sending to copy-item, it causes an error, as shown below. I have shown in the comment for the $to_loc_finalDT1 line, where I first see these two dirs:



Copy-Item : Cannot find path '\T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv \T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv' because it does not exist


So this is the pertinent powershell script:



$T2 = "\T2DisasterBackupLoc" 
$toLocParentDT2 = CreateDatedFolder $parentDirBaseNameDT2
$to_loc_finalDT2 = Join-Path -Path $toLocParentDT2 -ChildPath "Privileges"
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT2 ))

write-output " Creating folder $to_loc_finalDT2 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT2 -force



#second dir save files to
$parentDirBaseNameDT1 = "\T1DisasterBackupLoc"
$toLocParentDT1 = CreateDatedFolder $parentDirBaseNameDT1
$to_loc_finalDT1 = Join-Path -Path $toLocParentDT1 -ChildPath "Privileges" #shows 2 dirs here in debugger: \T2DisasterBackupLoc_2019-03-08Privileges \T2DisasterBackupLoc_2019-03-08Privileges
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT1 ))

write-output " Creating folder $to_loc_finalDT1 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT1 -force



I'm not sure how to get Join_path to just have the one dir, as it should. Right now, I think it's being treated as an array, which is not correct.



I tried searching for related issues, but didn't see anything similar.



Update



Here's the code for CreateDatedFolder:



#create dated folder to put backup files in 
function CreateDatedFolder([string]$name)
$datedDir = ""
$datedDir = "$name" + "_" + "$((Get-Date).ToString('yyyy-MM-dd'))"
New-Item -ItemType Directory -Path $datedDir -force
return $datedDir



The output for that looks fine when it's returned. It appends the date onto the T2DisasterBackupLoc, but the debugger only shows one dir there, not an array or 2 dirs that are separate strings.










share|improve this question
















I am constructing incremental directory structures, and for some reason Join-Path is showing 2 dirs. When I later join that with a file I'm sending to copy-item, it causes an error, as shown below. I have shown in the comment for the $to_loc_finalDT1 line, where I first see these two dirs:



Copy-Item : Cannot find path '\T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv \T2DisasterBackupLoc_2019-03-08PrivilegesPrivileges_HH_Bak.csv' because it does not exist


So this is the pertinent powershell script:



$T2 = "\T2DisasterBackupLoc" 
$toLocParentDT2 = CreateDatedFolder $parentDirBaseNameDT2
$to_loc_finalDT2 = Join-Path -Path $toLocParentDT2 -ChildPath "Privileges"
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT2 ))

write-output " Creating folder $to_loc_finalDT2 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT2 -force



#second dir save files to
$parentDirBaseNameDT1 = "\T1DisasterBackupLoc"
$toLocParentDT1 = CreateDatedFolder $parentDirBaseNameDT1
$to_loc_finalDT1 = Join-Path -Path $toLocParentDT1 -ChildPath "Privileges" #shows 2 dirs here in debugger: \T2DisasterBackupLoc_2019-03-08Privileges \T2DisasterBackupLoc_2019-03-08Privileges
#create sub-folder location
if(-Not (Test-Path $to_loc_finalDT1 ))

write-output " Creating folder $to_loc_finalDT1 because it does not exist "
New-Item -ItemType directory -Path $to_loc_finalDT1 -force



I'm not sure how to get Join_path to just have the one dir, as it should. Right now, I think it's being treated as an array, which is not correct.



I tried searching for related issues, but didn't see anything similar.



Update



Here's the code for CreateDatedFolder:



#create dated folder to put backup files in 
function CreateDatedFolder([string]$name)
$datedDir = ""
$datedDir = "$name" + "_" + "$((Get-Date).ToString('yyyy-MM-dd'))"
New-Item -ItemType Directory -Path $datedDir -force
return $datedDir



The output for that looks fine when it's returned. It appends the date onto the T2DisasterBackupLoc, but the debugger only shows one dir there, not an array or 2 dirs that are separate strings.







powershell return output return-value multiple-return-values






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 20:21









mklement0

140k23256293




140k23256293










asked Mar 8 at 15:03









MicheleMichele

1,47072845




1,47072845







  • 2





    Is CreateDatedFolder a function? What does it do? To me it looks like CreateDatedFolder creates two outputs that are stored in $toLocParentDT1 and Join-Path processes them both.

    – T-Me
    Mar 8 at 15:22











  • @T-Me - I added CreateDatedFolder to the Update of my question. It appends the date to the folder given. The output shows just one folder correctly, not the two.

    – Michele
    Mar 8 at 15:29












  • 2





    Is CreateDatedFolder a function? What does it do? To me it looks like CreateDatedFolder creates two outputs that are stored in $toLocParentDT1 and Join-Path processes them both.

    – T-Me
    Mar 8 at 15:22











  • @T-Me - I added CreateDatedFolder to the Update of my question. It appends the date to the folder given. The output shows just one folder correctly, not the two.

    – Michele
    Mar 8 at 15:29







2




2





Is CreateDatedFolder a function? What does it do? To me it looks like CreateDatedFolder creates two outputs that are stored in $toLocParentDT1 and Join-Path processes them both.

– T-Me
Mar 8 at 15:22





Is CreateDatedFolder a function? What does it do? To me it looks like CreateDatedFolder creates two outputs that are stored in $toLocParentDT1 and Join-Path processes them both.

– T-Me
Mar 8 at 15:22













@T-Me - I added CreateDatedFolder to the Update of my question. It appends the date to the folder given. The output shows just one folder correctly, not the two.

– Michele
Mar 8 at 15:29





@T-Me - I added CreateDatedFolder to the Update of my question. It appends the date to the folder given. The output shows just one folder correctly, not the two.

– Michele
Mar 8 at 15:29












1 Answer
1






active

oldest

votes


















2














As T-Me correctly inferred before you posted the CreateDatedFolder source, the problem is that the function inadvertently outputs 2 objects, and Join-Path accepts an array of parent paths to each join with the child path.



Specifically, it is the New-Item call that accidentally creates an additional output object, just before your return $datedDir call.



New-Item outputs a [System.IO.DirectoryInfo] instance representing the newly created directory and, due to PowerShell's implicit output behavior, that instance becomes part of what the function outputs too - any command or expression inside a script / function that returns a value that isn't captured or redirected becomes part of the output.



To prevent that, suppress the output:



$null = New-Item -ItemType Directory -Path $datedDir -force


Note that you never need return in PowerShell in order to output a result - but you may need it for flow control, to exit a function prematurely:



return $datedDir 


is syntactic sugar for:



$datedDir # Implicitly output the value of $datedDir.
# While you could also use `Write-Output $datedDir`,
# that is rarely needed and actually slows things down.
return # return from the function - flow control only





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065907%2fpowershell-join-path-showing-2-dirs-in-result-instead-of-1-accidental-script-f%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    As T-Me correctly inferred before you posted the CreateDatedFolder source, the problem is that the function inadvertently outputs 2 objects, and Join-Path accepts an array of parent paths to each join with the child path.



    Specifically, it is the New-Item call that accidentally creates an additional output object, just before your return $datedDir call.



    New-Item outputs a [System.IO.DirectoryInfo] instance representing the newly created directory and, due to PowerShell's implicit output behavior, that instance becomes part of what the function outputs too - any command or expression inside a script / function that returns a value that isn't captured or redirected becomes part of the output.



    To prevent that, suppress the output:



    $null = New-Item -ItemType Directory -Path $datedDir -force


    Note that you never need return in PowerShell in order to output a result - but you may need it for flow control, to exit a function prematurely:



    return $datedDir 


    is syntactic sugar for:



    $datedDir # Implicitly output the value of $datedDir.
    # While you could also use `Write-Output $datedDir`,
    # that is rarely needed and actually slows things down.
    return # return from the function - flow control only





    share|improve this answer





























      2














      As T-Me correctly inferred before you posted the CreateDatedFolder source, the problem is that the function inadvertently outputs 2 objects, and Join-Path accepts an array of parent paths to each join with the child path.



      Specifically, it is the New-Item call that accidentally creates an additional output object, just before your return $datedDir call.



      New-Item outputs a [System.IO.DirectoryInfo] instance representing the newly created directory and, due to PowerShell's implicit output behavior, that instance becomes part of what the function outputs too - any command or expression inside a script / function that returns a value that isn't captured or redirected becomes part of the output.



      To prevent that, suppress the output:



      $null = New-Item -ItemType Directory -Path $datedDir -force


      Note that you never need return in PowerShell in order to output a result - but you may need it for flow control, to exit a function prematurely:



      return $datedDir 


      is syntactic sugar for:



      $datedDir # Implicitly output the value of $datedDir.
      # While you could also use `Write-Output $datedDir`,
      # that is rarely needed and actually slows things down.
      return # return from the function - flow control only





      share|improve this answer



























        2












        2








        2







        As T-Me correctly inferred before you posted the CreateDatedFolder source, the problem is that the function inadvertently outputs 2 objects, and Join-Path accepts an array of parent paths to each join with the child path.



        Specifically, it is the New-Item call that accidentally creates an additional output object, just before your return $datedDir call.



        New-Item outputs a [System.IO.DirectoryInfo] instance representing the newly created directory and, due to PowerShell's implicit output behavior, that instance becomes part of what the function outputs too - any command or expression inside a script / function that returns a value that isn't captured or redirected becomes part of the output.



        To prevent that, suppress the output:



        $null = New-Item -ItemType Directory -Path $datedDir -force


        Note that you never need return in PowerShell in order to output a result - but you may need it for flow control, to exit a function prematurely:



        return $datedDir 


        is syntactic sugar for:



        $datedDir # Implicitly output the value of $datedDir.
        # While you could also use `Write-Output $datedDir`,
        # that is rarely needed and actually slows things down.
        return # return from the function - flow control only





        share|improve this answer















        As T-Me correctly inferred before you posted the CreateDatedFolder source, the problem is that the function inadvertently outputs 2 objects, and Join-Path accepts an array of parent paths to each join with the child path.



        Specifically, it is the New-Item call that accidentally creates an additional output object, just before your return $datedDir call.



        New-Item outputs a [System.IO.DirectoryInfo] instance representing the newly created directory and, due to PowerShell's implicit output behavior, that instance becomes part of what the function outputs too - any command or expression inside a script / function that returns a value that isn't captured or redirected becomes part of the output.



        To prevent that, suppress the output:



        $null = New-Item -ItemType Directory -Path $datedDir -force


        Note that you never need return in PowerShell in order to output a result - but you may need it for flow control, to exit a function prematurely:



        return $datedDir 


        is syntactic sugar for:



        $datedDir # Implicitly output the value of $datedDir.
        # While you could also use `Write-Output $datedDir`,
        # that is rarely needed and actually slows things down.
        return # return from the function - flow control only






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 27 at 20:19

























        answered Mar 8 at 15:33









        mklement0mklement0

        140k23256293




        140k23256293





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55065907%2fpowershell-join-path-showing-2-dirs-in-result-instead-of-1-accidental-script-f%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved