-1

Here is my question;

$source = "\\Somewhere\Overtherainbow\something.exe"
$destinationSource = "C:\temp"


Function MyCopyFunction([string]$from, [string]$to)
{
   $src= $source+$from
   $dest = $destinationSource+$to
    
   Copy-Item -Path $src -Destination $dest -Recurse
}

Function MyFunction([string]$p1, [string]$p2)
{
    MyCopy($p1, $p2)
}

    switch("1"){
    "1" {
     MyFunction("Dir1","Dir2") break;
}
}

Simple right ? Why is it when the "MyCopyFunction(p1,p2)" get called with 2 parameters it complains that the second parameter does not exist. But if I turn "MyCopyFunction($p1)" with only 1 parameter instead of two and supply the -Destination value manually, no issues what is the source of the issue here?

Here is the exception.... Copy-Item -Path $from -Destination $to -Recurse CategoryInfo : ObjectNotFound: ( :String) [Copy-Item], ItemNotFoundExcptionFullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

4
  • 2
    MyFunction "Dir1" "Dir2" no parentheses Commented Sep 23, 2021 at 0:49
  • I know that you can call a function with or without () MyFunction "para1","para2" is the same as MyFunction("para1","para2") is this not true ? And I've already tried this with and without () same result Commented Sep 23, 2021 at 0:52
  • 2
    @Ahhzeee No.... Commented Sep 23, 2021 at 1:10
  • 1
    In short: PowerShell functions, cmdlets, scripts, and external programs must be invoked like shell commands - foo arg1 arg2 - not like C# methods - foo('arg1', 'arg2'). If you use , to separate arguments, you'll construct an array that a command sees as a single argument. To prevent accidental use of method syntax, use Set-StrictMode -Version 2 or higher, but note its other effects. See this answer for more information. Commented Sep 23, 2021 at 2:00

1 Answer 1

3

The main problem is here,

MyCopyFunction(p1,p2)

When you call the function like this, PowerShell treats the input as a single array containing two elements and pass it positionally to the first variable(In this case it's $from). Instead of this, you should change the call site to MyCopyFunction "Dir1" "Dir2" to make it work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.