Passing Variables To/From a Function

I cobbled together some things I found on teh interwebs to make sure a directory name is properly formatted for use. I am having trouble getting the corrected variable back from the function.

When the script wasn’t “doing right”, I tested it by just adding the " \ " character to the variable in the function. The corrected string isn’t making it back to the main part of the code. What am I doing wrong?

Here it is:

function Fix-DirPath ($dirname) {
$dirname = $dirname+""
Write-Host “Inside function: $dirname”
Write-Host
}

$a = “C:\Windows”
Fix-DirPath $a
Write-Host $a

$a just comes back “c:\windows” inside the function the directory is correct.

Thank you for your help!!

So at the end of the function I added this line:

return $dirname

And now it’s working correctly. Is this the “correct” thing to do to use a function like this?

A couple things:

Inside your function you’re just adding “” (nothing) to the end of $dirname, so I got the same thing from the original code, inside and out of the function:

C:\Windows
C:\Windows

You are correct that the best thing to do is return your output (whether single variable, array, etc.) from the function to the main script if you are going to use that information at a later point in your code.

Lastly, it may make concatenating strings and variables together a bit easier if instead of something like this:

$dirname+"1234"

you use something like this:

"$($dirname)1234"

just a suggestion, might make things easier on you.

In PowerShell it is not necessary to do the “return thing”. You can use it to make your code a little easier to read but EVERYTHING you drop inside of a function will become its ouput even if it does not have a “return” in front of it. See this:

function out-something {
    param (
        [Parameter(Mandatory=$true)]
        [string]
        $Something,
        [Parameter(Mandatory = $true)]
        [string]
        $SomethingElse
    )
    "$Something and $SomethingElse"
}

When you run this code it will ask you to provide values for “Something:” and for “SomethingElse:”. And when you do so it will just output it together. Without “return” in the function. :wink:

Yeah, that’s a weird thing, when I pasted the code here it left out the . So it should have looked like " \ ".

That’s interesting! I didn’t know you could do that. Thank you for that!

Ooooo, see, I ran across some example scripts with the more elaborate ‘param’ parameters (apologies, lol) but I wasn’t entirely sure how to use those myself. Definitely something to think about; I really appreciate that example.