WSUSクライアントのキャッシュを、リモートから初期化するスクリプト（.bat）を書いてみた

#はじめに
WSUSクライアントで、更新エラーが消えない事象がちらほらあったので[こちらのページ](https://www.code-lab.net/?p=21376)で紹介されていた方法で解決できました。
そこで元記事のポリシーに従い、エンドユーザーにバレないことを前提条件としてスクリプト化（.bat）しました。

#前提条件

- ActiveDirectory+WSUS環境
- RPC(Remote Procedure Call)により、クライアントをリモート管理できる環境（[参考](http://qiita.com/nagase/items/3e9947afbf09063906dc)）
- [PsExec](https://technet.microsoft.com/ja-jp/sysinternals/pstools.aspx)がインストールされ、`psexec.exe`へのPathが設定されている
- エンドユーザーにバレないこと


#スクリプト全体

```cmd:wua_clear_cache.bat
@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Windows Update Agent のキャッシュ初期化
:: 概要: WSUSクライアントで、ダウンロードエラーが消えない場合に
::       このバッチを実行すると治る場合がある（かも）
::       ※要PsExec
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
setlocal ENABLEDELAYEDEXPANSION
set RETVAL=0

::::: 設定（ここから）:::::
set NODE=computer1
set USER=MYDOMAIN\Administrator
set PASS=XXXXXXXX
::::: 設定（ここまで）:::::


::------------------------------------------------------------------------------
:: ノード疎通チェック
::------------------------------------------------------------------------------
ping -n 1 %NODE% >NUL 2>&1
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
    echo "error: the node is offline."
    goto End
)

::------------------------------------------------------------------------------
:: 管理共有(C$)接続
::------------------------------------------------------------------------------
:ConnectIPC
call :Share connect
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
    goto End
)

::------------------------------------------------------------------------------
:: WindowsUpdateサービス停止
::------------------------------------------------------------------------------
:StopWuauserv
timeout 3 /nobreak >NUL
call :Service wuauserv stop
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
    goto DeleteIPC
)

::------------------------------------------------------------------------------
:: BITSサービス停止
::------------------------------------------------------------------------------
:StopBits
timeout 3 /nobreak >NUL
call :Service bits stop
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
    goto StartWuauserv
)

::------------------------------------------------------------------------------
:: 環境変数(SystemRoot, ProgramData)取得
::------------------------------------------------------------------------------
:GetEnv
timeout 3 /nobreak >NUL
set /p X="getting remote environment (systemroot, programdata) ... "<NUL
for /f "usebackq tokens=1,2 delims==" %%i in (`psexec \\%NODE% cmd /c set 2^> NUL ^| findstr /i "systemroot programdata"`) do (
    set var=%%i
    set val=%%j
    if /i "!var!"=="systemroot" (
        set SystemRootDir=!val:~2!
    )
    if /i "!var!"=="programdata" (
        set ProgramDataDir=!val:~2!
    )
)
if "%SystemRootDir%" == "" (
    set RETVAL=1
    echo Failed. ^(SystemRoot is empty^)
    goto StartBits
)
if "%ProgramDataDir%" == "" (
    set RETVAL=1
    echo Failed. ^(ProgramData is empty^)
    goto StartBits
)
echo Done.

::------------------------------------------------------------------------------
:: SoftwareDistributionフォルダ退避
::------------------------------------------------------------------------------
timeout 3 /nobreak >NUL
set /p X="moving SoftwareDistribution folder ... "<NUL
rd /s /q A:%SystemRootDir%\SoftwareDistribution.old >NUL 2>&1
move /y A:%SystemRootDir%\SoftwareDistribution A:%SystemRootDir%\SoftwareDistribution.old >NUL 2>&1
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
    echo Failed. ^(ErrCode=%errorlevel%^)
    goto StartBits
)
echo Done.

::------------------------------------------------------------------------------
:: qmgr0.datファイル削除
::------------------------------------------------------------------------------
timeout 3 /nobreak >NUL
set /p X="deleting qmgr0.dat ... "<NUL
del /q A:%ProgramDataDir%\Microsoft\Network\Downloader\qmgr0.dat >NUL 2>&1
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
    echo Failed. ^(ErrCode=%errorlevel%^)
    goto StartBits
)
echo Done.

::------------------------------------------------------------------------------
:: qmgr1.datファイル削除
::------------------------------------------------------------------------------
timeout 3 /nobreak >NUL
set /p X="deleting qmgr1.dat ... "<NUL
del /q A:%ProgramDataDir%\Microsoft\Network\Downloader\qmgr1.dat >NUL 2>&1
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
    echo Failed. ^(ErrCode=%errorlevel%^)
    goto StartBits
)
echo Done.

::------------------------------------------------------------------------------
:: BITSサービス起動
::------------------------------------------------------------------------------
:StartBits
timeout 3 /nobreak >NUL
call :Service bits start
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
)

::------------------------------------------------------------------------------
:: WindowsUpdateサービス起動
::------------------------------------------------------------------------------
:StartWuauserv
timeout 3 /nobreak >NUL
call :Service wuauserv start
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
)

::------------------------------------------------------------------------------
:: 管理共有(C$)切断
::------------------------------------------------------------------------------
:DeleteIPC
timeout 3 /nobreak >NUL
call :Share disconnect
if not %errorlevel% == 0 (
    set RETVAL=%errorlevel%
)

::------------------------------------------------------------------------------
:: 終了処理
::------------------------------------------------------------------------------
:End
endlocal
exit /b %RETVAL%


::==============================================================================
:: 管理共有接続/切断サブルーチン
::==============================================================================
:Share
set /p X="%1ing remote C$ share ... "<NUL
if "%1" == "connect" (
    net use A: \\%NODE%\C$ /user:%USER% %PASS% >NUL 2>&1
) else if "%1" == "disconnect" (
    net use A: /delete /y >NUL 2>&1
) else (
    echo Failed. ^(unknown parameter^)
    exit /b 1
)
if not %errorlevel% == 0 (
    echo Failed. ^(ErrCode=%errorlevel%^)
    exit /b %errorlevel%
)
echo Done.
exit /b 0

::==============================================================================
:: サービス開始/停止サブルーチン
::==============================================================================
:Service
set /p X="%2ing %1 service ... "<NUL
sc \\%NODE% %2 %1 >NUL 2>&1
if not %errorlevel% == 0 (
    echo Failed. ^(ErrCode=%errorlevel%^)
    exit /b %errorlevel%
)
echo Done.
exit /b 0
```

#実行結果

```
>wua_clear_cache.bat
connecting remote C$ share ... Done.
stoping wuauserv service ... Done.
stoping bits service ... Done.
getting remote environment (systemroot, programdata) ... Done.
moving SoftwareDistribution folder ... Done.
deleting qmgr0.dat ... Done.
deleting qmgr1.dat ... Done.
starting bits service ... Done.
starting wuauserv service ... Done.
disconnecting remote C$ share ... Done.
```