How to create a Powershell Alias for Set-Executionpolicy - powershell

Following guides to create an alias in powershell, I have run the following command:
Set-Alias rush-enable "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass"
This sets the alias. However when I run the alias I hit an error.
PS C:\example> rush-enable
rush-enable : The term 'Set-ExecutionPolicy -Scope Process
-ExecutionPolicy Unrestricted' is not recognized as the name of
a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that
the path is correct and try again.
At line:1 char:1
+ rush-enable
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Set-ExecutionPo.
..cy Unrestricted:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
However running the command on it's own works fine:
PS C:\example> Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted
PS C:\example>
Am I missing something? How should I format the command to work as an alias?

As per the documentation:
You can assign an alias to a cmdlet, script, function, or executable
file.
You cannot assign an alias to a command and its parameters. For
example, you can assign an alias to the Get-Eventlog cmdlet, but you
cannot assign an alias to the Get-Eventlog -LogName System command.
This is presumably a way to avoid having to disambiguate a parameter that exists on an alias and which is passed when invoking the alias.
You therefore have two options:
Encapsulate your command in a function called Enable-Rush (note the PowerShell acceptable naming scheme, if you care). In your case this would look something like:
function Enable-Rush {
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
}
Save the command as a file and create a alias to the file.
And to persist it, put it in a $PROFILE. Depending on your system, you might need to digitally sign the $PROFILE or change the PowerShell system Execution Policy to allow PowerShell scripts generated by the system to execute when starting a PowerShell process.

Related

Windows Terminal doesn't recognize a script function

