Custom PowerShell Commands

Philip Jonas
2 min readJun 4, 2021

Recently I came across a very interesting problem, Windows and the development environment is not exactly as friendly as Linux and or Mac. With either of these if you have long commands you simply create a bash script, add you command to that, allow excecution permissions and run it like you would a normal terminal command without having to constantly type out the entire command in terminal over and over again.

Windows PowerShell, well this is a different beast all together. Here is an example of a powershell command that you run in Nuget CLI to do a EF migration:

c:\> Add-Migration MigrationName -ProjectName Power.Project -ConfigurationTypeName "Server.Migrations.Configuration" -ConnectionString "Data Source=localhost;Initial Catalog=SystemController;Integrated;" -ConnectionProviderName "System.Data.SqlClient" -StartupProjectName Power.Project

Its amazing is it, would it not be better if we could simply have the following?

c:\> CreateMigration "MyMigrationNameGoesHere"

Its very simple to do and can be done in PowerShell or Nuget Package Manager CLI.

# 1. Open Nuget Command Line PMC (Package Manager Console)
# 2. Check if a profile exits
c:\> Test-path $profile
# 3. If this returns FALSE you will need to create one, run the following command
c:\> New-item -type file -force $profile
# 4. This will create a NuGet Powershell profile file for you at:
C:\Users\youruser\Documents\WindowsPowerShell\NuGet_profile.ps1
# 5. Next we need to set the execution policies: Run the following command and chose Y
c:\> Set-ExecutionPolicy RemoteSigned
# 6. This will give your machine permission to execute your own powershell scripts. Edit the profile in your editor of choice, to use notepad run the following command notepad $profile

Now add the following code to the file, you can add your own functions to this if you need to.
C:\Users\youruser\Documents\WindowsPowerShell\NuGet_profile.ps1

Function CreateMigration ($migrationName)
{
Add-Migration $migrationName -ProjectName Power.Project -ConfigurationTypeName "Server.Migrations.Configuration" -ConnectionString "Data Source=localhost;Initial Catalog=SystemController;Integrated;" -ConnectionProviderName "System.Data.SqlClient" -StartupProjectName Power.Project
}

Once you are done you can close PowerShell or NPM (Nuget package manager) and when you open it again you will have your own PowerShell commands.

As for the example above this indicates how you would pass arguments into the method.

--

--