0070 0070 - 1 year ago 429
Powershell Question

PowerShell - Net Use check if exists

I'm doing a Power-Shell script to remove connection without using the

net use * /delete
. Is that any way i can check on the connected Remote first before i proceed to drop it? I tried this, but its not working as i thought. I open to any suggestion.

$conns = net use
foreach ($con in ($conns | select Remote)) {
if($con -eq "//MyServerB/C$") {
net use "//MyServerB/C$" /delete

Answer Source

Since net use is not a PowerShell cmdlet, you are not getting back an object with which you can filter with Select-Object. Instead you are getting back text. Additionally, net use on my system uses backslashes in the remote path instead of forward slashes and if you use double quotes you would have to escape the dollar sign so I would just use single quotes.

So your code would have to look like this:

$conns = net use
foreach ($con in $conns) {
    if($con -match '\\\\MyServerB\\C\$') {
       net use '\\MyServerB\C$' /delete
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download