Reputation: 96
what I'm trying to do is setting up aliases to run Windows Terminal from file browser in the current directory, as admin or regular user. I'm not very familiar with powershell scripts and I'm trying to understand why my functions are called when the script is loaded instead of when the alias is called, which in turn runs terminals indefinitely..
Here is the script I wrote in $Profile
:
$wtHere = "wt -d ."
function Run-Command{
param($Command)
Invoke-Expression $Command
}
function Run-As-Administrator{
param($Command)
Run-Command -Command "runas /user:administrator $Command"
}
set-alias -Name wtha -Value $(Run-As-Administrator -Command $wtHere)
set-alias -Name wth -Value $(Run-Command -Command $wtHere)
Upvotes: 1
Views: 229
Reputation: 60110
Quoting this excellent answer which explains really well what you're doing wrong:
PowerShell aliases do not allow for arguments.
They can only refer to a command name, which can be the name of a cmdlet or a function, or the name / path of a script or executable
The
Set-Alias
cmdlet creates or changes an alias for a cmdlet or a command, such as a function, script, file, or other executable. An alias is an alternate name that refers to a cmdlet or command.
This should help you understand what is going:
$wtHere = "Hello world"
function Run-Command {
param($Command)
"$Command - Received on {0}" -f $MyInvocation.MyCommand.Name
}
function Run-As-Admin {
param($Command)
Run-Command ("From {0} - Command: $Command" -f $MyInvocation.MyCommand.Name)
}
Set-Alias -Name wtha -Value $(Run-As-Admin -Command $wtHere)
Set-Alias -Name wth -Value $(Run-Command -Command $wtHere)
Get-Alias wth, wtha | Select-Object Name, Definition
You're storing the "result" of your functions and not the functions definitions into your aliases. You can't store an expression such as Run-As-Admin -Command $wtHere
as the Value of your Alias, it will be stored as literal, even if you run the alias you would see that PowerShell will run the result of your expression and fail:
wth: The term 'Hello world - Received on Run-Command' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
What you should do is as simple as:
Set-Alias -Name wtha -Value Run-As-Admin
Set-Alias -Name wth -Value Run-Command
Then you can interactively run:
PS /> wtha $wtHere
Upvotes: 1