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

Batch file to find the shared folder and remove the sharing

@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:/ 驱动器文件夹的共享?是权限问题吗?

让我举一个共享示例 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\SO617143.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.


==>