If you use RoyalTS, here’s a little script that makes it easy to mount a remote host’s share to a local drive. In essence, it performs the same functionality as net use * \\host\share /USER:domainname\username
.
How it works
Free drive letter
In PowerShell New-PSDrive
is the way to mount a share. There is no matching option for the *
argument in net use
though (the asterisk maps the share to the first available drive letter). This post provides a convenient one-liner that iterates through all drive letters from D to Z, and returns the first one available.
(68..90 | %{$L=[char]$_; if ((gdr).Name -notContains $L) {$L}})[0]
Authentication
Using Out-GridView
, the user is presented with a list of available share (retrieved with Get-WmiObject
). To query the host and mount the selected share, we need the proper credentials. One option could be to run the script as a different user, but that means the drive won’t be visible in Explorer, as described in the notes section of the New-PSDrive
documentation:
Mapped network drives are specific to a user account. Mapped drives created in elevated sessions or sessions using the credential of another user aren’t visible in sessions started using different credentials.
Instead, $Username
and $Password
are script parameters, passed on by RoyalTS. We wrap them into a PSCredential
object, and add it to the Get-WmiObject
and New-PSDrive
call.
Feedback
To provide feedback of the outcome, we use the BurntToast module. When the mount is successful, it shows a notification including a button to open the drive in Explorer. If there was an error, the notification contains the error message.
All that’s left is to configure a new Command Task object in RoyalTS with the following settings:
- Command:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
- Arguments:
-WindowStyle Minimized -File Mount-Share.ps1 -ComputerName $URI$ -Username $EffectiveUsername$ -Password $EffectivePassword$
- Credentials: Select Use the context credentials and uncheck Run task in user context of credential
Code
Reference
- Find next available free drive letter using PowerShell | vGeek - Tales from real IT system Administration environment
- GitHub - Windos/BurntToast: Module for creating and displaying Toast Notifications on Microsoft Windows 10.
- Royal Apps
- New-PSDrive (Microsoft.PowerShell.Management) - PowerShell | Microsoft Docs