Scott Anderson
Scott Anderson

Reputation: 693

If-else not executing in powershell script

I am currently trying to create a PowerShell script that performs the same functionality as cd, but also checks for a .git folder (new directory is a git repository) and then if true subsequently fetches and performs git status.

I am trying to debug at the moment in PowerShell ISE, but in the debugger my script skips straight over the blocks inside of the if..else statements. Is this a syntax error, or should the if..else work correctly?

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!"
    }
}

P.S: I am aware that the long Where-Object pipe is awful (and indubitably non-functional as-is), but this is my 1st script. Would welcome any help with it but my main issue is the execution skipping the if/else code blocks.

Upvotes: 2

Views: 1112

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Just use Test-Path to check for a .git subfolder. I'd also recommend checking if the repository actually was cloned before calling git fetch.

function Set-LocationGit {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [String]$Location
    )

    if ($Location -eq $PWD.Path) {
        return  # path not changed => nothing to do
    }

    Set-Location $Location

    if (Test-Path -LiteralPath '.\.git' -Type Container) {
        if (git config --get 'remote.origin.url') { git fetch }
        git status
    }
}

Upvotes: 1

Rishi Kc
Rishi Kc

Reputation: 95

Hi you have an error in your Where-Object pipe which should have been an another if block. See my modified code and it works for me.

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>

Hope this helps.

Upvotes: 1

Related Questions