为什么新参数会改变我的 powershell 函数的行为?

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

正如标题所说,我对简单的 PowerShell 脚本感到很困惑

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)

当我 运行 这一切都按预期正常工作(文件夹已创建)。

模式 LastWriteTime 长度名称


d----- 2022 年 4 月 20 日 11:11 txt
PNG d----- 20.04.2022 11:11 png
jpg d----- 20.04.2022 11:11 jpg
C d----- 2022 年 4 月 20 日 11:11 c

但是当我现在像这样将字符串添加到参数列表时:

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)

它停止工作,但我没有收到任何错误。因为我的 Array 会突然为空或类似的东西...

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

create_dir($test_path, $my_folders)

你们能帮帮我吗?

我不确定你的第一个脚本是如何工作的,因为你发送的参数“$folders”没有在任何地方定义。

但要回答您的问题,只需传递 parameters/call 您的函数而不带括号和逗号。

例如。 create_dir $test_path $my_folders