Home > OS >  Why does a new parameter change the behavior of my powershell function?
Why does a new parameter change the behavior of my powershell function?

Time:04-21

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?

CodePudding user response:

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

  • Related