ninja-one/old/map-network-drive.ps1

#Requires -Version 5.1

<#
.SYNOPSIS
    Adds a shared drive from a server on the network.
.DESCRIPTION
    Adds a shared drive from a server on the network.
#>


[CmdletBinding()]
param (
    [Parameter()]
    [String]$Server,
    [Parameter()]
    [String]$Name,
    [Parameter()]
    [String]$DriveLetter,
    [Parameter()]
    [Switch]$Remove = [System.Convert]::ToBoolean($env:removeShare)
)



begin {
    # Check for required PowerShell version (7+)
    if (!($PSVersionTable.PSVersion.Major -ge 7)) {
        try {
            # Install PowerShell 7 if missing
            if (!(Test-Path "$env:SystemDrive\Program Files\PowerShell\7")) {
                Write-Output 'Installing PowerShell version 7...'
                Invoke-Expression "& { $( Invoke-RestMethod https://aka.ms/install-powershell.ps1 ) } -UseMSI -Quiet"
            }
    
            # Refresh PATH
            $env:Path = [System.Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [System.Environment]::GetEnvironmentVariable('Path', 'User')
    
            # Restart script in PowerShell 7
            pwsh -File "`"$PSCommandPath`"" @PSBoundParameters
    
        }
        catch {
            Write-Output 'PowerShell 7 was not installed. Update PowerShell and try again: $_'
            throw $Error
        }
        finally {
            exit $LASTEXITCODE
        }
    }
    else {
        $PSStyle.OutputRendering = 'PlainText'
    }

        
    if ($env:server -and $env:server -notlike "null") {
        $Server = $env:server
    }
    if ($env:shareName -and $env:shareName -notlike "null") {
        $Name = $env:shareName
    }
    if ($env:driveLetter -and $env:driveLetter -notlike "null") {
        $DriveLetter = $env:driveLetter
    }

    if (-not $Remove -and -not $Server) {
        Write-Host "[Error] Please specify a Server"
        exit 1
    }
    if (-not $Remove -and -not $Name) {
        Write-Host "[Error] Please specify a Share Name"
        exit 1
    }
    if (-not $DriveLetter) {
        Write-Host "[Error] Please specify a Drive Letter"
        exit 1
    }
    else {
        # if $DriveLetter contains a colon, remove it
        $DriveLetter = $DriveLetter -replace ":", ""
        
        # If $DriveLetter does not contain a colon, add one
        # if ($DriveLetter -notlike "*:*") {
        # $DriveLetter = "${DriveLetter}:"
        # }
    }
}
process {
    try {
        # if $Remove is true, remove the network drive
        if ($Remove) {
            Write-Host "Removing network drive: $DriveLetter"
            # net use requires $DriveLetter to be in the format of a drive letter (e.g. "Z:") so add a colon if it is missing
            if ($DriveLetter -notlike "*:*") {
                $DriveLetter = "${DriveLetter}:"
            }
            net use $DriveLetter /delete
            exit 0
        }

        # Check if the drive letter is already in use
        $existingDrive = Get-PSDrive -Name $DriveLetter -ErrorAction SilentlyContinue

        # If it is, check if it is already mapped to the desired network path
        if ($existingDrive) {
            if ($existingDrive.DisplayRoot -ieq "\\$Server\$Name") {
                Write-Host "Drive letter $DriveLetter is already mapped to \\$Server\$Name"
                exit 0
            }
            else {
                Write-Host "[Error] Drive letter $DriveLetter is already in use by $($existingDrive.DisplayRoot)"
                exit 1
            }
        }
        
        # check to make sure the user is a member of the domain
        $context = [System.DirectoryServices.AccountManagement.ContextType]::Domain
        $userPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::Current
        if (-not $userPrincipal.ContextType -eq $context) {
            Write-Host "User is not a domain user."
            exit 1
        }

        # Make sure the computer can connect to the server
        if (-not (Test-Connection -ComputerName $Server -Count 1 -Quiet)) {
            Write-Error -Message "[Error] Unable to connect to $Server"
            exit 1
        }
        
        # Add the network drive
        Write-Host "Adding network drive \\$Server\$Name to drive letter $DriveLetter"

        New-PSDrive -Name $DriveLetter -PSProvider "FileSystem" -Root "\\$Server\$Name" -Persist
    }
    catch {
        Write-Error $_
        Write-Host "[Error] Failed to add or remove the network drive: $DriveLetter"

        exit 1
    }
    exit 0
}
end {

}