首页 > 解决方案 > if-else 不在 powershell 脚本中执行

问题描述

我目前正在尝试创建一个 PowerShell 脚本,该脚本执行与 .git 相同的功能cd,但还会检查 .git 文件夹(新目录是 git 存储库),然后如果为 true,则随后获取并执行 .git 文件夹git status

我目前正在尝试在 PowerShell ISE 中进行调试,但在调试器中,我的脚本直接跳过了if..else语句内的块。这是语法错误,还是应该if..else正常工作?

function gd {
    #set parameters taken from program (only file location)
    Param(
        [Parameter(Position=0)]
        [String]$location
    )

    #get current directory location
    [String]$Cl = $(Get-Location)

    Set-Location $location

    [String]$Nl = $(Get-Location)

    if ($Cl -eq $Nl) {
        return
    } else {
        Get-ChildItem -Hidden | Where-Object {
            $_.Name -eq ".git"
        } | Write-Output "Eureka!";
        git fetch;
        git status;
        return
        Write-Output "No .git found here!"
    }
}

PS:我知道长Where-Object管道很糟糕(并且毫无疑问无法正常工作),但这是我的第一个脚本。欢迎任何帮助,但我的主要问题是跳过 if/else 代码块的执行。

标签: powershellscripting

解决方案


嗨,您的 Where-Object 管道中有一个错误,它应该是另一个 if 块。查看我修改后的代码,它对我有用。

function gd {
    #set parameters taken from program (only file location)
    Param(
        [Parameter(Position=0)]
        [String]$location
    )
    #get current directory location
    [String]$Cl = $(Get-Location)

    Set-Location $location
    $location
    [String]$Nl = $(Get-Location)

    if ($Cl -eq $Nl) {
    return
    } else {
        if(Get-ChildItem -Hidden | Where-Object {
            $_.Name -eq ".git"
        } ) 
    {
        Write-Output "Eureka!"
        git fetch;
        git status;
        }
        else{
        Write-Output "No .git found here!"
    }
    }
}
gd D:\<git-folder>

希望这可以帮助。


推荐阅读