The presence of certain drives can be very important for the successful operation of IT. In this article I would like to describe how you can check a drive connection remotely using Windows Powershell.
In this specific case, there was the problem that a drive that was mounted using a USB server* was disconnected due to a user error. This resulted in various error messages and software crashes.
For this reason, I installed a script that checks the connection remotely via Powershell and sends an email to the responsible administrator if the drive connection does not exist. If the drive is connected correctly, no email will be sent.
I then run the script at regular intervals using the task scheduler so that I am automatically notified if the drive is not available again.
Check existing drive connection using a script
In the first part of the script, the name of the remote server and the drive letter to be checked are entered. The email server as well as the sender and recipient of the email must be stored in the lower area.
# Define target server and drive letter $remoteServer = “TargetServerName” $driveLetter = “X:” # Script to run on the remote server $scriptBlock = { param($driveLetter) Get-PSDrive -Name $driveLetter.TrimEnd(‘:’ ) } # Check if the drive exists on the remote server if (-not (Invoke-Command -ComputerName $remoteServer -ScriptBlock $scriptBlock -ArgumentList $driveLetter)) { # Email parameters $smtpServer = “YourExchangeServer” # Exchange Server address $from = “[email protected]” # Sender address $to = “[email protected]” # Recipient address $subject = “Drive $driveLetter not found on $remoteServer” $body = “The drive $driveLetter was found on the Server $remoteServer not found.” # Sending the email Send-MailMessage -SmtpServer $smtpServer -From $from -To $to -Subject $subject -Body $body }
Checking the drive connection on the local server
If the check is to be carried out locally, the script is a little shorter, as we can have the command executed directly on the server in question.
# Define the drive letter to check $driveLetter = “X:” # Check if the drive exists if (!(Get-PSDrive | Where-Object { $_.Name -eq $driveLetter.TrimEnd(‘:’ ) })) { # Email parameters $smtpServer = “YourExchangeServer” # Exchange server address $from = “[email protected]” # Sender address $to = “[email protected]” # Recipient address $subject = “Drive $ driveLetter not found” $body = “The drive $driveLetter was not found on the server.” # Sending the email Send-MailMessage -SmtpServer $smtpServer -From $from -To $to -Subject $subject -Body $body }
Also interesting: