Automatically convert a PowerShell command to use splatting
You have a lengthy multi-parameter PowerShell command that you'd like to convert to use splatting. For example, you want to convert the following command for creating a virtual machine in Azure to use splatting instead of inline parameters.
1New-AzVm -ResourceGroupName myResourceGroup -Name myVM -Location southcentralus -Image Win2022AzureEditionCore -Size Standard_DS2_v2 -VirtualNetworkName myVnet -SubnetName mySubnet -SecurityGroupName myNetworkSecurityGroup -PublicIpAddressName myPublicIpAddress
Prerequisites
- PowerShell
- Visual Studio Code (VS Code)
- PowerShell extension for VS Code
- EditorServicesCommandSuite PowerShell module
Install the EditorServicesCommandSuite module from the PowerShell Gallery.
1Install-Module -Name EditorServicesCommandSuite -AllowPrerelease
Run Import-CommandSuite
in your PowerShell Extension integrated terminal session of VS Code.
Optional: Add the following commands to your PowerShell profile for VS Code to automatically run
Import-CommandSuite
every time you start a new PowerShell session in VS Code.
Import-CommandSuite
imports the EditorServicesCommandSuite module for use in VS Code. The second
command runs my standard PowerShell profile by dot-sourcing it.
1# Import the EditorServicesCommandSuite module for use in VS Code
2Import-CommandSuite
3
4# Load your standard profile
5. $HOME/Documents/PowerShell/Microsoft.PowerShell_profile.ps1
I've placed them in my PowerShell CurrentUserCurrentHost profile for VS Code.
Convert to splatting
-
In VS Code, place your cursor somewhere within the command you want to convert to use splatting.
-
Press Ctrl+Shift+P (or F1) to open the command palette in VS Code.
-
Select PowerShell: Show Additional Commands from PowerShell Modules.
-
Then, choose Splat Command.
As shown in the following example, you successfully converted the command shown earlier in this article to use splatting.
1$newAzVmSplat = @{
2 ResourceGroupName = 'myResourceGroup'
3 Name = 'myVM'
4 Location = 'southcentralus'
5 Image = 'Win2022AzureEditionCore'
6 Size = 'Standard_DS2_v2'
7 VirtualNetworkName = 'myVnet'
8 SubnetName = 'mySubnet'
9 SecurityGroupName = 'myNetworkSecurityGroup'
10 PublicIpAddressName = 'myPublicIpAddress'
11}
12
13New-AzVm @newAzVmSplat
Thanks to Patrick Meinecke for creating the EditorServicesCommandSuite PowerShell module and Sean Wheeler for his thoughts and insights about using the module.
One tip Sean shared is that if you have multiple commands piped together, the command where you place the cursor is the one that's converted to use splatting.
Summary
In this article, you learned how to automatically convert lengthy multi-parameter PowerShell commands to splatting using the EditorServicesCommandSuite PowerShell module in VS Code.