0

As the title already says I'm very confused about my simple PowerShell script

function create_dir([array]$folders)
{
    $dir = "D:\test\New Folders"
    

    foreach ($folder in $folders)
    {
        Write-Host $folder
        New-Item -Path $dir -Name $folder -ItemType "directory" -Force
    }
}


$test_path = "D:\test\New Folders"
$my_folders = @("txt","png","jpg", "c")

create_dir($folders)

When I run this everything works fine and as intended (the folders get created).

Mode LastWriteTime Length Name


d----- 20.04.2022 11:11 txt
png d----- 20.04.2022 11:11 png
jpg d----- 20.04.2022 11:11 jpg
c d----- 20.04.2022 11:11 c

But when I now add a string to the parameterlist like this:

function create_dir([string]$test, [array]$folders)
{
    $dir = "D:\test\New Folders"
    

    foreach ($folder in $folders)
    {
        Write-Host $folder
        New-Item -Path $test -Name $folder -ItemType "directory" -Force
    }
}


$test_path = "D:\test\New Folders"
$my_folders = @("txt","png","jpg", "c")

create_dir($test_path, $my_folders)

It stops working but I dont get any errors. As my Array would suddently be empty or soemthing...

$test_path = "D:\test\New Folders" $my_folders = @("txt","png","jpg", "c")

create_dir($test_path, $my_folders)

Can you guys please help me?

atzaka
  • 3
  • 6
  • In `create_dir($test_path, $my_folders)` you are actually constructing an array of `$test_path` and `$my_folders` and pass that as a _single_ argument to the function. Proof: `function fun($a,$b){ "a: $a"; "b: $b" }; fun(1,2)`. PowerShell functions have to be called without parentheses, like shell commands: `create_dir $test_path $my_folders`. – zett42 Apr 20 '22 at 11:33
  • Does this answer your question? [PowerShell's parsing modes: argument (command) mode vs. expression mode](https://stackoverflow.com/questions/48776180/powershells-parsing-modes-argument-command-mode-vs-expression-mode) – zett42 Apr 20 '22 at 11:34

1 Answers1

0

I'm not sure how your first script worked since the parameter you sent "$folders" wasn't defined anywhere.

But to answer your question just pass the parameters/call your function without the parenthesis and comma.

Ex. create_dir $test_path $my_folders

Theo
  • 57,719
  • 8
  • 24
  • 41
Rass Rigor
  • 16
  • 1