#---------------------------------------------------------------- # Dirname.ps1 #---------------------------------------------------------------- param ( [string]$name = $null ); $script:SEPARATOR = "\"; #---------------------------------------------------------------- # function Do-Dirname #---------------------------------------------------------------- function Do-Dirname() { param ( [string]$name = $null ); $dirname = "."; if ( $name ) { if ( $name -ne $script:SEPARATOR ) { $start_index = $name.Length-1; # for paths like \foo\bar\, bypass the trailing separator if ( ($name.Length -gt 1) -and $name.EndsWith($script:SEPARATOR) ) { $start_index--; } # Reverse Iterate through the string until we find a path separator for($dirlen=$start_index; $dirlen -ge 0; $dirlen--) { if ( $name[$dirlen] -eq $script:SEPARATOR ) { break; } } if ( $dirlen -eq -1 ) { # No path separators found, default to the current directory $dirname = "." } else { $dirname = $name.Substring(0, $dirlen); #sanity checks if ( $dirname.Length -eq 0 ) { $dirname = $script:SEPARATOR; } if ( $dirname -like "[a-zA-Z]:" ) { $dirname += $script:SEPARATOR; } } } } $dirname; } #---------------------------------------------------------------- # function Do-DirnameUnitTests #---------------------------------------------------------------- function Do-DirnameUnitTests() { $tests = @( @("foo", "."), @("foo\", "."), @("", "."), @("\foo", "\"), @("\foo\", "\"), @("\foo\bar", "\foo"), @("\foo\bar\", "\foo"), @("c:\foo", "c:\"), @("c:\foo\bar", "c:\foo"), @("c:\foo\bar\", "c:\foo") ); $success = "PASS"; " {0,-15} {1,-15} {2,-15} {3}" -f ("Test", "Expected", "Found", "Pass"); foreach ($test in $tests) { $result = Do-Dirname $test[0]; $status = $result -eq $test[1]; "(""{0,-15}"" -> ""{1,-15}"") -> ""{2,-15}"" : {3}" -f ($test[0], $test[1], $result, $status); #Write-Host "TEST: (""$($test[0])"" -> ""$($test[1])"") -> ""$result"" : $status"; if ( ! $status ) { $success = "FAIL"; } } "" "RESULT: $success"; } Do-Dirname -name $name;