Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

Mastering Removable Storage Permissions: A PowerShell Guide

Key takeaways

  • Automates device permissions: The script streamlines the process of setting permissions on removable storage devices.
  • Supports multiple devices: It covers a range of devices including USB, DVD, Floppy, Tape, and WPD.
  • Requires admin rights: Running the script necessitates Administrator privileges.
  • Modifies registry settings: It adjusts permissions by altering specific registry keys and values.
  • Ensures compliance and security: Ideal for environments where data security and regulatory compliance are crucial.
  • Flexible control: Offers the ability to both deny and allow read, write, and execute actions.
  • Group policy update and reboot: Concludes with a group policy update and optional system reboot.
  • Risk of over-restriction: There’s a potential to hinder workflows if overly restrictive policies are applied.
  • NinjaOne integration: Complements platforms like NinjaOne for broader IT management and security.

Managing access to removable storage devices is a critical aspect of IT security. This responsibility is especially pronounced in environments where data security and integrity are paramount. PowerShell scripts, like the one we’re exploring today, provide a robust solution for controlling these permissions efficiently.

Background

The script in question is designed to enable or disable read, write, and execute access to various removable storage devices including floppy drives, CD/DVD drives, tape drives, Windows Portable Devices (WPD), and USB drives. This functionality is essential for IT professionals and Managed Service Providers (MSPs) who need to enforce data security policies, prevent data leaks, or comply with regulatory standards.

The script:

#Requires -Version 2.0

<#
.SYNOPSIS
    Disable or Enable Write, Read, and Execute access to Removable Storage devices.
.DESCRIPTION
    Disable or Enable Write, Read, and Execute access to Floppy, CD/DVD, Tape, WPD, and/or USB.
    Disable actions are does first, then allow actions are done after.
.EXAMPLE
     -Device DVD -DenyRead -DenyWrite -DenyExecute
    Disable Write, Read, and Execute access to CD/DVD drive.
.EXAMPLE
     -Device DVD -AllowRead -AllowWrite -AllowExecute
    Allow Write, Read, and Execute access to CD/DVD drive.
.EXAMPLE
     -Device DVD -DenyWrite -DenyExecute -AllowRead
    Disable Write, Read, and Execute access to CD/DVD drive, but Allow Read.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2012
    Local Group Policy updates like this requires the computer to rebooted.
    Release Notes: Renamed script and added Script Variable support
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    DataIOSecurity
#>

[CmdletBinding()]
param (
    # Supported devices Floppy, DVD, Tape, WPD, USB
    [String[]]
    $Device,
    [switch]
    $DenyRead = [System.Convert]::ToBoolean($env:DenyRead),
    [switch]
    $DenyWrite = [System.Convert]::ToBoolean($env:DenyWrite),
    [switch]
    $DenyExecute = [System.Convert]::ToBoolean($env:DenyExecute),
    [switch]
    $AllowRead = [System.Convert]::ToBoolean($env:AllowRead),
    [switch]
    $AllowWrite = [System.Convert]::ToBoolean($env:AllowWrite),
    [switch]
    $AllowExecute = [System.Convert]::ToBoolean($env:AllowExecute),
    [switch]
    $ForceReboot = [System.Convert]::ToBoolean($env:ForceReboot)
)

