Using Safe Cmdlets Only

by Mar 14, 2013

Let's assume you want to set up a restricted PowerShell v3 console that just provides access to Microsoft cmdlets with the verb Get. One way to do this is to create a custom module that publishes the cmdlets you want to keep, then to remove all other modules:

$PSModuleAutoLoadingPreference = 'none'
Get-Module | Remove-Module
New-Module -Name SafeSubSet { 
   Get-Module Microsoft* -ListAvailable  | Import-Module
   Export-ModuleMember -Cmdlet Get-*, Import-Module
} | Import-Module

This isn't enough, though, because the PowerShell core snap-in is still there and cannot be removed. It provides cmdlets like Import-Module, so a user could go ahead and re-import modules. That's why you should mark all unwanted core cmdlets as "private", effectively hiding them:

Get-Command -Noun Module*,Job,PSSnapin,PSSessionConfiguration*,PSRemoting | ForEach-Object { $_.Visibility = 'Private' }
Get-Command -Verb New | ForEach-Object { $_.Visibility = 'Private' }

Twitter This Tip! ReTweet this Tip!