2012年12月28日金曜日

◆PowerGUIをVersion3で実行する

PowerGUIが一向にPowerShell3.0に対応してこないと思っていたら、どうやら3.0に対応させるためには起動パラメータが必要らしい。

"C:\Program Files\PowerGUI\ScriptEditor.exe" -version 3.0

リリースノートを見ると正式にはCTPまでの対応の様だ。
(実はかなり早い時期から対応していたのね・・・)

パラメータ付きで実行するとこんな感じになる。

image

2012年12月27日木曜日

◆PowerShell ISE でコメント編集(V3)

V3になってPowerShell ISEもインテリセンスが効くので本格的に使っても良いかと思うのだが、残念なことに致命的な機能不足としてコメント編集ができないのである。

ここまで高機能にしたにも拘わらず、コメント編集のようなポピュラーな機能がないというのは一体全体どういう事なのだろう。

と嘆いていても仕方がないのでなんとか自前でAdd-Onを作ってと思ったのだが、どうにもこうにも・・・・。

$psiseのSelectedTextがリードオンリーなのでちょっとうまい方法が浮かばない。

以下の様に力技でやってはみたものの、選択した行と全く同じ行が他にもあるとそちらもヒットしてしまう。

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020

#コメント化
$comment =
 {
 
$psise.CurrentFile.Editor.Text -split "`r`n" |  %
{
   
$targets =
 
   
$psise.CurrentFile.Editor.SelectedText  -split "`r`n";$result=
@()
  }{
   
if($_ -ne "" -and $targets -contains $_
){
   
$result += ("#" + $_)}else{$result += $_
}
  }{
   
$cmresult =
 
   
$result -join "`r`n";$psise.CurrentFile.Editor.Text = $cmresult
  }

 
$out = $psise.CurrentPowerShellTab.ConsolePane.
text
 
$out = $out.replace(('PS>' + $comment),""
)
 
cls
  $out
}
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.
Add(
                       
"Comment",$comment,"Alt+Z") | Out-Null

いろいろと調べたが、どうやらV3から追加になったブロック選択の機能を使うのが次善の策といった感じのようだ。

「Alt」キーを押しながらマウスで先頭カラムを範囲選択した上で”#”を打ち込めば一発で入るという寸法だ。
ちょっと見えづらいがこんな感じ
imageimage

マウスを使わない場合は「Alt」+「Shift」を押しながら矢印キーで選択していけばよい。

なれればほぼ我慢できるかなぁ。

◆特定の場所で文字列を分割(文字を削らない)

正規表現に詳しい方には常識かもしれないが以下のパターンは使いでがありそうなのでメモしておく。

Splitting Texts without Losing Anything - Power Tips - PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources

PS>$profile
F:\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

PS>$profile -split '\\'
F:
Documents
WindowsPowerShell
Microsoft.PowerShell_profile.ps1

PS>$profile -split '(?<=\\)'
F:\
Documents\
WindowsPowerShell\
Microsoft.PowerShell_profile.ps1

PS>$profile -split '(?=\\)'
F:
\Documents
\WindowsPowerShell
\Microsoft.PowerShell_profile.ps1

最初の例では分割文字に「\」を指定しているのでそれが削られたうえで分割される。

場合によっては「\」を削らずに分割したい場合があるでしょうというのが、この話の趣旨。

「\」の右側で分割するか左側で分割するかの2パターン。
これは「\」を先頭から検索するか後ろから検索するかで切り分けが可能。

ここら辺の正規表現の説明は以下を参照。
PowerShell: ◆正規表現の基礎<グループ化構成体>

2012年12月21日金曜日

◆IISのログを取得する2(結合、複合化、解凍)

PowerShell: ◆IISのログを取得する1(取得、圧縮、暗号化、分割)で作成したファイルをもとに戻すスクリプト。

ファイルのパターンは以下のように別れる。

  1. 圧縮ファイル(ログ.zip)
  2. 暗号化ファイル(ログ.dat)
  3. 非暗号化分割ファイル(ZIP.001~ZIP.nnn)
  4. 暗号化分割ファイル(DAT.001~DAT.nnn)

パラメータを指定せずにスクリプトを実行するとファイル選択ダイアログが表示されるので、対象のファイルを選択する。
(分割ファイルの場合はすべての分割ファイルを選択する。)

ファイル選択ダイアログはPowershellをSTAモードで実行する必要があるため「OutLogメイン.ps1」経由で「結合.ps1」を呼んでいる。
(V3からはSTAがデフォルトになったようだが。)

パラメータ指定で実行する時は、「InPath」に入力ファイル(分割ファイルの時はフォルダ指定)、「OutPath」に出力フォルダを指定する。

出力フォルダに「ログyyyyMMdd_HHmmss」の名前でフォルダを作り、その中にログを復号・解凍する。

image

<OutLogメイン.ps1>

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021

param(
 
[string]$InPath,
  [string]$OutPath="desktop"
)
#staで起動するために「OutLogメイン経由で結合.ps1を起動する。Ver3では不要」

$currntPath = Split-Path $myInvocation.MyCommand.path
Start-Transcript (Join-Path $currntPath "OutLog.log")

<# 分配演算子は使えない(バグ?)
$param = @{}
$param.OutPath = $OutPath
if($InPath){$param.InPath = $InPath}
#>

$scriptPath = Join-Path $currntPath "結合.ps1"
if($InPath
){
   
Powershell -sta $scriptPath $InPath $OutPath
}else
{
   
Powershell -sta $scriptPath -OutPath $OutPath
}
Stop-Transcript

<結合.ps1>

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174

param(
 
$InPath,
  $OutPath="desktop"
)

function MakeDir($path
){
 
$f = mkdir $path
  Write-Host "mkdir $path" -ForegroundColor Cyan
}

$currntPath = Split-Path $myInvocation.MyCommand.path
$initFolder = [Environment]::GetFolderPath("desktop")

#入力パス取得&パターン判定
##ZIP:zipファイル、DAT:暗号化(DAT)ファイル、
##ZIPn:圧縮分割フォルダ、DATn:暗号化分割フォルダ

$inPtn = "";[String[]]$inPathFiles=""
if($InPath
){
 
if(Test-Path $InPath -PathType Leaf){  #ファイル指定--
  if((Split-Path $InPath -Leaf) -eq "ログ.zip"
){
   
$inPtn = "ZIP"
    $inPathFiles[0] = $InPath
  }else
{
   
if((Split-Path $InPath -Leaf) -eq "ログ.dat"
){
     
$inPtn = "DAT"
    $inPathFiles[0] = $InPath
    }else
{
     
Write-Error "◆入力指定誤り◆";return
    }
  }
  }
elseif(Test-Path $InPath -PathType Container){  #フォルダ指定--
    if(dir $InPath -Filter zip.*
){
   
$inPtn = "ZIPn"
    $inPathFiles = dir $InPath -Filter zip.* | select -ExpandProperty fullname
  }elseif(dir $InPath -Filter dat.*
){
   
$inPtn = "DATn"
    $inPathFiles = dir $InPath -Filter dat.* | select -ExpandProperty fullname
  }else
{
   
Write-Error "◆入力指定誤り◆";return
  }
  }
else
{
   
$InPath -eq ""
    $InPath
    if($InPath){"True"
}
   
Write-Error "◆入力指定誤り◆";return
  }
}
else
{
 
Add-Type -AssemblyName System.Windows.Forms
 
 
$dl = New-Object System.Windows.Forms.OpenFileDialog
 
 
$dl.Title = "ファイルの選択"
 
 
$dl.InitialDirectory = $initFolder
 
 
$dl.Multiselect = $true
  if($dl.ShowDialog() -eq "OK"
){ 
     
$inPathFiles = $dl.
FileNames
   
switch (Split-Path $inPathFiles[0] -Leaf
) {
     
"ログ.zip" {$inPtn = "ZIP";break
}
     
"ログ.dat" {$inPtn = "DAT";break
}
     
"dat.001" {$inPtn = "DATn";break
}
     
"zip.001" {$inPtn = "ZIPn";break
}
     
default
 {
       
Write-Error "◆入力指定誤り◆";return
      }
    }
  }
else{return
}
}


#出力先フォルダ作成
if((Test-Path $OutPath) -eq $false
){
 
$spcialFolder = [environment+specialfolder] |
 
   
Get-Member -Static -type property | select -expand name
  if($spcialFolder -contains $OutPath
){
   
$OutPath = [Environment]::GetFolderPath($OutPath
)
  }
else
{
   
Write-Error "◆出力パス誤り◆";return
  }
}

$outPathRoot =
 
 
Join-Path $OutPath ("ログ" + (Get-Date).ToString("yyyyMMdd_HHmmss"))
MakeDir $outPathRoot 


#◆◆◆ パターンに応じて「結合」「複合化」「解凍」実行をコントロール 
function Executer
{
 
 
switch ($inPtn
) {
   
"ZIP"
 {
     
$zipTargetFile = $inPathFiles[0]
      break
    }
   
"DAT"
 {
     
$decryptTargetFile = $inPathFiles[0]
      . F_Decrypt
      $zipTargetFile = $DecryptedFileName
      break
    }
   
"ZIPn"
 {
     
$joinTargetFiles = $inPathFiles
      . F_Join
      $zipTargetFile = $joinedFileName
      break
    }
   
"DATn"
 {
     
$joinTargetFiles = $inPathFiles
      . F_Join
      $decryptTargetFile = $joinedFileName
      . F_Decrypt
      $zipTargetFile = $DecryptedFileName
      break
    }
   
default
 {
     
break
    }
  }
 
. F_UnZip
  dir $outPathRoot | ?{$_.PSIsContainer -eq $false} | del
}

#◆結合
function F_Join
{
 
#$inpPath = "F:\Desktop\test"
  #$outPath = "F:\Desktop\Dec.txt"
  $joinedFileName = Join-Path $outPathRoot "結合ログ.tmp"
  $dest = New-Object System.IO.FileStream
(
   
$joinedFileName,[IO.FileMode]::Create,[IO.FileAccess]::
Write)
 
Get-Item $joinTargetFiles | sort name | %
{
     
$data = [System.IO.File]::ReadAllBytes($_.
FullName)
     
$dest.Write($data,0,$data.
Length)
  }
 
$dest.
Dispose()
 
Write-Host "結合しました" -ForegroundColor Cyan
}

#◆複合化
function F_Decrypt
{
 
$KEYFilePath = Join-Path $currntPath "KEY.dat"
  $IVFilePath = Join-Path $currntPath "IV.dat"
  if((Test-Path $KEYFilePath) -and (Test-Path $IVFilePath
)){
   
$desKey = [System.IO.File]::ReadAllBytes($KEYFilePath
)
   
$desIV = [System.IO.File]::ReadAllBytes($IVFilePath
)
  }
else
{
   
$desKey = [byte[]](1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1
)
   
$desIV = [byte[]](0,0,0,0,0,0,0,0
)
  }
 
$DecryptedFileName = Join-Path $outPathRoot "ログ.zip"
  $src = [System.IO.File]::ReadAllBytes($decryptTargetFile
)

 
$desProvider =
 
   
New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider
  $decryptor = $desProvider.CreateDecryptor($desKey,$desIV
)
 
$ms = New-Object System.IO.MemoryStream
  $cs = New-Object System.Security.Cryptography.CryptoStream
(
   
$ms, $decryptor, [System.Security.Cryptography.CryptoStreamMode]::
Write)
 
$cs.Write($src,0,$src.
Length)
 
$cs.
Close()
 
[System.IO.File]::WriteAllBytes($DecryptedFileName,$ms.
ToArray())
 
Write-Host "複合しました" -ForegroundColor Cyan
}

#◆解凍
function F_UnZip
{
 
$dllPath = Join-Path $currntPath "ICSharpCode.SharpZipLib.dll"
  [Void][Reflection.Assembly]::LoadFile($dllPath
)
 
$zipFile =
 
     
New-Object ICSharpCode.SharpZipLib.Zip.FastZip
  $zipFile.RestoreAttributesOnExtract  = $true
  $zipFile.RestoreDateTimeOnExtract = $true
  $zipFile.CreateEmptyDirectories = $true
  #$zipFile.ExtractZip($DecryptedFileName,$outPathRoot,"")
  $zipFile.ExtractZip($zipTargetFile,$outPathRoot,""
)
 
Write-Host "解凍しました" -ForegroundColor Cyan
}

. Executer  #「結合」「複合化」「解凍」呼び出し
Write-Host "◆終了しました◆" -ForegroundColor Magenta

2012年12月20日木曜日

◆IISのログを取得する1(取得、圧縮、暗号化、分割)ソース

PowerShell: ◆IISのログを取得する1(取得、圧縮、暗号化、分割)のソース

<オプションダイアログ.ps1>

#config取得

$scriptPath = Split-Path $myInvocation.MyCommand.path

$confPath = Join-Path $scriptPath "GetLog.config"

$conf = [xml](Get-Content $confPath)

 

#CheckBoxchk*変数名を使っているので他には使わない

Remove-Variable chk*

 

$frmCls = "System.Windows.Forms"

Add-Type -AssemblyName $frmCls

$ctrlArray = New-Object System.Collections.ArrayList

 

function CreateObj($ctrl){

    $obj = New-Object $ctrl

  $obj.Left = 10

  if($obj -is [System.Windows.Forms.Label]){

    $obj.Height -= 10

  }

  [void]$ctrlArray.Add($obj)

    return $obj

}

$form = New-Object $frmCls".Form"

$form.Text = "オプション指定"

$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

 

#コントロール

$chk1 = createObj $frmCls".CheckBox"

$chk1.Text = "圧縮";$chk1.Checked = $true

$chk2 = createObj $frmCls".CheckBox"

$chk2.Text = "暗号化";$chk2.Checked = $false

$chk3 = createObj $frmCls".CheckBox"

$chk3.Text = "分割(KB)";$chk3.Checked = $false

$chk3.add_CheckedChanged({

  $txt2.Enabled = $chk3.Checked

})

$txt2 = CreateObj $frmCls".TextBox"

$txt2.Text = 500

$txt2.TextAlign = "Right"

$txt2.Enabled = $chk3.Checked

 

 

$chk4 = createObj $frmCls".CheckBox"

$chk4.Text = "イベントログ(全部)";$chk4.Checked = $true

$chk4.add_CheckedChanged({

  $chk5.Enabled = !$chk4.Checked

})

$chk5 = createObj $frmCls".CheckBox"

$chk5.Text = "イベントログ(範囲抽出)"

$chk5.Enabled = $false

$chk5.add_CheckedChanged({

  $chk4.Enabled = !$chk5.Checked

  if($chk5.Checked){$chk4.Checked = $false}

  $dp1.Enabled = $dp2.Enabled = $chk5.Checked

})

 

$lb1 = CreateObj $frmCls".Label"

$lb1.Text = "イベントログ抽出開始日"

$dp1 = CreateObj $frmCls".DateTimePicker"

$dp1.Enabled = $false

 

$lb2 = CreateObj $frmCls".Label"

$lb2.Text = "イベントログ抽出終了日"

$dp2 = CreateObj $frmCls".DateTimePicker"

$dp2.Enabled = $false

 

#configから抽出項目列挙(オプション)

$counterChkBox = Get-Variable |

?{$_.Value -is [System.Windows.Forms.CheckBox]} |

  measure | select -ExpandProperty count

$conf.root.iislogs.log | %{

  ++$counterChkBox

  $currentObj =

    Set-Variable -Name chk$counterChkBox -Value (

    createObj $frmCls".CheckBox") -PassThru

  $currentObj.Value.Text = $_.name

  $currentObj.Value.Checked = $true

}

 

#出力先用フォルダー選択ダイアログ

