Skip to content

Instantly share code, notes, and snippets.

@kspeeckaert
Created October 12, 2021 07:45
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 kspeeckaert/41e6f5a3dacaa5b83b577bc4cdfd5491 to your computer and use it in GitHub Desktop.
Save kspeeckaert/41e6f5a3dacaa5b83b577bc4cdfd5491 to your computer and use it in GitHub Desktop.
Mount a remote share (to be used with RoyalTS)
#Requires -Module BurntToast
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)] [String]$ComputerName,
[Parameter(Mandatory=$true)] [String]$Username,
[Parameter(Mandatory=$true)] [String]$Password
)
function Get-DisplayName {
param (
[Parameter(Mandatory)][string]$ComputerName
)
if ($ComputerName -match '\d+\.\d+\.\d+\.\d+') {
# We have received an IP
$HostDisplayName = $ComputerName
} else {
# We received a hostname, possibly with FQDN
$HostDisplayName = $ComputerName.split('.')[0]
}
return $HostDisplayName
}
try {
# Convert to SecureString
[securestring]$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
[pscredential]$Credential = New-Object System.Management.Automation.PSCredential ($Username, $SecurePassword)
Write-Verbose "Enumerating shares for $ComputerName ..."
$Shares = Get-WmiObject -Class Win32_Share -ComputerName $ComputerName -Credential $Credential
$Share = $Shares | Sort-Object -Property Name | Out-GridView -Title 'Select a share to mount...' -PassThru
if ($Share -eq $null) {
Write-Verbose 'User cancelled!'
break
}
# Source: http://vcloud-lab.com/entries/windows-2016-server-r2/find-next-available-free-drive-letter-using-powershell-
$LocalDrive = (68..90 | %{$L=[char]$_; if ((Get-PSDrive).Name -notContains $L) {$L}})[0]
$UNCPath = "\\${ComputerName}\$($Share.Name)"
# Shorten the name of the UNC path for the notification
$UNCDisplayPath = "\\$(Get-DisplayName -ComputerName $ComputerName)\$($Share.Name)"
Write-Verbose "Mounting $UNCPath to ${LocalDrive}..."
New-PSDrive `
-Name $LocalDrive `
–PSProvider FileSystem `
–Root $UNCPath `
–Persist `
-Credential $Credential | Out-Null
New-BurntToastNotification `
-AppLogo 'remote_drive.png' `
-Text "Drive mounted!",
"$UNCDisplayPath mounted to ${LocalDrive}" `
-Button $(New-BTButton -Content 'Open drive' -Arguments "${LocalDrive}:\")
}
catch {
New-BurntToastNotification `
-AppLogo 'remote_drive.png' `
-Text "Mount failed!",
"Failed to mount $UNCPath!",
$_.Exception.Message
Write-Error $_.Exception.Message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment