One powershell profile on multiple machines

den 1 juni 2017 av Dennie

It’s not that unusual to have one computer for work and one for private coding, but changing one thing on one machine and then have to repeat that step on another ain't going to happen. And in particular, some of the paths on the different machines differ which makes the problem a bit more fun to deal with. The solution for this was to create a file that holds the machine specific paths for the different machines and this minified example just adds a ssh key when I start powershell.

For version control I’ve tried both git and dropbox and I prefer the later one much because I don't need to do a fetch to get my files updated.
And for the paths I use json format to store computer-bound preferences which is really easy to manage in Powershell.
We begin with the json file containing the various computers' settings (Home, Work1 and Work2 represents the different computer names)

{
  "Home": {
    	"profile" : {
        	"filename" : "Microsoft.PowerShell_profile.ps1"
        },
        "paths":
        [
	        {
	        	"name" : "home",
	        	"path" : "c:\\users\\johndoe"
			},
			{
	        	"name" : "projects",
	        	"path" : "d:\\projects"
			}
        ]
    },
    "Work1": {
    	"profile" : {
        	"filename" : "Profile.ps1"
        },
        "paths":
        [
        	{
	        	"name" : "home",
	        	"path" : "c:\\users\\john.doe"
			},
			{
	        	"name" : "projects",
	        	"path" : "c:\\projects"
			}
        ]
    },
    "Work2": {
    	"profile" : {
        	"filename" : "Profile.ps1"
        },
        "paths":
        [
        	{
	        	"name" : "home",
	        	"path" : "c:\\users\\jode"
			},
			{
	        	"name" : "projects",
	        	"path" : "c:\\users\\some-other-user\\projects"
			}
        ]
    }
}

At the top in the profile file, we read the correct json-node in the settings simply with the existing variable env:computername

$allSettings = (Get-Content "$scriptPath\settings.json" -Raw) | ConvertFrom-Json
$settings = $allSettings.$(Get-Content env:computername)

And two simple functions to get properties and the path values: 

function Get-Path($name){
    return ($settings.paths | where name -Like "$name").path
}

And a simple example of how to get the home-path in our profile to add a ssh profile:

function SshInit {
    $sshHome = Get-Path 'home'
    Start-SshAgent -Quiet
    ssh-add "$sshHome\.ssh\id_rsa"
}