$lbl3 = CreateObj $frmCls".Label"

$lbl3.Text = "出力場所"

$txt1 = CreateObj $frmCls".TextBox"

$deskPath = [environment]::GetFolderPath("desktop")

$txt1.Text = $deskPath

$btnFolder = CreateObj $frmCls".Button"

$btnFolder.Text = "..."

$btnFolder.add_Click({

  $shell = New-Object -com Shell.Application

  

  $folderPath =

    $shell.BrowseForFolder(0,"対象フォルダーを選択してください",0,$deskPath)

  if($folderPath){$txt1.Text = $folderPath.Self.Path}

 

})

 

#OK」「Cancel」ボタン

$btnOK = CreateObj $frmCls".Button"

$btnOK.Text = "OK"

$btnCancel = CreateObj $frmCls".Button"

$btnCancel.Text = "キャンセル"

$form.AcceptButton = $btnOK ; $form.CancelButton = $btnCancel

$btnOK.add_Click({

  $ret = $true

  $txt1.BackColor = $txt2.BackColor = "White"

  if(!($txt1.Text -and (Test-Path $txt1.Text)))

  {

    $txt1.BackColor = "Pink";$ret = $false

  }

  if($chk3.Checked -and ![int]::TryParse($txt2.Text,[ref]$null)){

    $txt2.BackColor = "Pink";$ret = $false

  }

  if($ret){

    $form.Close()

    $form.set_DialogResult([System.Windows.Forms.DialogResult]::OK)

  }

})

$btnCancel.add_Click({$form.Close()})

 

$ctrlArray.ToArray()  |

    ?{$_ -is [System.Windows.Forms.Control]} |

    %{$yPos=5}{

        $_.Width = 200

        $_.Top = $yPos

        $yPos += $_.Height + 5

        $form.Controls.Add($_)

    $form.Height = $yPos + 50  #タイトルバーを簡便的に50程度と扱う

     }

 

#ボタンレイアウト調整

$btnFolder.Width = 30;$btnFolder.top = $txt1.top

$btnFolder.Left = $txt1.Left + $txt1.Width + 5

$btnFolder.Height = $txt1.Height

$btnCancel.Top = $btnOK.Top

$btnOK.Width = $btnCancel.Width = 100

$btnCancel.Left = $btnOK.Right + 10

 

#ダイアログ結果リターン

$dialogReturn = $false

if($form.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK){

  $dialogReturn = $true

  $dlgOutPath = $txt1.Text

  $dlgSelectFromDay = $dp1.Value

  $dlgSelectEndDay = $dp2.Value

  $dlgsplitSize = 1024 * $txt2.Text

  $dlgOptions = Get-Variable chk* -ValueOnly | select -ExpandProperty Checked

}

$form.Dispose()

 

#ダイアログボタン結果,出力パス,イベントログ抽出開始日,終了日,分割サイズ,

#チェックボックス値(圧縮,

#  暗号化,分割,イベントログ全部,イベントログ一部,ログオプション・・・・) 

return $dialogReturn,$dlgOutPath,$dlgSelectFromDay,

       $dlgSelectEndDay,$dlgSplitSize,$dlgOptions

<GetLogメイン.ps1>

param(

  [string]$OutPath="desktop",

  [switch]$EventLog,

  [datetime]$FromEvent,

  [datetime]$ToEvent,

  [switch]$Compress,

  [switch]$Encrypt,

  [switch]$Split,

  [long]$SplitSizeKB=500,

  [bool[]]$Options 

)

$currntPath = Split-Path $myInvocation.MyCommand.path

Start-Transcript (Join-Path $currntPath "GetLog.log")

$confPath = Join-Path $currntPath "GetLog.config"

$conf = [xml](Get-Content $confPath)

$confOptions = $conf.root.iislogs.log

 

if($PSBoundParameters.get_Count()){

  if(!($EventLog -or $FromEvent -or $ToEvent -or $Options.Count)){

    Write-Error "Enter target log.";return

  }

  $P_OutPath = $OutPath

  $P_EventLog = $EventLog

  $P_FromEvent = $FromEvent

  $P_ToEvent = $ToEvent

  $P_Compress = $Compress

  $P_Encrypt = $Encrypt

  $P_Split = $Split

  $P_SplitSize = $SplitSizeKB * 1kb

  $P_Options = 1..$confOptions.Count | %{$false}  #falseの配列を作る

  if($Options){

    0..($Options.Count-1) | %{$P_Options[$_] = $Options[$_]}

  }

#  $P_Options = $Options

}else{

  $dialogParam = & (Join-Path $currntPath "オプションダイアログ.ps1")

  $dialogReturn,$dlgOutPath,$dlgSelectFromDay,

  $dlgSelectEndDay,$dlgSplitSize,$dlgOptions = $dialogParam

  if($dialogReturn){

    $P_OutPath = $dlgOutPath

    $P_EventLog = $dlgOptions[3]  #イベントログ(全部)

    if($dlgOptions[4]){      #イベントログ(範囲抽出)

      $P_FromEvent = $dlgSelectFromDay

      $P_ToEvent = $dlgSelectEndDay

    }else{

      $P_FromEvent = $P_ToEvent = $null

    }

    $P_Compress = $dlgOptions[0]  #圧縮

    $P_Encrypt = $dlgOptions[1]    #暗号化

    $P_Split = $dlgOptions[2]    #分割

    $P_SplitSize = $dlgSplitSize  #分割サイズ

    #IISログ+その他オプションログ

    $P_Options = $dlgOptions[5..($dlgOptions.count-1)]   

  }else{

    exit

  }

}

 

$bunkatuPath = Join-Path $currntPath "分割.ps1"

 

& $bunkatuPath $P_OutPath $P_EventLog $P_FromEvent $P_ToEvent `

  $P_Compress $P_Encrypt $P_Split $P_SplitSize $P_Options $conf

Write-Host "Script End" -ForegroundColor Cyan

Stop-Transcript

<分割.ps1>

param(

  [string]$OutPath,

  $EventLog,

  $FromEvent,

  $ToEvent,

  $Compress,

  $Encrypt,

  $Split,

  [long]$SplitSize,

  [bool[]]$Options,

  [xml]$conf

)

 

function MakeDir($path){

  $f = mkdir $path

  Write-Host "mkdir $path" -ForegroundColor Cyan

}

 

$filterString = @"

  Event/System/TimeCreated[@SystemTime>='{0}'] and

  Event/System/TimeCreated[@SystemTime<'{1}']

"@

 

$currntPath = Split-Path $myInvocation.MyCommand.path

$confPath = Join-Path $currntPath "GetLog.config"

#プログレスバー

$evlogTotal = $conf.root.eventlogs.log.count

if($conf.root.eventlogs.text -eq "true"){$evlogTotal = $evlogTotal * 2}

$evLogCounter = 0

function WriteProgress($currentOperation,$endflg){

<#  $script:evLogCounter++

    if($endflg){

        $percent = 100

    }else{

        $percent = [Math]::Min(($script:evLogCounter * 100 / $evlogTotal),90)

    }

  Write-Progress -Activity ログ取得 -Status "取得しています" `

    -CurrentOperation (Split-Path $currentOperation -Leaf) `

    -PercentComplete $percent #>

}

 

#出力先フォルダ作成

if((Test-Path $OutPath) -eq $false){

  $spcialFolder = [environment+specialfolder] |

    Get-Member -Static -type property | select -expand name

  if($spcialFolder -contains $OutPath){

    $OutPath = [Environment]::GetFolderPath($OutPath)

  }else{

    Write-Error "出力パス誤り";return

  }

}

$outPathRoot =

  Join-Path $OutPath ("ログ" + (Get-Date).ToString("yyyyMMdd_HHmmss"))

MakeDir $outPathRoot | Out-Null

$plainPath = Join-Path $outPathRoot "オリジナル"

MakeDir $plainPath | Out-Null

 

#◆◆◆ イベントログ抽出◆◆◆◆◆◆◆

$filter = $null

if($EventLog){  #全部抽出

  $filter = "*"

}elseif($FromEvent){ #日付範囲で抽出

  $startTime = $FromEvent.ToString("yyyy/MM/dd 00:00:00")

    if($ToEvent -eq $null){$ToEvent = Get-Date}

  $endTime = $ToEvent.AddDays(1).ToString("yyyy/MM/dd 00:00:00")

  $startUtcTime =

    [System.TimeZoneInfo]::ConvertTimeToUtc(

      $startTime).ToString("yyyy-MM-ddTHH:mm:ssZ")

  $endUtcTime =

    [System.TimeZoneInfo]::ConvertTimeToUtc(

      $endTime).ToString("yyyy-MM-ddTHH:mm:ssZ")

 

  $filter = $filterString -f $startUtcTime,$endUtcTime

}

 

if($filter){

  $evsession =

    New-Object -TypeName System.Diagnostics.Eventing.Reader.EventLogSession

  #イベントログ用フォルダ作成

  $evLogFolder = Join-Path $plainPath "イベントログ"

  MakeDir $evLogFolder

  #抽出対象ログ名称取得し、それぞれにFilterを適用しながらGet

  $conf.root.eventlogs.log |

  %{

    #初期処理

    $dateRange=$null

    if(!$EventLog){

      $dateRange = $FromEvent.ToString("yyyyMMdd") + "-" +

             $ToEvent.ToString("yyyyMMdd") 

    }

  }{  #ログ種類毎の処理

    #イベントログ形式で出力

    $evLogFullName = 

      Join-Path $evLogFolder ($_.name + $dateRange + ".evtx")

    $evsession.ExportLog($_.name,"LogName",$filter,$evLogFullName)

    Write-Host "出力しました $evLogFullName" -ForegroundColor Cyan

    WriteProgress $evLogFullName

    #テキストで出力

        if($conf.root.eventlogs.text -eq "true"){

            $filterHash = @{}

            $filterHash.LogName = $_.name

            if(!$EvnetLog){

                $filterHash.StartTime = $startTime

                $filterHash.EndTime = $endTime

            }

      Get-WinEvent -FilterHashtable $filterHash |

      %{

        $csvPath = [IO.Path]::ChangeExtension($evLogFullName,"txt")

        $sw = New-Object System.IO.StreamWriter(

            $csvPath,$false,[Text.Encoding]::UTF8)

                $sw.WriteLine(

                    ("レベル","日付と時刻","ソース","イベント ID",

           "タスクのカテゴリ","メッセージ" -join "`t"))

      }{

        if($_.task -eq 0){$task = "なし"}else{$task = $_.task}

                $sw.WriteLine(

                    ($_.LevelDisplayName,$_.TimeCreated,$_.ProviderName,

           $_.Id,$task,$_.message -join "`t"))

      }{

        $sw.Close()

        Write-Host "出力しました $csvPath" -ForegroundColor Cyan

        WriteProgress $csvPath

      }

    }

 

  }

}

 

#◆◆◆ IISログコピー◆◆◆◆◆◆

$optionCtr = 0

$conf.root.iislogs.log | %{

  if($Options[$optionCtr++]){

    $logPath = Join-Path $plainPath $_.name

    MakeDir $logPath | Out-Null

    if($_.day){

      $day = (Get-Date).AddDays(-($_.day)).ToString("yyyy/MM/dd") 

    }else{

      $day = [DateTime]::MinValue.ToString("yyyy/MM/dd")

    }

   

    $targetPath = $_.Path

    if($_.sitename){  #IISアクセスログはパスにサイトIDを付加する

            $siteName = $_.sitename

      $iis =

          New-Object DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC")

      $siteID = $iis.children | ?{$_.schemaClassName -eq "IIsWebServer"} |

         ?{$_.serverComment -eq $siteName} | select -expand name

               

      $targetPath = $targetPath -replace '\(id\)',$siteID

    }

    dir $targetPath | ?{!$_.PSIsContainer} |

      ?{$_.LastWriteTime -gt $day} | copy -Destination $logPath -PassThru |

      %{"コピーしました $_"} | Write-Host -ForegroundColor Cyan 

  }

}

 

WriteProgress "終了" $true

 

#圧縮◆◆◆◆◆◆

if($Compress -or $Encrypt){

  $zipFolder = Join-Path $outPathRoot "圧縮"

  MakeDir $zipFolder | Out-Null

  $outZipFile = Join-Path $zipFolder "ログ.zip"

  $dllPath = Join-Path $currntPath "ICSharpCode.SharpZipLib.dll"

  [Void][Reflection.Assembly]::LoadFile($dllPath)

  $zipFile =

      New-Object ICSharpCode.SharpZipLib.Zip.FastZip

  $zipFile.CreateEmptyDirectories = $true

  $zipFile.CreateZip($outZipFile,$plainPath,$true,$null,$null)

  Write-Host "圧縮しました $outZipFile" -ForegroundColor Cyan

}

 

#暗号化◆◆◆◆◆◆

if($Encrypt){

  $encFolder = Join-Path $outPathRoot "暗号化"

  MakeDir $encFolder

  $outEncFile = Join-Path $encFolder "ログ.dat"

  $KEYFilePath = Join-Path $currntPath "KEY.dat"

  $IVFilePath = Join-Path $currntPath "IV.dat"

  if((Test-Path $KEYFilePath) -and (Test-Path $IVFilePath)){

    $desKey = [System.IO.File]::ReadAllBytes($KEYFilePath)

    $desIV = [System.IO.File]::ReadAllBytes($IVFilePath)

  }else{

    $desKey = [byte[]](1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1)

    $desIV = [byte[]](0,0,0,0,0,0,0,0)

  }

 

  $src = [System.IO.File]::ReadAllBytes($outZipFile)

  $desProvider =

    New-Object System.Security.Cryptography.TripleDESCryptoServiceProvider

  $encryptor = $desProvider.CreateEncryptor($desKey,$desIV)

  $ms = New-Object System.IO.MemoryStream

  $cs = New-Object System.Security.Cryptography.CryptoStream(

    $ms, $encryptor, [System.Security.Cryptography.CryptoStreamMode]::Write)

  $cs.Write($src,0,$src.Length)

  $cs.Close()

  [System.IO.File]::WriteAllBytes($outEncFile,$ms.ToArray())

  Write-Host "暗号化しました $outEncFile" -ForegroundColor Cyan

}

 

#分割◆◆◆◆◆

if($Split -and ($Compress -or $Encrypt)){

  $splitFolder = Join-Path $outPathRoot "分割"

  MakeDir $splitFolder

  if($Encrypt){

    $outSplitFileBase = Join-Path $splitFolder "DAT"

  }else{

    $outSplitFileBase = Join-Path $splitFolder "ZIP"

  }

  if($Encrypt){

    $splitTargetFile = Get-Item $outEncFile

  }else{

    $splitTargetFile = Get-Item $outZipFile

  }

  if($splitTargetFile.Length -gt $SplitSize)

  {

      $src = [System.IO.File]::ReadAllBytes($splitTargetFile)

      $num = 0

      for ($remain = $src.length; $remain -gt 0; $remain -= $SplitSize) {

          $length = [System.Math]::Min($SplitSize,$remain)

          $dest = New-Object byte[] $Length

          [System.Array]::Copy($src,$num * $SplitSize,$dest,0,$length)

          $num++

          $exName = ".{0:D3}" -f $num

          $splitName = $outSplitFileBase + $exName

          [System.IO.File]::WriteAllBytes($splitName,$dest)

      Write-Host "分割しました $splitName" -ForegroundColor Cyan

      }

  }else{

    Write-Host $splitTargetFile -ForegroundColor Yellow

    Write-Host $outSplitFileBase -ForegroundColor Yellow

    Copy $splitTargetFile ($outSplitFileBase + ".001")

  }

}

 

Write-Host "◆◆◆ 終了しました ◆◆◆" -ForegroundColor Magenta