Skip to content

Instantly share code, notes, and snippets.

@MyITGuy
Created October 6, 2020 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MyITGuy/114ab479eecbc6bff116a2c792b84049 to your computer and use it in GitHub Desktop.
Save MyITGuy/114ab479eecbc6bff116a2c792b84049 to your computer and use it in GitHub Desktop.
Get-DefaultMediaCost / Set-DefaultMediaCost to assist in managing metered connections in Windows 10. (requires a reboot after modification)
#region Get-DefaultMediaCost
function Get-DefaultMediaCost {
[CmdletBinding()]
PARAM(
)
DynamicParam {
# Set the dynamic parameters' name. You probably want to change this.
$DynamicParam_MediaType = 'MediaType'
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes. You may also want to change these.
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 0
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
# Generate and set the ValidateSet. You definitely want to change this. This part populates your set.
$arrSet = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost" | Get-Member | Where-Object { $_.MemberType -eq 'NoteProperty' -and $_.Definition -match '^int' } | Select-Object -ExpandProperty Name | Sort-Object
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($DynamicParam_MediaType, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($DynamicParam_MediaType, $RuntimeParameter)
return $RuntimeParameterDictionary
}
begin {
# Bind the parameter to a friendly variable
$MediaType = $PsBoundParameters[$DynamicParam_MediaType]
}
process {
try {
$RegistryKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost"
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($RegistryKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::Default, [System.Security.AccessControl.RegistryRights]::ReadKey)
$DefaultMediaCost = $key.GetValue($MediaType)
$key.Close()
$DefaultMediaCost
}
catch {
throw $_
}
}
end {
}
}
#endregion Get-DefaultMediaCost
#region Set-DefaultMediaCost
function Set-DefaultMediaCost {
[CmdletBinding()]
PARAM(
[Parameter(Mandatory = $true, Position = 1)]
# NetworkCostType Enum, https://docs.microsoft.com/en-us/uwp/api/windows.networking.connectivity.networkcosttype?view=winrt-19041
[ValidateSet('Unknown', 'Unrestricted', 'Fixed', 'Variable')]
[string]
$NetworkCostType
)
DynamicParam {
# Set the dynamic parameters' name. You probably want to change this.
$DynamicParam_MediaType = 'MediaType'
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes. You may also want to change these.
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 0
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
# Generate and set the ValidateSet. You definitely want to change this. This part populates your set.
$arrSet = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost" | Get-Member | Where-Object { $_.MemberType -eq 'NoteProperty' -and $_.Definition -match '^int' } | Select-Object -ExpandProperty Name | Sort-Object
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($DynamicParam_MediaType, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($DynamicParam_MediaType, $RuntimeParameter)
return $RuntimeParameterDictionary
}
begin {
# Bind the parameter to a friendly variable
$MediaType = $PsBoundParameters[$DynamicParam_MediaType]
#region Get-NetworkCostFromType
function Get-NetworkCostFromType {
param (
[string]
$NetworkCostType
)
switch ($NetworkCostType) {
'Unrestricted' {
1
break
}
'Fixed' {
2
break
}
'Variable' {
3
break
}
default {
0
}
}
}
#endregion Get-NetworkCostFromType
#region Enable-Privilege
function Enable-Privilege {
param(
## The privilege to adjust. This set is taken from
## http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx
[ValidateSet(
"SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
"SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
"SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
"SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
"SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
"SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
"SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
"SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
"SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
"SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
"SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
$Privilege,
## The process on which to adjust the privilege. Defaults to the current process.
$ProcessId = $pid,
## Switch to disable the privilege, rather than enable it.
[Switch] $Disable
)
## Taken from P/Invoke.NET with minor adjustments.
$definition = @'
using System;
using System.Runtime.InteropServices;
public class AdjPriv
{
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
{
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = new IntPtr(processHandle);
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
if(disable)
{
tp.Attr = SE_PRIVILEGE_DISABLED;
}
else
{
tp.Attr = SE_PRIVILEGE_ENABLED;
}
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
}
'@
$processHandle = (Get-Process -id $ProcessId).Handle
$type = Add-Type $definition -PassThru
$type[0]::EnablePrivilege($processHandle, $Privilege, $Disable)
}
#endregion Enable-Privilege
}
process {
#Check for Admin rights
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "$($MyInvocation.MyCommand) cannot be run because the current Windows PowerShell session is not running as an administrator. Start Windows PowerShell as an administrator and then try running the function again."
return
}
try {
$NetworkCost = Get-NetworkCostFromType -NetworkCostType $NetworkCostType
$RegistryKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost"
$DefaultMediaCost = Get-DefaultMediaCost -MediaType $MediaType
if ($DefaultMediaCost -eq $NetworkCost) {
Write-Verbose "Change unnecessary."
return
}
# Add SeTakeOwnershipPrivilege for this process
Enable-Privilege -Privilege SeTakeOwnershipPrivilege | Out-Null
# Add SeRestorePrivilege for this process
Enable-Privilege -Privilege SeRestorePrivilege | Out-Null
$AdministratorsNTAccount = [System.Security.Principal.NTAccount]"Administrators"
$AdmistratorsFullControlRegistryAccessRule = New-Object System.Security.AccessControl.RegistryAccessRule ($AdministratorsNTAccount, [System.Security.AccessControl.RegistryRights]::FullControl, @("ObjectInherit", "ContainerInherit"), "None", "Allow")
$AdmistratorsReadRegistryAccessRule = New-Object System.Security.AccessControl.RegistryAccessRule ($AdministratorsNTAccount, [System.Security.AccessControl.RegistryRights]::ReadKey, @("ObjectInherit", "ContainerInherit"), "None", "Allow")
$TrustedInstallerNTAccount = [System.Security.Principal.NTAccount]"NT Service\TrustedInstaller"
# $TrustedInstallerFullControlRegistryAccessRule = New-Object System.Security.AccessControl.RegistryAccessRule ($TrustedInstallerNTAccount, [System.Security.AccessControl.RegistryRights]::FullControl, @("ObjectInherit", "ContainerInherit"), "None", "Allow")
#region Change registry key ownership to Administrators
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($RegistryKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership)
# You must get a blank acl for the key b/c you do not currently have access
$acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
$acl.SetOwner($AdministratorsNTAccount)
$key.SetAccessControl($acl)
$key.Close()
#endregion
#region Add Administrators Full Control
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($RegistryKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership)
$acl = $key.GetAccessControl()
# Give Administrators full control to keys and subkeys
$acl.SetAccessRule($AdmistratorsFullControlRegistryAccessRule)
$key.SetAccessControl($acl)
$key.Close()
#endregion
#region Make the change
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($RegistryKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::FullControl)
$key.SetValue($MediaType, $NetworkCost, [Microsoft.Win32.RegistryValueKind]::DWord)
$key.Close()
#endregion
$DefaultMediaCost = Get-DefaultMediaCost -MediaType $MediaType
if ($DefaultMediaCost -eq $NetworkCost) {
Write-Verbose "Change success."
} else {
Write-Verbose "Change failure."
}
}
catch {
throw $_
}
}
end {
try {
if ($AdministratorsNTAccount) {
#region Remove Administrators Full Control
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($RegistryKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership)
$acl = $key.GetAccessControl()
$acl.RemoveAccessRuleAll($AdmistratorsFullControlRegistryAccessRule)
$acl.SetAccessRule($AdmistratorsReadRegistryAccessRule)
# $acl.SetAccessRule($TrustedInstallerFullControlRegistryAccessRule)
$key.SetAccessControl($acl)
$key.Close()
#endregion
}
if ($TrustedInstallerNTAccount) {
#region Change registry key ownership to TrustedInstaller.
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey($RegistryKey, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [System.Security.AccessControl.RegistryRights]::TakeOwnership)
# You must get a blank acl for the key b/c you do not currently have access
$acl = $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None)
$acl.SetOwner($TrustedInstallerNTAccount)
$key.SetAccessControl($acl)
$key.Close()
#endregion
}
}
catch {
throw $_
}
}
}
#endregion Set-DefaultMediaCost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment