将变量传递给函数

Pass variables to function

我有两个功能。这些函数需要像这样传递一些早期声明的变量:

Function variable1, variable2

现在我尝试用 [ref] 做参数但没有成功。

这是其中一个函数的代码。在这种情况下,之前声明的变量是 $wincluster$vmhostwin.

function deploytemplatewin {
    foreach ($image in $winimage) {
        $templatename =  $image, $wincluster -join "_"
        $vcdatastore = $vc + "_vm_template_01"
        try {
            Get-Template $templatename -ErrorAction Stop;
            $TemplateExists = $true
        } catch {
            $TemplateExists = $false
        }
        if ($TemplateExists -eq $false) {
            Write-Log -Message "$($templatename) template was copied to cluster $($wincluster) on vCenter $($vc)"
            New-VM -Name $templatename -VMHost $vmhostwin -Datastore $vcdatastore -Location (Get-Folder -Name WinTemplates) |
                Set-VM -ToTemplate -Confirm:$false
        } elseif ($TemplateExists -eq $true) {
            Write-Log -Message "Template $($templatename) already existed in cluster $($wincluster) on vCenter $($vc)"
        }
    }
}

最坏的情况,我可以在函数中明确声明变量并且它有效。

如果您想要 function with parameters you need to define the parameters. You may also want to use the canonical Verb-Noun form for your function name (see here 获得批准的动词列表)。

简单方法:

function Deploy-WindowsTemplate($Cluster, $VMHost) {
    foreach ($image in $winimage) {
        $templatename = $image, $Cluster -join "_"
        ...
    }
}

更多advanced方法:

function Deploy-WindowsTemplate {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string]$Cluster,
        [Parameter(Mandatory=$true)]
        [string]$VMHost
    )

    foreach ($image in $winimage) {
        $templatename = $image, $Cluster -join "_"
        ...
    }
}

如果您愿意,您也可以不使用参数并使用 automatic variable $args,但我不建议这样做。

function Deploy-WindowsTemplate {
    foreach ($image in $winimage) {
        $templatename = $image, $args[0] -join "_"
        ...
    }
}

但是请注意,调用函数时 parameter/argument 值由空格而不是逗号分隔。它们可以作为位置参数传递(默认情况下按照参数定义的顺序)

Deploy-WindowsTemplate $wincluster $vmhostwin

或命名参数

Deploy-WindowsTemplate -Cluster $wincluster -VMHost $vmhostwin

逗号分隔值作为单个数组参数传递。

Deploy-WindowsTemplate $wincluster, $vmhostwin
#                      ^^^^^^^^^^^^^^^^^^^^^^^
#                           one argument!