-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

Ahhzeee
  • 123
  • 1
  • 12
  • 2
    `MyFunction "Dir1" "Dir2"` no parentheses – js2010 Sep 23 '21 at 00: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 – Ahhzeee Sep 23 '21 at 00:52
  • 2
    @Ahhzeee No.... – js2010 Sep 23 '21 at 01: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`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-strictmode) or higher, but note its other effects. See [this answer](https://stackoverflow.com/a/65208621/45375) for more information. – mklement0 Sep 23 '21 at 02:00

1 Answers1

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46