Cannot get NET SHARE to work with spaced variables

53 views Asked by At

I am trying to write a batch file that goes over existing network shares and deletes all the non-administrative ones.

Here's my code:

FOR /F "USEBACKQ SKIP=1 TOKENS=*"  %%j IN (`wmic /node:192.168.0.101 SHARE WHERE "Name like '%%[^$]'" GET NAME ^| findstr /r /v "^$"`) DO NET SHARE %%j /DELETE

SKIP=1for skipping meta-column information on wmic return

findstr /r /v "^$" for removing a trailing whiteline from wmic return which was getting captured in %%j

Now, this only works for share names that do not contain a space in-between.

To remedy, I have tried (which doesn't work as well):

FOR /F "USEBACKQ SKIP=1 TOKENS=*"  %%j IN (`wmic /node:192.168.0.101 SHARE WHERE "Name like '%%[^$]'" GET NAME ^| findstr /r /v "^$"`) DO NET SHARE "%%j" /DELETE

Further, trying to echo the %%j variable in quotes resulted in this:

FOR /F "USEBACKQ SKIP=1 TOKENS=*"  %%j IN (`wmic /node:192.168.0.101 SHARE WHERE "Name like '%%[^$]'" GET NAME ^| findstr /r /v "^$"`) DO @ECHO "%%j"

Only single quotes present

Where only single quotes got printed

Kindly help!

2

There are 2 answers

5
Compo On BEST ANSWER

You can do all of that with a single WMIC command, without a For loop and without the need to involve FindStr or the Share option of net.exe:

@%SystemRoot%\System32\wbem\WMIC.exe /Node:192.168.0.101 Share Where "Type < 2147483648" Call Delete
1
dave_thompson_085 On

wmic for some insane reason outputs end of line with two CR's: CR CR LF. Windows including FINDSTR and CMD only takes CR LF as end of line and leaves the other CR as part of the data, so echo "somestuff <CR>" produces a display with " only in the leftmost column. In W10 (and I assume 11) if you redirect to a file and open it in notepad you will see it interprets these as 'Macintosh (CR)' linebreaks.

Windows tools aren't generally flexible in dealing with unexpected control characters. The only way I can find, in a CMD/batch file, is the delayedexpansion trick:

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "USEBACKQ SKIP=1 TOKENS=*"  %%j IN (`wmic ...`) DO @(SET "X=%%j" & ECHO {!X:~0,-1!})

However you will quickly see this leaves a bunch of trailing spaces (also) output by wmic, which causes e.g. net share "blah blah " /delete to fail, and I don't know any way to remove the trailing spaces while keeping embedded ones that you want.

If you instead use powershell's (get-smbshare).name you don't have either problem (no extra CR and no extra spaces, also no header line and no empty line to bother with). But if you use powershell you can use its filtering also and do the whole job in one command:

remove-smbshare ((get-smbshare).name -notmatch "\$") -force

and this is no longer the question you asked.