批量删除Windows系统中的所有网络共享

时间:2016-10-19 22:49:48

标签: windows batch-file

我尝试使用批处理脚本删除Windows 7计算机上托管的所有共享。

代码

@echo off

REG QUERY HKLM\System\CurrentControlSet\Services\LanmanServer\Shares > %APPDATA%\shares.txt

findstr /I /V HKEY_LOCAL_MACHINE %APPDATA%\shares.txt | findstr /I /V HKLM >> %APPDATA%\shares2.txt

SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=1" %%S in (%APPDATA%\shares2.txt) do (
    set tempy=%%S
    net share "!tempy!" /delete
)
ENDLOCAL

shares.txt (运行后)

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Shares
Test    REG_MULTI_SZ    CSCFlags=0\0MaxUses=4294967295\0Path=C:\Test\0Permissions=0\0Remark=\0ShareName=Docs\0Type=0
Sp aces    REG_MULTI_SZ    CSCFlags=0\0MaxUses=4294967295\0Path=C:\Test\0Permissions=0\0Remark=\0ShareName=Sp aces\0Type=0

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Shares\Security

shares2.txt (运行后)

Test    REG_MULTI_SZ    CSCFlags=0\0MaxUses=4294967295\0Path=C:\Test\0Permissions=0\0Remark=\0ShareName=Docs\0Type=0
Sp aces    REG_MULTI_SZ    CSCFlags=0\0MaxUses=4294967295\0Path=C:\Test\0Permissions=0\0Remark=\0ShareName=Sp aces\0Type=0

我用两股测试它,"测试"和" Sp aces"

我能够删除test分享,但我无法删除sp aces分享,因为"tokens=1"只抓取第一个字。如何调整它以使其适用于单个单词和带空格的单词?

2 个答案:

答案 0 :(得分:0)

...假设:

  • shares2.txt使用四个相邻的空格作为列分隔符;
  • 共享名称不包含四个相邻的空格;
  • 共享名称不包含|字符;
  • 共享名称不包含!字符;
  • 共享名称不以;字符开头;

...以下代码可能适合您:

setlocal EnableDelayedExpansion
for /F "usebackq delims=" %%S in ("%APPDATA%\shares2.txt") do (
    set "tempy=%%S"
    for /F "tokens=1 delims=|" %%N in ("!tempy:    =|!") do (
        net share "%%N" /delete
    )
)
endlocal

以下是一个改进的变体,它允许共享名称包含!并以;开头:

setlocal DisableDelayedExpansion
for /F "usebackq delims=" %%S in ("%APPDATA%\shares2.txt") do (
    set "tempy=%%S"
    setlocal EnableDelayedExpansion
    for /F "tokens=1 delims=|" %%N in (^""!tempy:    =|!"^") do (
        endlocal
        net share "%%~N" /delete
    )
)
endlocal

答案 1 :(得分:0)

一个批处理文件,没有临时文件,完全未经测试,甚至可能无法使用某些数据类型:

@Echo Off
For /F "Tokens=2* Delims==;" %%A In ('WMIC Class StdRegProv Call EnumValues^
 "&H80000002"^, "System\CurrentControlSet\Services\LanmanServer\Shares"
 ^|Find "sNames"') Do Set "_=%%A"
For %%A In (%_:~2,-1%) Do Net Share %%A /Delete