LoginSignup
1
1

More than 5 years have passed since last update.

Windows Server Backup by powershell

Last updated at Posted at 2017-10-04

小難しくない程度にPowershellでもにょもにょやってみました。
作ってみたけどお蔵入り…orz

Windows Server Backup by powershell

WBADMINによるSYSTEMバックアップ取得が失敗した場合に、PSのerrorlevelに相当する$lastexitcodeを使用して正常終了(0)でない場合に、自分で作ったフォルダを片付けてスクリプトを離脱exitする。だけ。

point

  • \$lastexitcode
     dosでいうerrorlevelと同じように扱える 
  • \$ret= Invoke-Expression -Command \$command2
     Invokeに渡すときは$commandのように変数に1つに固める。\$ret= で出力を取出せる
  • Remove-Item $bkup_path -recurse
     フォルダ消去。recurseで中身・サブフォルダごと。
WSBSYSBACKUP.ps1
###ログの指定と格納先準備
$logfile = "C:\UserScripts\WSB_LOG.txt"
$bkup_path ="\\192.168.1.10\ABChost_sysbk\"
$DateText = get-date -format "yyyyMMdd_HHmmss"
$bkup_path = $bkup_path + $DateText

###フォルダ作る
md $bkup_path

###WSBコマンド
$command = "WBADMIN Delete Catalog -quiet"
$command2 = "WBADMIN START BACKUP -backupTarget:" + $bkup_path + " -allCritical -systemState -vssFull -quiet"

###いざ実行
Invoke-Expression -Command $command
$ret= Invoke-Expression -Command $command2

###WSBログはoutしとく
echo $ret > $logfile

###エラー処理(正常の0じゃneぇとき反応。WSBを直接キャンセルすると-3とか。)
if ($lastexitcode -ne 0){
    echo "WBADMINが正常に終了しなかったため処理を中断します。return:$lastexitcode" >> $logfile
    echo "この処理で作成した次のフォルダのバックアップは不完全です。" >> $logfile
    echo "$bkup_path は自動削除します。" >> $logfile
    ###フォルダは消す
    Remove-Item $bkup_path -recurse
    exit     ###離脱
}else{
}

以降に、引き続き正常な時の処理を書く

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1