begin {
    function Test-StringEmpty {
        param([string]$Text)
        # Returns true if string is empty, null, or whitespace
        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }
    }
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
    $RegSettings = @(
        [PSCustomObject]@{
            Name        = "Floppy"
            BasePath    = "HKLM:\Software\Policies\Microsoft\Windows\RemovableStorageDevices\{53f56311-b6bf-11d0-94f2-00a0c91efb8b}"
            DenyExecute = "Deny_Execute"
            DenyWrite   = "Deny_Write"
            DenyRead    = "Deny_Read"
        },
        [PSCustomObject]@{
            Name        = "DVD"
            BasePath    = "HKLM:\Software\Policies\Microsoft\Windows\RemovableStorageDevices\{53f56308-b6bf-11d0-94f2-00a0c91efb8b}"
            DenyExecute = "Deny_Execute"
            DenyWrite   = "Deny_Write"
            DenyRead    = "Deny_Read"
        },
        [PSCustomObject]@{
            Name        = "Tape"
            BasePath    = "HKLM:\Software\Policies\Microsoft\Windows\RemovableStorageDevices\{53f5630b-b6bf-11d0-94f2-00a0c91efb8b}"
            DenyExecute = "Deny_Execute"
            DenyWrite   = "Deny_Write"
            DenyRead    = "Deny_Read"
        },
        [PSCustomObject]@{
            Name      = "WPD"
            BasePath  = "HKLM:\Software\Policies\Microsoft\Windows\RemovableStorageDevices\{6AC27878-A6FA-4155-BA85-F98F491D4F33}"
            DenyWrite = "Deny_Write"
            DenyRead  = "Deny_Read"
        },
        [PSCustomObject]@{
            Name      = "WPD"
            BasePath  = "HKLM:\Software\Policies\Microsoft\Windows\RemovableStorageDevices\{F33FDC04-D1AC-4E8E-9A30-19BBD4B108AE}"
            DenyWrite = "Deny_Write"
            DenyRead  = "Deny_Read"
        },
        [PSCustomObject]@{
            Name        = "USB"
            BasePath    = "HKLM:\Software\Policies\Microsoft\Windows\RemovableStorageDevices\{53f5630d-b6bf-11d0-94f2-00a0c91efb8b}"
            DenyExecute = "Deny_Execute"
            DenyWrite   = "Deny_Write"
            DenyRead    = "Deny_Read"
        }
    )
    $Device = if ($(Test-StringEmpty -Text $env:Device)) { $Device }else { $env:Device }

    if ($(Test-StringEmpty -Text $Device)) {
        Write-Error "Device is required."
        exit 1
    }
    if ((-not $DenyRead -and -not $DenyWrite -and -not $DenyExecute) -and (-not $AllowRead -and -not $AllowWrite -and -not $AllowExecute)) {
        Write-Error "At least one Deny or Allow is required."
        exit 1
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # Split any string that has a comma and validate types of devices
    $Device = $Device | ForEach-Object {
        $_ -split ',' | ForEach-Object {
            "$_".Trim()
        }
    } | Where-Object { $_ -in "Floppy", "DVD", "Tape", "WPD", "USB" }

    try {
        $Device | ForEach-Object {
            $CurDevice = $_
            # Loop through each item in $RegSettings and work on the current device($Device)
            $RegSettings | Where-Object { $_.Name -in $CurDevice } | ForEach-Object {
                $CurRegSetting = $_
                $Path = $CurRegSetting.BasePath

                # Build Deny list
                $Deny = [System.Collections.ArrayList]::new() # Older PowerShell compatible Lists
                if ($DenyRead) { $Deny.Add("Read") | Out-Null }
                if ($DenyWrite) { $Deny.Add("Write") | Out-Null }
                if ($DenyExecute) { $Deny.Add("Execute") | Out-Null }
                # Build Allow list
                $Allow = [System.Collections.ArrayList]::new() # Older PowerShell compatible Lists
                if ($AllowRead) { $Allow.Add("Read") | Out-Null }
                if ($AllowWrite) { $Allow.Add("Write") | Out-Null }
                if ($AllowExecute) { $Allow.Add("Execute") | Out-Null }

                # Loop though each $Deny item passed
                $Deny | ForEach-Object {
                    $CurDeny = $_
                    # Only act on what we have, like WPD where we only have Deny_Write and Deny_Read
                    # $CurRegSetting."Deny$CurDeny" is a method of access a property
                    if ($CurRegSetting."Deny$CurDeny") {
                        $CurDenyType = $CurRegSetting."Deny$CurDeny"
                        # Check if we need to create the path
                        if (-not (Test-Path -Path $Path -ErrorAction SilentlyContinue)) {
                            New-Item -Path ($Path | Split-Path -Parent) -Name ($Path | Split-Path -Leaf) -Force -Confirm:$false | Out-Null
                            Write-Host "Creating path: $($Path)"
                        }
                        # Check if the property already exists and update it or create the property
                        if ((Get-ItemProperty -Path $Path -Name $CurDenyType -ErrorAction SilentlyContinue)."$CurDenyType") {
                            Set-ItemProperty -Path $Path -Name $CurDenyType -Value 1 -Force -Confirm:$false | Out-Null
                            Write-Host "Setting $($Path)/$CurDenyType to 1"
                        }
                        else {
                            New-ItemProperty -Path $Path -Name $CurDenyType -Value 1 -PropertyType "DWORD" -Force -Confirm:$false | Out-Null
                            Write-Host "Creating and Setting $($Path)/$CurDenyType to 1"
                        }
                        Write-Host "Deny $CurDeny for $CurDevice set to $((Get-ItemProperty -Path $Path -Name $CurDenyType -ErrorAction SilentlyContinue)."$CurDenyType")"
                    }
                    else {
                        # Skipping this as we don't have Deny_Execute for WPD
                        Write-Host "Skipping $($CurRegSetting."Deny$CurDeny")"
                    }
                }
                # Loop though each $Allow item passed
                $Allow | ForEach-Object {
                    $CurAllow = $_
                    # Only act on what we have, like WPD where we only have Deny_Write and Deny_Read
                    # $CurRegSetting."Deny$CurAllow" is a method to access a property
                    if ($CurRegSetting."Deny$CurAllow") {
                        $CurAllowType = $CurRegSetting."Deny$CurAllow"
                        # Check if the property already exists and update it or create the property
                        if ((Get-ItemProperty -Path $Path -Name $CurAllowType -ErrorAction SilentlyContinue)."$CurAllowType") {
                            Set-ItemProperty -Path $Path -Name $CurAllowType -Value 0 -Force -Confirm:$false | Out-Null
                            Write-Host "Setting $($Path)/$CurAllowType to 0"
                        }
                        Write-Host "Allow access for $CurDevice"
                    }
                    else {
                        # Skipping this as we don't have Deny_Execute for WPD
                        Write-Host "Skipping $($CurRegSetting."Deny$CurAllow")"
                    }
                }
            }
        }
        

        Write-Host "Running: gpupdate.exe /force"
        gpupdate.exe /force
        Write-Host "Completed Running: gpupdate.exe /force"
        Write-Host "Computer will need to be rebooted for changes to take effect."

        if ($ForceReboot) {
            shutdown.exe -r -t 60
        }
        else {
            Write-Host "Computer will need to be rebooted to see changes."
        }
        exit 0
    }
    catch {
        Write-Error $_
        exit 1
    }
}
end {
    
    
    
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

The script operates in several distinct phases:

  • Parameter definition: It begins by defining parameters for different device types and actions (Deny or Allow for Read, Write, Execute).
  • Pre-execution checks: It includes functions to check for empty strings and verify if the script is run with elevated (Administrator) privileges.
  • Registry setting adjustments: The core functionality revolves around modifying registry settings for each device type. These settings determine the permissions for each action (Read, Write, Execute).
  • Execution logic: The script creates or modifies registry keys and values based on the input parameters. It can set permissions to either deny or allow actions on the specified devices.
  • Final Steps: The script concludes by updating group policies with gpupdate.exe and optionally initiating a system reboot for the changes to take effect.

Potential use cases

Consider a financial firm that must adhere to strict data security regulations. An IT administrator can use this script to disable write access to USB drives on all employee workstations, preventing sensitive data from being copied onto external devices.

Comparisons

Traditional methods of configuring device permissions might involve manual registry edits or group policy configurations. This script automates these processes, reducing the margin for error and saving time.

FAQs

  • Is the script compatible with all Windows versions?
    • It supports Windows 7 and above, including server editions.
  • Can it control access to network drives?
    • No, it’s specifically for removable storage devices.
  • Does the script require administrative rights?
    • Yes, it must be run with Administrator privileges.

Implications

While this script is a powerful tool for enhancing data security, it also carries the risk of restricting access too tightly, potentially hindering legitimate workflows. It’s essential to balance security needs with operational requirements.

Recommendations

  • Test the script in a controlled environment before deploying it broadly.
  • Document all changes made using the script for future reference.
  • Regularly review and update the access policies to align with evolving security needs.

Final thoughts

In today’s dynamic IT landscape, tools like NinjaOne can complement scripts like this by providing an integrated platform for managing IT operations, including security configurations. NinjaOne’s ability to centralize management tasks ensures that security policies are consistently applied across the entire IT infrastructure, enhancing overall security and operational efficiency.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).