Variable set in script displaying output when script is run

This topic contains 2 replies, has 2 voices, and was last updated by  Bruce Keezer 4 months ago.

  • Author
    Posts
  • #89936

    Bruce Keezer
    Participant

    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?

  • #89939

    Sam Boutros
    Participant
    #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."
            
    }
    
  • #89942

    Bruce Keezer
    Participant

    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).

You must be logged in to reply to this topic.