I've recently discovered the Windows Terminal and wanted to give it a try. However, it doesn't seem to work the same as the original PowerShell Console. When I try to call a script function in it like . .\Func-Test.ps1; My-Func -test abc it says:
My-Func : The term 'My-Func' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is
correct and try again. At line:1 char:15
. .\Func-Test; My-Func -test abc
~~~~~~~~
CategoryInfo : ObjectNotFound: (My-Func:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
Doing the same in the classic PowerShell Console works without any issues. Both consoles use the same $PSVersionTable.PSVersion which is 5.1.19041.1682.
Am I using the Windows Terminal incorrectly or isn't this supposed to work in it (yet)?
I fixed it by executing as Administrator this command in the Windows Terminal. Strangely the PowerShell Console already showed RemoteSigned. Apparently they use different environments.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine

Unable to set alias in PowerShell using a string

I tried to set an alias in PowerShell by running Set-Alias -Name artisan -Value 'php aritsan', though the command ran successfully but when I call the alias the following error occurs :
artisan : The term 'php aritsan' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
+ artisan
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (php aritsan:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
What's the correct way to go for?
P.S: artisan is a file in the current directory. The file is packaged with laravel framework
This will help you create an alias for "php artisan" in Windows PowerShell Globally.
Just follow these steps and its done.
First of all search powershell using win+S and run it as administrator and then paste this code and hit Enter.
if (!(Test-Path -Path $PROFILE )) {New-Item -Type File -Path $PROFILE -Force }
Then run this command.
notepad $profile
A notepad file will open. Paste this code in notepad file and hit ctrl+S
Function CD32($arg1,$arg2,$arg3,$arg4,$arg5) {php artisan $arg1 $arg2 $arg3 $arg4 $arg5}
Set-Alias -Name pa -Value CD32
And then finally paste this command on your powershell and hit enter.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
And it's done. Now you can use "pa" as an alias for "php artisan" globally in your windows powershell.
Here I am using "pa" on my VS Code PowerShell.
All the details are described in:
Get-Help alias -ShowWindow shows all available help for alias
Get-Help Set-Alias show specific help for Set-Alias
An alias is an alternate name or nickname for a cmdlet or for a command
element, such as a function, script, file, or executable file. You
can use the alias instead of the command name in any Windows PowerShell
commands.
You can assign an alias to a cmdlet, script, function, or executable file.
However, you cannot assign an alias to a command and its parameters.
For example, you can assign an alias to the Get-Eventlog cmdlet, but you
cannot assign an alias to the "Get-Eventlog -LogName System" command.
However, you can create a function that includes the command. To create a
function, type the word "function" followed by a name for the function.
Type the command, and enclose it in braces ({}).
For example, the following command creates the syslog function. This
function represents the "Get-Eventlog -LogName System" command:
function syslog {Get-Eventlog -LogName System}
You can now type "syslog" instead of the command. And, you can create
aliases for the syslog function.
For more information about functions, type:
Get-Help about_Functions

Powershell script cannot recognize absolute file path

I have a windows command script that needs to run another powershell script in another location. The windows command script contains the following code:
powershell -NoProfile -Command "Set-ExecutionPolicy Bypass -Scope Process -Force; & "C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1" -Update"
When I run the windows command script, it always show the following error:
& : The term 'C:\Users\Tommy' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:53
I have tried adding dot to the front of the absolute file path and it did not work.
Try updating "C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1" to 'C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1'. You are ending your quotes early by using the double quotes again.
powershell -NoProfile -Command "Set-ExecutionPolicy Bypass -Scope Process -Force; & 'C:\Users\Tommy\AppData\bootstrap\bootstrap.ps1' -Update"

Set the font type and size using the command prompt (or batch file)

I tried the solution given from: Specify the size of command prompt when executing a batch file
I ran:
powershell -command "&{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But I get these errors, any ideas?
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. At line:1 char:22 + &{set-executionpolicy <<<< remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
Import-Module : The specified module 'SetConsoleFont' was not loaded because no valid module file was found in any module directory . At line:1 char:50 + &{set-executionpolicy remotesigned; Import-Module <<<< SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : ResourceUnavailable: (SetConsoleFont:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
The term 'Get-ConsoleFontInfo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spe lling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:86 + &{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo <<<< | Format-Table -AutoSize} + CategoryInfo : ObjectNotFound: (Get-ConsoleFontInfo:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
I have put the file SetConsoleFont.psm1 in
C:\Users\Adrian\Documents\WindowsPowerShell\Modules\SetConsoleFont
You say "You're not allowed to set the execution policy" well maybe I'm not, but it's my machine so why shouldn't I? I don't want to execute these commands as Administrator, just as a user, me (Adrian)
Another comment was to try set-executionpolicy bypass process
so I tried:
powershell -command "&{set-executionpolicy bypass process; set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But got even more red errors.
I have no idea what powershell is or how to use it, I just want to change the font from a batch file without hassle!
Try set-executionpolicy bypass process instead.
Also make sure you have put the module in a module path folder such as:
[yourprofile]\Documents\WindowsPowershell\Modules
I managed to get it working but only in a PowerShell console, and I had to run it as Administrator. However this is not practical for me for the following reasons:
I wish to change the font of new window seamlessly from a batch file, which will be run by users of the software. They may not have Administrator access and so cannot execute "set-executionpolicy remotesigned" which I needed to do to get it working.
Also this has to be done in a DOS batch file, so opening up a powershell window is not an option. It only works in a PowerShell window and not with the DOS "powershell -command" option.
So a partial answer.
If you want to change Execution Policy, it should be done in an elevated prompt.
And loading the module can be done by giving absolute path. Example is below.
Import-Module c:\users\testuser\desktop\SetConsoleFont.psm1 -Verbose
and we can bypass execution policy like below.
powershell.exe -executionpolicy bypass -command "${<your code>}"
Edit: The imported module will be available only in the scope of the script block.
here it is with in {}. So whatever cmdlets and functions in side the module should be executed in sided the scriptblock.
Regards,
Kvprasoon

How to pass path with spaces to script

I am trying to use PowerShell to call an EXE that is at a location/path containing spaces. When I call the script from the command line, the EXE's full path is not being passed to the script. Any ideas as to why this is happening?
PowerShell Script Contents (Untitled1.ps1)
Here is the entire script that gets called from the command line:
param(
[string] $ParamExePath
)
function Run-CallThisExe {
param(
[string] $ThisExePath
)
Write-Host "ThisExePath: " "$ThisExePath"
start-process -FilePath $ThisExePath
}
write-host "ParamExePath: " $ParamExePath
Run-CallThisExe -ThisExePath "$ParamExePath"
Command Line String
Here is the command line string being run from the PowerShell script's parent folder:
powershell -command .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"
Output
Here is what is output after running the script
ParamExePath: C:\path
ThisExePath: C:\path
start-process : This command cannot be run due to the error: The system cannot
find the file specified.
At C:\sample\Untitled1.ps1:11 char:5
+ start-process -FilePath $ThisExePath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Just change this:
powershell -command .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"
To This:
powershell -file .\Untitled1.ps1 -NonInteractive -ParamExePath "C:\path with spaces\myapp.exe"
The -Command Parameter used to execute commands for example {Get-Date}
The -File Parameter used to Run .ps1 Script File
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
Type Powershell /? to get full details on each Parameter
A couple of other ways to call it:
powershell -command .\Untitled1.ps1 -NonInteractive "-ParamExePath 'C:\path with spaces\myapp.exe'"
powershell -command ".\Untitled1.ps1 -ParamExePath 'C:\path with spaces\myapp.exe'" -NonInteractive
Note that if you pass a folder path to Powershell that has a trailing backslash it cannot handle it. e.g. -ParamFolder "C:\project folder\app\bin debug\". The parameter string ends up with a double quote at the end. So when you try to append the name of a file to it you end up with something like C:\project folder\app\bin debug"Filename.txt. In this case you have to send in a second backslash at the end.