0

-U returns the else echo statement and I can't figure out why. Everything else works if just seems to be ignoring my first if statement. The script functions for folder navigation. -U should return the /users/username directory. Thanks in advance for the help.

function  display-path {Get-ChildItem Env:Path }
function folder {

    [CmdletBinding(DefaultParameterSetName='Default')]
    param(    
        [Alias('u')]
        [Parameter(ParameterSetName='User')]
        [switch] $Username
        ,
        [Alias('s')]
        [Parameter(ParameterSetName='Scripts')]
        [switch] $Scripts
        ,
        [Parameter(ParameterSetName='Desktop')]
        [Alias('d')]
        [switch] $Desktop
        ,
        [Alias('h')]
        [Parameter(ParameterSetName='help')]
        [switch] $Help
        ,
        [Alias('r')]
        [Parameter(ParameterSetName='root')]
        [switch] $root
        )
      
    $targetFolder = 
    if ($Username) {
        $targetFolder += '\user\username'
        }
    if ($Scripts) {
        $targetFolder += '\Desktop\Scripts'
    } 
    elseif ($Desktop) {
        $targetFolder += '\Desktop'
    }
    if ($root) {
        $targetFolder += 'c:\'

    }
      
    else { 
        echo "
        -H         Display help. This is the same as not typing any options.
        -U         Change to the 'Username' directory
        -S         Change to the 'scripts' directory
        -D         Change to the 'desktop' directory"
            
    }
      
    Push-Location -LiteralPath $targetFolder
}

EDIT: Here is the code updated with the else if statement that doesn't work, it is ignoring the first if statement.

function  display-path {Get-ChildItem Env:Path }

    <# 
    **One of these can be used to navigate to the username directory. The first will only allow you to navigate to one user, the second allows for you to select the user.**
    $targetFolder = 
      if ($Username) { 
        $targetFolder += '\user\Username' #replace with your username
      } 
       
    if ($Username) { 
      Join-Path (Split-Path -LiteralPath $HOME) $Username
    } else {
      $HOME
    } #>
    function folder {
        [CmdletBinding(DefaultParameterSetName='Default')]
        param(    
          [Alias('u')]
          [switch] $Username
          ,
          [Alias('s')]
          [Parameter(ParameterSetName='Scripts')]
          [switch] $Scripts
          ,
          [Parameter(ParameterSetName='Desktop')]
          [Alias('d')]
          [switch] $Desktop
          ,
          [Alias('h')]
          [Parameter(ParameterSetName = 'help')]
          [switch]$Help
          ,
          [Alias('r')]
          [Parameter(ParameterSetName = 'root')]
          [switch]$root
        )
      
        $targetFolder = 
        if ($Username) { 
        $targetFolder += '\users\username   
          }
          elseif ($Scripts) {
          $targetFolder += '\Desktop\Scripts'
        }
          elseif ($Desktop) {
          $targetFolder += '\Desktop'
        }
          elseif ($root) {
  
            ## same as other but we can use $env:homedrive for the root of C:
        
            $targetFolder = $env:HOMEDRIVE + '\'
            $r = ' -R '
        
          }
        elseif ($Help) {
        echo "
        -H         Display help. This is the same as not typing any options.
        -U         Change to the 'Username' directory
        -S         Change to the 'scripts' directory
        -D         Change to the 'desktop' directory"
    }
        else {
        echo "
        -H         Display help. This is the same as not typing any options.
        -U         Change to the 'Username' directory
        -S         Change to the 'scripts' directory
        -D         Change to the 'desktop' directory"
    }
      
        Push-Location -LiteralPath $targetFolder
      }

3
  • 2
    Because you are missing a bunch of elseifs in your chain of checks (or the whole setup is wrong)? That final else is executed when $root is not specified regardless of other parameters. Commented Apr 29, 2022 at 21:35
  • how should it be? Commented Apr 29, 2022 at 21:48
  • the else statement is executed if the requirements of the if and ellseif statement are not met. See here for documentation: learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/… Commented Apr 29, 2022 at 21:59

2 Answers 2

2

If you want parameters to do something mutually exclusive and show help only if none are specified, you need to chain all your checks in a single if ... elseif ... elseif ... else chain:

    if ($Username) {
        $targetFolder += '\user\swmur'
    }
    elseif ($Scripts) {
        $targetFolder += '\Desktop\Scripts'
    } 
    elseif ($Desktop) {
        $targetFolder += '\Desktop'
    }
    elseif ($root) {
        $targetFolder += 'c:\'
    }
    else {
        echo "
        -H         Display help. This is the same as not typing any options.
        -U         Change to the 'Username' directory
        -S         Change to the 'scripts' directory
        -D         Change to the 'desktop' directory"
    }

Sign up to request clarification or add additional context in comments.

6 Comments

That broke it entirely. now it does nothing
This wouldn't break it. Maybe post your updated code. He didn't give you the entire function, just the if elseif portion
the first if statement is ignored, so the rest of the elseif are also ignored
@RobertCotterman see edit for code
@user14894283, your updated code misses a closing quote in $targetFolder += '\users\username line messing up the whole script. Also, you don't need the $targetFolder = line. What do you think it does?
|
2

I added some colorful commentary. This should be pretty close to what you're looking for.

