繁体   English   中英

如何将多个变量传递给 powershell 函数?

[英]How do I pass multiple variables to a powershell function?

只是把它放在那里。 这是我下载和安装应用程序的代码。

# File Download and Install Function
function FDL($url){
# set to the default download directory; obviously can be wherever one wants
$DL = set-location $env:USERPROFILE\downloads\
# using this to capture just the filename
$FN = $url -split("/")
$FD = $FN[$FN.Length-1]
# Download File
Start-BitsTransfer -source $url -destination $DL\$FD
# Install File
Start-Process -NoNewWindow $DL\$FD -ArgumentList $args
}

PS:> FDL "https://www.kymoto.org/downloads/ISStudio_Latest.exe"

假设 URL 正确,此功能每次都能完美运行!

然后我想,如果我有为安装程序类型放置正确参数的功能怎么办。 所以我想出了这个:

# File Download and Install Function
function FDL($url,$p){
    # set to the default download directory; obviously can be whereever one wants
    $DL = set-location $env:USERPROFILE\downloads\
    # using this to capture just the filename
    $FN = $url -split("/")
    $FD = $FN[$FN.Length-1]
    
    switch ($p){
        1 {" /passive /qb /norestart";break}
        2 {" /sp- /silent /norestart /SUPPRESSMSGBOXES /CURRENTUSERS /NORESTART /NOCANCEL /FORCECLOSEAPPLICATION /RESTARTAPPLICATIONS";break}
        3 {" /SILENT";break}
        4 {" /quiet";break}
        5 {" /S";break}
        6 {" /Q";break}
    }
    
    Start-BitsTransfer -source $url -destination $DL\$FD
    Start-Process -NoNewWindow $DL\$FD -ArgumentList $p
}

# 2 because this is an InnoSetup   installer type
PS:> FDL 'https://www.kymoto.org/downloads/ISStudio_Latest.exe', 2 

失败

Start-BitsTransfer : The number of items specified in the Source parameter do not match the number of items specified in the Destination parameter. Verify that the same 
number of items is specified in the Source and Destination parameters.
At [dir]\FileDownloader Function.ps1:17 char:1
+ Start-BitsTransfer -source $url -destination $DL\$FD
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Start-BitsTransfer], ArgumentException
    + FullyQualifiedErrorId : StartBitsTransferArgumentException,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
Start-BitsTransfer : 
At [dir]\FileDownloader Function.ps1:17 char:1
+ Start-BitsTransfer -source $url -destination $DL\$FD
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Start-BitsTransfer], Exception
    + FullyQualifiedErrorId : System.Exception,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
Start-Process : Cannot validate argument on parameter 'ArgumentList'. The argument is null or empty. Provide an argument that is not null or empty, and then try the 
command again.
At [dir]\FileDownloader Function.ps1:20 char:50
+ Start-Process -NoNewWindow $DL\$FD -ArgumentList ($p)
+                                                  ~~~~
    + CategoryInfo          : InvalidData: (:) [Start-Process], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartProcessCommand

无论我如何调整此代码,它都会出现相同的错误。 任何建议或帮助将不胜感激!

可能不是您正在寻找的内容,但它应该会提示您在 PowerShell 中处理函数的代码。

一些指针,PowerShell 中的参数要么是Positional要么是Namedabout_Parameters解释了这两个概念。 最重要的是,每个参数都由空格不是逗号分隔。

您可以使用Uri Class解析 URL,因此,从您的地址获取文件名非常简单:

# Last segment from this Uri (index -1 from the segment array)
([uri] 'https://www.kymoto.org/downloads/ISStudio_Latest.exe').Segments[-1]

-ArgumentList from Start-Process需要string[] ,您可以传递参数数组而不是单个字符串,如示例 7所示。

您永远不会从switch ($p)捕获输出,这解释了错误:

启动过程:无法验证参数“ArgumentList”上的参数。 参数为 null 或空。

可以使用哈希表代替switch

最后,我添加了一个-PassThru开关,现在如果您在激活开关的情况下调用该函数( DownloadFile -PassThru -Uri ... ),该函数将输出代表已启动进程的Process实例

function DownloadFile {
    [cmdletbinding()]
    param(
        [parameter(Mandatory)]
        [uri] $Uri,

        [parameter()]
        [ValidateSet(1,2,3,4,5,6)]
        [int] $Arguments,

        [parameter()]
        [string] $Destination = "$env:USERPROFILE\Downloads",

        [parameter()]
        [switch] $PassThru
    )

    $arg = @{
        1 = '/passive', '/qb', '/norestart'
        2 = @(
            '/sp-', '/silent', '/norestart', '/SUPPRESSMSGBOXES'
            '/CURRENTUSERS', '/NORESTART', '/NOCANCEL'
            '/FORCECLOSEAPPLICATION', '/RESTARTAPPLICATIONS'
        )
        3 = '/SILENT'
        4 = '/quiet'
        5 = '/S'
        6 = '/Q'
    }

    $destFile = Join-Path $Destination -ChildPath $Uri.Segments[-1]
    Start-BitsTransfer -Source $Uri -Destination $destFile
    $param = @{
        FilePath     = $destFile
        ArgumentList = $arg[$Arguments]
        NoNewWindow  = $true
        PassThru     = $PassThru.IsPresent
    }
    Start-Process @param
}

DownloadFile -Uri 'https://www.kymoto.org/downloads/ISStudio_Latest.exe' -Arguments 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM