批处理文件以查找共享文件夹并删除共享

时间:2017-03-06 03:38:05

标签: batch-file batch-processing

@echo off
FOR /F "usebackq" %%i IN (`hostname`) DO SET HOSTNAME=%%i

for /F %%a IN ('wmic /node:"%HOSTNAME%" share get path') DO (
IF "%%a"=="C:\windows" (
    echo "Cannot remove ADMIN shared Drive" %%a
) ELSE (
    NET SHARE %%a /DELETE
)

)

endlocal

我编写了这个以Windows调度程序运行的脚本。该脚本检查共享文件夹并删除共享文件夹。我面临的问题是当我独自运行时

wmic /node:"%HOSTNAME%" share get path

我明白了:

Path
C:\windows
C:\
E:\
E:\someFolder

但是当我运行脚本时它只删除E:\和E:\ someFolder而不是C:。 我写的条件不是删除C:\ windows但为什么它跳过C:。 请帮忙。

更新 实际上我刚看到它没有删除任何C:/驱动器文件夹的共享?这是许可问题吗?

1 个答案:

答案 0 :(得分:0)

让我给出一个共享示例odds and ends,其中包含共享名称和资源路径中的空格:

==> net share | findstr /I "Resource --- odds \$"
Share name   Resource                        Remark
-------------------------------------------------------------------------------
ADMIN$       C:\Windows                      Remote Admin
C$           C:\                             Default share
D$           D:\                             Default share
IPC$                                         Remote IPC
print$       C:\Windows\system32\spool\drivers
odds and ends
             D:\bat\odds and ends

==>

以下脚本显示了脚本中的一些错误(主要在注释和ECHO中解释)。另请参阅Dave Benham's WMIC and FOR /F: A fix for the trailing <CR> problem

@ECHO OFF
SETLOCAL EnableExtensions

FOR /F "usebackq" %%i IN (`hostname`) DO SET HOSTNAME=%%i

set "_narrow="                         your setting - get all 
set "_narrow=^| find /I "odds""        setting to narrow output - delete this line

echo(
echo --- ORIGINAL APPROACH: does not respect spaces in path ---
for /F %%a IN ('wmic /node:"%HOSTNAME%" share get path %_narrow%') DO echo [%%~a]

echo(
echo --- UPDATED: respects spaces in path but does not respect wmic behaviour ---
for /F "delims=" %%a IN ('wmic /node:"%HOSTNAME%" share get path %_narrow%') DO (
    echo [%%~a])

echo(
echo --- UPDATED: DBenham's solution preserves unwanted trailing spaces ---
for /F "delims=" %%a IN ('wmic /node:"%HOSTNAME%" share get path %_narrow%') DO (
  for /F "delims=" %%A in ("%%~a") do echo [%%~A]
)

echo(
echo --- WORKING SCRIPT ---
for /F "tokens=1,* delims==" %%a IN ('
  wmic /node:"%HOSTNAME%" share get path /value %_narrow%
') do for /F "delims=" %%A in ("%%~b") do (
    IF /I "%%~A"=="C:\windows" (
        echo "Cannot remove ADMIN shared Drive" [%%A]
    ) ELSE (
        rem next NET SHARE command is merely ECHOed for debugging purposes 
        ECHO NET SHARE "%%~A" /DELETE
    )
)

<强>输出

==> D:\bat\SO\42617143.bat

--- ORIGINAL APPROACH: does not respect spaces in path ---
[D:\bat\odds]

--- UPDATED: respects spaces in path but does not respect wmic behaviour ---
]D:\bat\odds and ends

--- UPDATED: DBenham's solution preserves unwanted trailing spaces ---
[D:\bat\odds and ends                 ]

--- WORKING SCRIPT ---
NET SHARE "D:\bat\odds and ends" /DELETE

==>

<强>答案即可。但是,NET命令需要提升才能成功执行某些操作:

==> NET SHARE "D:\bat\odds and ends" /DELETE
System error 5 has occurred.

Access is denied.


==>