Skip to content

Instantly share code, notes, and snippets.

@Thecarisma
Last active December 14, 2023 20:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thecarisma/518b1bcc80a08191b8fd5a4e88ad9f21 to your computer and use it in GitHub Desktop.
Save Thecarisma/518b1bcc80a08191b8fd5a4e88ad9f21 to your computer and use it in GitHub Desktop.
Powershell - Shebang, Hebang and Webang Command + Subshell
Param(
# the commands to execute or the file to execute
[Parameter(Mandatory=$false, ValueFromRemainingArguments = $true)]
[string[]]$Commands
)
Function Main {
If ($Commands) {
Evalute-Line $Commands
} Else {
Enter-Shell
}
Exit $LastExitCode
}
Function Enter-Shell {
while ($true) {
$Commands = Read-Host "$"
Evalute-Line $Commands
}
}
Function Evalute-Line {
Param(
[string]$LineArgs
)
$FirstCommand = ""
$OtherCommands = ""
ForEach ($Command in $Commands) {
If (-not $FirstCommand) {
$FirstCommand = $Command
If ($FirstCommand -eq "exit()" -or $FirstCommand -eq "exit" -or $FirstCommand -eq "close") {
exit
}
} else {
if ($Command.Contains(" ")) {
$OtherCommands += "'$Command' "
} else {
$OtherCommands += "$Command "
}
}
}
$Old_CD = [Environment]::CurrentDirectory
[Environment]::CurrentDirectory = Get-Location
$FirstCommand = Resolve-Shebang $FirstCommand
[Environment]::CurrentDirectory = $Old_CD
iex "$FirstCommand $OtherCommands"
}
Function Resolve-Shebang {
Param(
[string]$FirstCommand_
)
If ([System.IO.File]::Exists($FirstCommand_)) {
foreach($Line in Get-Content $FirstCommand_) {
If($Line.StartsWith("#!")){ # Shebang
$Shebang = $Line.SubString(2, $Line.Length - 2)
$Bangs = $Shebang.Split(" ")
$Shebang = ""
ForEach ($Bang in $Bangs) {
If ($Bang.StartsWith('/') -and ($Bang.EndsWith('/env') -or $Bang.EndsWith('/bin'))) {
} Else {
$Shebang += "$Bang "
}
}
$Shebang = $Shebang -f [System.IO.Path]::GetFullPath($FirstCommand_)
return $Shebang
} ElseIf ($Line.StartsWith("//!")){ # Hebang
$Hebang = $Line.SubString(3, $Line.Length - 3)
$Bangs = $Hebang.Split(" ")
$Hebang = ""
ForEach ($Bang in $Bangs) {
If ($Bang.StartsWith('/') -and ($Bang.EndsWith('/env') -or $Bang.EndsWith('/bin'))) {
} Else {
$Hebang += "$Bang "
}
}
$Hebang = $Hebang -f [System.IO.Path]::GetFullPath($FirstCommand_)
return $Hebang
} ElseIf ($Line.StartsWith("/*!")){ # Webang
$Webang = $Line.SubString(3, $Line.Length - 3)
$Bangs = $Webang.Split(" ")
$Webang = ""
ForEach ($Bang in $Bangs) {
if ($Bang.Contains("`*`/")) {
$BangEndIndex = $Bang.LastIndexOf("`*`/")
$Bang = $Bang.SubString(0, $BangEndIndex)
}
If ($Bang.StartsWith('/') -and ($Bang.EndsWith('/env') -or $Bang.EndsWith('/bin'))) {
} Else {
$Webang += "$Bang "
}
}
$Webang = $Webang -f [System.IO.Path]::GetFullPath($FirstCommand_)
return $Webang
}
return $FirstCommand_
}
}
return $FirstCommand_
}
Main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment