Powershell people: please review a bash -> pwsh translation

Hi folks.

This bash script

#!/bin/sh
exercise=${PWD##*/}
tests="${exercise}-test.lisp"

if ! [ -f "${tests}" ]; then
    echo "Test file not found: $tests" >&2
    exit 2
fi

ros run \
    --load "${tests}" \
    --eval "(uiop:quit (if (${exercise}-test:run-tests) 0 1))"

(ros is a Common Lisp utility application)

into this powershell

#! powershell

$exercise = get-location | split-path -leaf
$tests = $exercise + "-test.lisp"

if (-not (test-path -path $tests)) {
    write-error "Test file not found: $tests"
} else {
    ros run --load $tests --eval "(uiop:quit (if (${exercise}-test:run-tests) 0 1))"
}

Does it look OK?

(@ihid, please create a subcategory for Powershell when it’s convenient)

While I know that space after #! is (generally, and historically) allowed, I prefer it without, while for the track it should at least be consistent. Currently, there is one place where this exists, and it is without the space.

Does windows even use the shebang?

I do not know for sure, but powershell is not just for Windows any more.

Script looks good. There is no need for shebang.
There might be a good chance you want to use $PSScriptRoot instead of Get-Location in many cases.
The first one will give you the location in your current PS session, but the second is more precise. It will give you the exact directory where the current executing script is located.

For example in my repo for PS in vscode, I have this path structure:

C:\User\Name\Docs\GitHub\Powershell\exercise\practice\specific-exercise\myfile.ps1

If i call get-location inside this myfile.ps1, it would give me

C:\User\Name\Docs\GitHub\Powershell

Because this is where the session start, the super grandparent folder.
But if I use $PSScriptRoot, it would give me

C:\User\Name\Docs\GitHub\Powershell\exercise\practice\specific-exercise\

This is the exact folder that my file is located in atm, which is better if I want the path to nearby files in the same folder.

Also please and thank you in advance @iHiD for the PowerShell category, we are nearly hit the 100 exercises mark.

Erik has a script for this that he’ll run when he’s next in (Wedneday) :slight_smile:

Great tip, thanks:

$exercise = split-path -path $PSScriptRoot -leaf

See PowerShell - Exercism

2 Likes