Author Posts

December 22, 2017 at 5:22 pm

I wrote a script to check if an external drive used for backups is mapped to P:, and if not check to see if a drive labeled "Offsite*" is connected. If the Offsite drive is connected, it will change the drive letter to P:.

(Eventually I plan on integrating this into my backup script, but for now it is stand alone.)

#This script MUST be run in an elevated PowerShell Instance for the Set_WmiInstance cmdlet to change the drive letter of the backup drive.

$TargetDir = "P:\Offsite-BAK-Files\" #Destination folder
$TargetTest = Test-Path $TargetDir #Saves results of testing for an existing backup folder on the P: drive as a variable.
$OffsiteDrive = Get-WmiObject "Win32_Volume" -namespace "root\cimv2" | where-object {$_.Label -and ($_.Label -like "*OffSite*")} #Saves as a variable results of check for a drive containing a label that includes "Offsite"

If ($TargetTest) {

    Write-Host "P: drive is mapped"

    } ElseIf ($OffsiteDrive) {

            Set-WmiInstance -input $OffsiteDrive -Arguments @{DriveLetter="P:"}
            Write-Host "Changed drive letter of Offsite backup drive to P:"

        } Else {

            Write-Host "No backup drive is connected."
        
        }

The script functions properly, but it displays the properties of the drive saved to the $OffsiteDrive variable when it runs. How can I prevent this from happening?

December 22, 2017 at 6:07 pm

#Requires -RunAsAdministrator

$TargetDir = "P:\Offsite-BAK-Files\" #Destination folder
$TargetTest = Test-Path $TargetDir #Saves results of testing for an existing backup folder on the P: drive as a variable.
$OffsiteDrive = Get-WmiObject "Win32_Volume" -namespace "root\cimv2" | where-object {$_.Label -and ($_.Label -like "*OffSite*")} #Saves as a variable results of check for a drive containing a label that includes "Offsite"

If ($TargetTest) {

    Write-Output "P: drive is mapped"

} ElseIf ($OffsiteDrive) {

    Set-WmiInstance -input $OffsiteDrive -Arguments @{DriveLetter="P:"} | Out-Null
    Write-Output "Changed drive letter of Offsite backup drive to P:"

} Else {

    Write-Output "No backup drive is connected."
        
}

December 22, 2017 at 6:32 pm

Thanks Sam. I was turned around in thinking it was the variable that was displaying the output rather than the Set-WmiInstance cmdlet. As I'm sure you've gathered, I'm still pretty new to PowerShell scripting (as well as scripting in general).