Max Filgate
Max Filgate

Reputation: 65

Concatenate path and file

I'm new to PowerShell, and am pretty happy with how far I've gotten with writing new functions etc, but this one has me stumped, such a simple thing ...

Below is the function:

Function fnConcatenatePathFile ([String]$Path, [String]$File)
{
   $FullPath = "$($Path)\$($File)"
   Return $FullPath
}

I then call the function like this:

fnConcatenatePathFile ("C:\_Store", "run.sql")

I expect the result to be:

"C:\_Store\run.sql"

But instead I get:

"C:\_Store run.sql\"

Driving me bonkers ... any clues?

Upvotes: 3

Views: 3612

Answers (2)

Martin Brandl
Martin Brandl

Reputation: 59031

Frode F. already showed you what you did wrong. However, there is a Join-Path cmdlet to combine a path:

Join-Path "C:\_Store" "run.sql"

Output:

C:\_Store\run.sql

Upvotes: 7

Frode F.
Frode F.

Reputation: 54981

You're using the wrong syntax for calling functions. In Powershell you separate arguments by a space and you also don't need to use ().

, is the array-operator, so "C:\_Store", "run.sql" actually passes an array of two strings to $Path and because you're using the variable (containing an array) in a string, the strings are joined together with a whitespace. $File is empty, which is why it ends with nothing after \.

Try:

fnConcatenatePathFile "C:\_Store" "run.sql"

or to make it clearer:

fnConcatenatePathFile -Path "C:\_Store" -File "run.sql"

Upvotes: 4

Related Questions