function display-path {
  <#
    .SYNOPSIS
    quick shortcut to get env:PATH

    .DESCRIPTION
    Call Get-ChildItem with the the -path set to "env:Path" which actually just outputs out the child items of the current folder...

    .EXAMPLE
    display-path | Format-List


    Name  : Path
    Value : C:\Program Files\Eclipse Adoptium\jdk-17.0.2.8-hotspot\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPow
          erShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\ProgramData\chocolatey\bin;C:\Program Files\Go\bin;C:\Program 
          Files\dotnet\;C:\Program Files\Eclipse Adoptium\jdk-17.0.2.8-hotspot\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\Syste
          m32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\ProgramData\chocolatey\bin;C:\Program 
          Files\Go\bin;C:\Program Files\dotnet\;C:\Python310\Scripts;C:\Users\jedurham\AppData\Local\Programs\Microsoft VS Code\bin

    .NOTES
    not sure why anyone needs this

#>

  Get-ChildItem -Path Env:Path 
}



function folder {
  <#
    .SYNOPSIS
    shortcut to move between folder someone uses often

    .DESCRIPTION
    shortcut to move between folder someone uses often. 
    can be used to quickly navigate to common directories.

    .PARAMETER Username
    Moves to the C:\Users\currentuser\ Folder.

    .PARAMETER Scripts
    Moves to a hard coded path called 'C:\Users\currentuser\Desktop\Scripts'

    .PARAMETER Desktop
    Moves to a hard coded path called 'C:\Users\currentuser\Desktop\'

    .PARAMETER Help
    Displays this file.

    .PARAMETER root
    Moves to the root of the current drive. 


    .EXAMPLE
    folder -Username
    C:> folder -U
    You chose the -U  flag!! Moving to C:\Users\currentuser\

    .EXAMPLE
    folder -Scripts

    C:> folder -S
    You chose the -S  flag!! Moving to C:\Users\currentuser\Desktop\Scripts

    .EXAMPLE
    folder -Desktop

    C:> folder -D
    You chose the -D flag!! Moving to C:\Users\currentuser\Desktop\
    

    .EXAMPLE
    folder -root
    C:\> folder -r
    You chose the -R flag!! Moving to C:\

    .NOTES
    Needs a lot of work .... 

    v0.01

#>



  [CmdletBinding(DefaultParameterSetName = 'Default')]
  param(
    [Alias('u')]
    [Parameter(ParameterSetName = 'User')]
    [switch]$Username
    ,
    [Alias('s')]
    [Parameter(ParameterSetName = 'Scripts')]
    [switch]$Scripts
    ,
    [Parameter(ParameterSetName = 'Desktop')]
    [Alias('d')]
    [switch]$Desktop
    ,
    [Alias('h')]
    [Parameter(ParameterSetName = 'help')]
    [switch]$Help
    ,
    [Alias('r')]
    [Parameter(ParameterSetName = 'root')]
    [switch]$root
  )



  $switchoutput = 'You chose the{0} flag!! Moving to {1}{2}'


  if ($Username) {

    ## you need more comments in your code
    ## are you just trying to move the \user\current logged in?
    ## just use $env:USERPROFILE

    $targetFolder = $env:USERPROFILE
    $u = ' -U'
    Write-Output -InputObject ($switchoutput -f $U, $targetFolder, '')


  }
  elseif ($Scripts) {

    ## a little tougher here because you need to hard code this path
    ## we could also ask for it ask an addendum to this switch :P
    ## ill do it this way

    $targetFolder = $env:USERPROFILE
    $s = ' -S '
    ## it might be better to define this else 

    $scriptspath = 'Desktop\Scripts'
    $targetFolder = $env:USERPROFILE + $scriptspath

    Write-Output -InputObject ($switchoutput -f $S, $targetFolder, '')

  }


  elseif ($Desktop) {

    ## same as above
    ## it might be better to define this else

    $desktop = '\Desktop\'
    $targetFolder = $env:USERPROFILE + $desktop
    $d = ' -D '

    Write-Output -InputObject ($switchoutput -f $d, $targetFolder, '')


  }
  elseif ($root) {

    ## same as other but we can use $env:homedrive for the root of C:

    $targetFolder = $env:HOMEDRIVE + '\'
    $r = ' -R '

    Write-Output -InputObject ($switchoutput -f $r, $targetFolder, '')
  }


  else {
    Write-Output -InputObject "
        -H         Display help. This is the same as not typing any options.
        -U         Change to the 'Username' directory
        -S         Change to the 'scripts' directory
        -D         Change to the 'desktop' directory"
        -R         Change to the Root of home directory"

  }

  if (Test-Path -Path $targetFolder) {
    Set-Location -LiteralPath $targetFolder -Verbose
  }
  else {
    Write-Output -InputObject ('{0} was not found :( exiting' -f $targetFolder)
  }
}

8 Comments

Thanks for posting this! Everything works except for the desktop
Cannot convert the "\Desktop\" value of type "System.String" to type "System.Management.Automation.SwitchParameter". At C:\Users\swmur\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:116 char:7 + $desktop = '\Desktop\' + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : ConvertToFinalInvalidCastException
Write-Output : Missing an argument for parameter 'InputObject'. Specify a parameter of type 'System.Management.Automation.PSObject[]' and try again. At C:\Users\swmur\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:121 char:20 + Write-Output -InputObject + ~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Write-Output], ParameterBindingException + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.WriteOutputCommand
Test-Path : Cannot bind argument to parameter 'Path' because it is null. At C:\Users\swmur\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:130 char:25 + if (Test-Path -Path $targetFolder) { + ~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCom mand
I fixed the desktop - there was an extra ‘\‘ in the path. The other error you’ll have to troubleshoot yourselves. You’ll have to define positions for parameters and where the ‘-path’ would come from.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.