Reputation: 329
I'd like to remove network drives from the system using a PowerShell script.
I need to find the drive by name, as the command $net.RemoveNetworkDrive('P:',1)
needs the driveletter.
Is there a command to find the network drive letter in PowerShell?
My script:
$Drive = "\\192.168.2.117\Blabla"
echo $Drive
cls
if (((New-Object -Com WScript.Network).EnumNetworkDrives() | Where-Object {$_ -eq $Drive}))
{
echo 'found Drive'
#$net = $(New-Object -comobject WScript.Network)
#$net.RemoveNetworkDrive('P:',1)
}
else
{
echo 'Drive not there'
}
Upvotes: 0
Views: 3953
Reputation: 194
You could try the following method for getting the drive information:
$Drive = Get-WmiObject -Class Win32_mappedLogicalDisk `
-filter "ProviderName='\\\\192.168.2.117\\Blabla'"
$Drive.Name
$Drive.Name
would become the drive letter which should allow you to the do the following:
$net = $(New-Object -comobject WScript.Network)
$net.RemoveNetworkDrive($Drive.Name,$true)
Upvotes: 3
Reputation: 1911
the actual solution is a combination of Win32_LogicalDisk
and your PS cmdlet :
$net = $(New-Object -comobject WScript.Network)
foreach($driveLetter in Get-WMIObject -query "Select * From Win32_LogicalDisk Where DriveType = 4" | Select-Object DeviceID)
{
#$net.RemoveNetworkDrive($driveLetter, $True)
echo $driveLetter
}
This will remove networkdrives only and does not need any weird UNC path or something.
Btw : dont use 1
where a boolean
is expected, that paradigm will break your scripts one day ... its what professionals call "bad code"
Upvotes: -1
Reputation: 5871
I would suggest using Get-PSDrive
instead of a COM Object.
Following code should work:
#get drive by root (note that we use "displayroot" for the comparison, "root" contains the driveletter)
Get-PSDrive | where {$_.DisplayRoot -eq "\\192.168.2.117\BlaBla"} | Remove-PSDrive
Or in Case you have to use the ComObject to remove the drive you can do the following:
$driveletter = (Get-PSDrive | where {$_.DisplayRoot -eq "\\192.168.2.117\BlaBla"}).root
$net.RemoveNetworkDrive($driveletter,$True)
Upvotes: 1