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

时间:2016-05-09 13:25:38

标签: powershell

我有以下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

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

我阅读了about scopes文章,但无法弄明白。

目前我收到错误:

  

INIFILE:D:\ Projects \ scripts \ Configs \ HBOX.ini Test-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 个答案:

答案 0 :(得分:1)

[X(ii),Y(jj),Data(ii,jj)]

应替换为

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

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

编辑:还有一些选择:How can I check if a string is null or empty in PowerShell?

你可以使用

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

甚至只是

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

答案 1 :(得分:1)

正如其他人所提到的,您在第一个Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'System.Web.HttpContext'. JustMock Lite can only mock interface members, virtual/abstract members in non-sealed classes, delegates and all members on classes derived from MarshalByRefObject on instances created with Mock.Create or Mock.CreateLike. For any other scenario you need to use the full version of JustMock.语句中无意中将空字符串分配给$ file。这真的是你问题的根源。

但是,而不是:

if (!$file ...

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

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

答案 2 :(得分: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
相关问题