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?
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.
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.