首页 文章

PowerShell:将局部变量传递给函数

提问于
浏览
1

我有以下Powershell代码:

function readConfigData
{
    $workingDir = (Get-Location).Path
    $file = ""

    if ($Global:USE_LOCAL_SERVER)
    {
        $file = $workingDir + '\Configs\Localhost.ini'
    }
    else
    {
        $file = $workingDir + '\Configs\' + $env:COMPUTERNAME + '.ini'
    }

    Write-Host 'INIFILE: ' $file

    if (!$file -or ($file = ""))
    {
        throw [System.Exception] "Ini fil är inte satt."
    }
    if (!(Test-Path -Path $file))
    {
        throw [System.Exception] "Kan inte hitta ini fil."
    }
}

readConfigData

我应该如何声明可以传递给函数 Test-Path 的局部变量 $file . 我的局部变量$ file被填充,但是当我把它作为参数放到其他函数时,就像它超出了范围 .

我阅读了about scopes文章,但未能弄明白 .

目前我收到错误:

INIFILE:D:\ Projects \ scripts \ Configs \ HBOX.ini Test-Path:无法将参数绑定到参数'Path',因为它是一个空字符串 . 在D:\ Projects \ freelancer.com \ nero2000 \ cmd脚本到powershell \ script.ps1:141 char:27 if(!(Test-Path -Path $ file))~~~~~ CategoryInfo:InvalidData:(:) [Test-Path],ParameterBindingValidationException FullyQualifiedErrorId:ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand

3 回答

  • 1
    if (!$file -or ($file = ""))
    

    应该被替换

    if (!$file -or ($file -eq ""))
    

    您将$ file分配给第一个if子句中的空字符串,因此您的变量在Test-Path调用中为空 .

    编辑:还有一些替代方案:How can I check if a string is null or empty in PowerShell?

    你可以使用

    if([string]::IsNullOrEmpty($file))
    

    甚至只是

    if(!$file)
    
  • 1

    正如其他人所提到的,您在第一个 if (!$file ... 语句中无意中将空字符串分配给$ file . 这真的是你问题的根源 .

    但是,而不是:

    if (!$file -or ($file = ""))
    

    你可以使用这个论坛,我发现它更好地解释了:

    if([String]::IsNullOrEmpty($file))
    
  • 1

    我将定义一个函数 Get-ConfigFile 来检索配置并为本地服务器添加 switch

    function Get-ConfigFile
    {
        Param(
            [switch]$UseLocalServer
        )
    
        $workingDir = (Get-Location).Path
        if ($UseLocalServer.IsPresent)
        {
             Join-Path $workingDir '\Configs\Localhost.ini'
        }
        else
        {
             Join-Path $workingDir ('\Configs\{0}.ini' -f $env:COMPUTERNAME)
        }
    }
    

    我还将使用Join-Path cmdlet来加入路径而不是字符串连接 .

    现在,您可以使用以下命令检索配置文件路径:

    $configFile = Get-ConfigFile -UseLocalServer:$Global:USE_LOCAL_SERVER
    

    如果需要,请确保该文件存在:

    if (-not(Test-Path -Path $configFile))
    {
        throw [System.Exception] "Kan inte hitta ini fil."
    }
    

    注意:Get-Location将为您提供当前的powershell路径(工作位置),如果您想获取脚本所在的路径,请使用此代码:

    $workingDir = split-path -parent $MyInvocation.MyCommand.Definitio
    

相关问题