DIY DLPシステム

機密情報の漏洩を防ぐという主なタスクに加えて、DLPシステムには二次的な(追加の)タスクがあります。 これらには以下が含まれます。





手動のDLPシステムはすべてのタスクを解決するのではなく、以下にのみ焦点を合わせます。





Windowsでファイルを見つけるのは簡単で簡単な作業です。 リモートマシンでの検索でさえ、それほど複雑ではありません。 しかし、何百台ものマシンで何かを見つける必要がある場合、問題はどのようになりますか? すべてのPCを手で歩いてはいけません。 このタスクは、情報を保存するために監査を実施する必要がある場合など、Windows管理者の作業では非常に一般的です。 はい、実装例はありますが、保存が禁止されているデータ(映画、ゲームなど)を見つけることを目的としています。私が提案したオプションは、DLPシステムのタスクの1つを実装します。



それで、スクリプトは何をすることができますか(またはむしろスクリプトのセット)? 管理者を煩わせず、検証のためにPCのリストをダウンロードしないために、スクリプトはADと統合し、必要な情報を取得します。拡張子と名前でフィルタリングし、例外を追加し、フォルダーにレポートを生成し、管理者とユーザーにメッセージを送信することができます(通知の検出必要なファイルと推奨事項)。 パラメーターを組み合わせて変更し、必要な機能を取得できます。 検索後、検索情報が保存されているPCの名前を持つファイルのリストが作成されます。 スクリプトの2番目の部分は、見つかったファイルをすべて削除するか、特定の基準に従って削除することです。



このスクリプトを使用してユーザーを追跡し、作業ドキュメントを特定の場所(パーソナルネットワークドライブ)に保存する必要があることを通知します。スクリプトはPC上のアクティブユーザーを識別し、ADからメールボックスに関するデータを取得し、どのファイルとそれが見つかったかに関する通知を送信しますユーザーがネットワークストレージに移動する必要があるローカルドライブ上で削除します。そうしないと削除されます。 その結果、規制に従っていないものを削除します。 したがって、機密情報の保存を制御するDLPシステムの機能の1つを実装します。



ファイル検索スクリプトアルゴリズム







  1. 特定のOUからワークステーションのリストを取得します
  2. HomePage属性のデータをチェックします。値が「Pass」の場合、ファイルの検索はスキップされます。検索はこのコンピューターで既に実行されているためです。
  3. 可用性を確認します
  4. 利用できない場合は、ファイルに書き込みます
  5. 可能な場合、ファイルを検索します
  6. 検索の最後に、HomePage属性に書き込みます-値「Pass」
  7. ファイルは、マシンの名前と検出されたファイルのリストで形成されます
  8. メッセージが添付ファイル付きで管理者に送信されます
  9. ローカルユーザー名を指定します
  10. ユーザーのADアドレ​​スを認識します
  11. レポートのコピーを送信します


バイパスリセットスクリプトアルゴリズム







  1. ADからマシンのリストを取得します
  2. notpass属性の値を設定します


したがって、すべてのマシンは、すでにスキャンされたマシンを含め、スクリプト処理の分野に分類されます。



ファイル削除スクリプトアルゴリズム







  1. スクリプトの内容をロードします
  2. リストの各行(結果)について、リモートコンピューター上のオブジェクトを削除します


スクリプトのセットアップと起動(ファイル監査)



スクリプトは、指定されたパラメーターを使用してコマンドとして実行されます。 以下は、スクリプトとそのパラメーターの実行例です。 Start-AuditFiles-スクリプトを実行するコマンド。 タスクの必要に応じて、パラメーターを組み合わせることができます。



例1



Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder “*Folder1*,*Folder2*” -ReportPath \\server\reports\ - Throttle 5
      
      





この例では、OUからコンピューターを検索します。ファイル(* File1 *、* File2 *)を除く拡張子(* .doc、*。Docx、*。Sys)を持つすべてのファイルは、ディレクトリ(* Folder1 *、* Folder2 *)を除きます。 、レポートはディレクトリに複製されます(\\ server \ reports \)。 レポートはユーザーと管理者に送信されます。 スレッドの数は5です。



例2



 Start-AuditFiles -RemoteComputer ws-pc-4902,ws-pc-0982 -SMTP smtp.server.com -AdminMail administrator@server.com -Include *.doc,*.docx,*.sys -ExclusionFile *New*,*au* -AdminOnly - Throttle 10
      
      





この例では、コンピューター(ws-pc-4902、ws-pc-098)、ファイル(* File1 *、* File2 *)を除くすべての拡張子(* .doc、*。Docx、*。Sys)を持つファイルを検索します。 レポートは管理者にのみ送信されます。 スレッドの数は10です。



ターゲットコンピューターの設定



OURemoteComputerの指定に必要または必要 )-ターゲットコンピューターのある組織単位へのパス。このパラメーターが指定されていない場合、RemoteComputerパラメーターを指定する必要があります。 これらの2つのパラメーターのいずれかをスクリプトで使用する必要があります。



例:-OU "OU =テスト、DC =ルート、DC =ローカル"または-OU $ Computerlist(変数は他のスクリプトと組み合わせて設定されます)。



RemoteComputerOUの指定に必要または必須 )-リストの特定のコンピューター(特定の1つまたは複数のコンマ)に対してのみスクリプトを実行する必要がある場合に設定



例:-RemoteComputer ws-pc-4902、ws-pc-0982



検索オプション



IncludeFile必須、マスクを使用できます *)-検索する必要があるファイルまたはその拡張子のリスト(リストの場合があります)。



ExclusionFileオプション )-検索から除外するファイルのリスト(リストの場合があります)。



ExclusionFolderオプション )-検索から除外されたディレクトリのリスト。



レポートオプション



ReportPathオプション )-スキャン結果がコピーされるネットワークリソースまたはローカルディレクトリへのパス。



AdminMailオプション )-レポートを送信するためのアドレス。管理者宛てのレポートは同じアドレスに配信されます。



SMTPオプション )-メッセージを送信するためのゲートウェイとして使用されるSMTPサーバーの名前。



AdminOnlyオプション )-管理者のみにレポートを送信するモードを有効にします。



スロットル必須、1〜99の数値 )-スキャンスレッドの数を設定します。



モジュールのインストール



ファイルをディレクトリ「C:\ Windows \ system32 \ WindowsPowerShell \ v1.0 \ Modules」にコピーする必要があります。

Invoke-Parallel.psm1

Start-AuditFiles.psm1



スクリプトを実行する前に、モジュールをインポートする必要があります。



 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Invoke-Parallel.psm1 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1
      
      





スクリプト(モジュール)



このスクリプトは、 Invoke-Parallel.psm1ファイルとして保存する必要があります。



スクリプトInvoke-Parallel.psm1
 function Invoke-Parallel { [cmdletbinding(DefaultParameterSetName='ScriptBlock')] Param ( [Parameter(Mandatory=$false,position=0,ParameterSetName='ScriptBlock')] [System.Management.Automation.ScriptBlock]$ScriptBlock, [Parameter(Mandatory=$false,ParameterSetName='ScriptFile')] [ValidateScript({test-path $_ -pathtype leaf})] $ScriptFile, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [Alias('CN','__Server','IPAddress','Server','ComputerName')] [PSObject]$InputObject, [PSObject]$Parameter, [switch]$ImportVariables, [switch]$ImportModules, [int]$Throttle = 20, [int]$SleepTimer = 200, [int]$RunspaceTimeout = 0, [switch]$NoCloseOnTimeout = $false, [int]$MaxQueue, [validatescript({Test-Path (Split-Path $_ -parent)})] [string]$LogFile = "C:\temp\log.log", [switch] $Quiet = $false ) Begin { if( -not $PSBoundParameters.ContainsKey('MaxQueue') ) { if($RunspaceTimeout -ne 0){ $script:MaxQueue = $Throttle } else{ $script:MaxQueue = $Throttle * 3 } } else { $script:MaxQueue = $MaxQueue } Write-Verbose "Throttle: '$throttle' SleepTimer '$sleepTimer' runSpaceTimeout '$runspaceTimeout' maxQueue '$maxQueue' logFile '$logFile'" if ($ImportVariables -or $ImportModules) { $StandardUserEnv = [powershell]::Create().addscript({ $Modules = Get-Module | Select -ExpandProperty Name $Snapins = Get-PSSnapin | Select -ExpandProperty Name $Variables = Get-Variable | Select -ExpandProperty Name @{ Variables = $Variables Modules = $Modules Snapins = $Snapins } }).invoke()[0] if ($ImportVariables) { Function _temp {[cmdletbinding()] param() } $VariablesToExclude = @( (Get-Command _temp | Select -ExpandProperty parameters).Keys + $PSBoundParameters.Keys + $StandardUserEnv.Variables ) Write-Verbose "Excluding variables $( ($VariablesToExclude | sort ) -join ", ")" $UserVariables = @( Get-Variable | Where { -not ($VariablesToExclude -contains $_.Name) } ) Write-Verbose "Found variables to import: $( ($UserVariables | Select -expandproperty Name | Sort ) -join ", " | Out-String).`n" } if ($ImportModules) { $UserModules = @( Get-Module | Where {$StandardUserEnv.Modules -notcontains $_.Name -and (Test-Path $_.Path -ErrorAction SilentlyContinue)} | Select -ExpandProperty Path ) $UserSnapins = @( Get-PSSnapin | Select -ExpandProperty Name | Where {$StandardUserEnv.Snapins -notcontains $_ } ) } } Function Get-RunspaceData { [cmdletbinding()] param( [switch]$Wait ) Do { $more = $false if (-not $Quiet) { Write-Progress -Activity "Running Query" -Status "Starting threads"` -CurrentOperation "$startedCount threads defined - $totalCount input objects - $script:completedCount input objects processed"` -PercentComplete $( Try { $script:completedCount / $totalCount * 100 } Catch {0} ) } Foreach($runspace in $runspaces) { $currentdate = Get-Date $runtime = $currentdate - $runspace.startTime $runMin = [math]::Round( $runtime.totalminutes ,2 ) $log = "" | select Date, Action, Runtime, Status, Details $log.Action = "Removing:'$($runspace.object)'" $log.Date = $currentdate $log.Runtime = "$runMin minutes" If ($runspace.Runspace.isCompleted) { $script:completedCount++ if($runspace.powershell.Streams.Error.Count -gt 0) { $log.status = "CompletedWithErrors" Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] foreach($ErrorRecord in $runspace.powershell.Streams.Error) { Write-Error -ErrorRecord $ErrorRecord } } else { $log.status = "Completed" Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] } $runspace.powershell.EndInvoke($runspace.Runspace) $runspace.powershell.dispose() $runspace.Runspace = $null $runspace.powershell = $null } ElseIf ( $runspaceTimeout -ne 0 -and $runtime.totalseconds -gt $runspaceTimeout) { $script:completedCount++ $timedOutTasks = $true $log.status = "TimedOut" Write-Verbose ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] Write-Error "Runspace timed out at $($runtime.totalseconds) seconds for the object:`n$($runspace.object | out-string)" if (!$noCloseOnTimeout) { $runspace.powershell.dispose() } $runspace.Runspace = $null $runspace.powershell = $null $completedCount++ } ElseIf ($runspace.Runspace -ne $null ) { $log = $null $more = $true } if($logFile -and $log){ ($log | ConvertTo-Csv -Delimiter ";" -NoTypeInformation)[1] | out-file $LogFile -append } } $temphash = $runspaces.clone() $temphash | Where { $_.runspace -eq $Null } | ForEach { $Runspaces.remove($_) } if($PSBoundParameters['Wait']){ Start-Sleep -milliseconds $SleepTimer } } while ($more -and $PSBoundParameters['Wait']) } if($PSCmdlet.ParameterSetName -eq 'ScriptFile') { $ScriptBlock = [scriptblock]::Create( $(Get-Content $ScriptFile | out-string) ) } elseif($PSCmdlet.ParameterSetName -eq 'ScriptBlock') { [string[]]$ParamsToAdd = '$_' if( $PSBoundParameters.ContainsKey('Parameter') ) { $ParamsToAdd += '$Parameter' } $UsingVariableData = $Null if($PSVersionTable.PSVersion.Major -gt 2) { $UsingVariables = $ScriptBlock.ast.FindAll({$args[0] -is [System.Management.Automation.Language.UsingExpressionAst]},$True) If ($UsingVariables) { $List = New-Object 'System.Collections.Generic.List`1[System.Management.Automation.Language.VariableExpressionAst]' ForEach ($Ast in $UsingVariables) { [void]$list.Add($Ast.SubExpression) } $UsingVar = $UsingVariables | Group SubExpression | ForEach {$_.Group | Select -First 1} $UsingVariableData = ForEach ($Var in $UsingVar) { Try { $Value = Get-Variable -Name $Var.SubExpression.VariablePath.UserPath -ErrorAction Stop [pscustomobject]@{ Name = $Var.SubExpression.Extent.Text Value = $Value.Value NewName = ('$__using_{0}' -f $Var.SubExpression.VariablePath.UserPath) NewVarName = ('__using_{0}' -f $Var.SubExpression.VariablePath.UserPath) } } Catch { Write-Error "$($Var.SubExpression.Extent.Text) is not a valid Using: variable!" } } $ParamsToAdd += $UsingVariableData | Select -ExpandProperty NewName -Unique $NewParams = $UsingVariableData.NewName -join ', ' $Tuple = [Tuple]::Create($list, $NewParams) $bindingFlags = [Reflection.BindingFlags]"Default,NonPublic,Instance" $GetWithInputHandlingForInvokeCommandImpl = ($ScriptBlock.ast.gettype().GetMethod('GetWithInputHandlingForInvokeCommandImpl',$bindingFlags)) $StringScriptBlock = $GetWithInputHandlingForInvokeCommandImpl.Invoke($ScriptBlock.ast,@($Tuple)) $ScriptBlock = [scriptblock]::Create($StringScriptBlock) Write-Verbose $StringScriptBlock } } $ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock("param($($ParamsToAdd -Join ", "))`r`n" + $Scriptblock.ToString()) } else { Throw "Must provide ScriptBlock or ScriptFile"; Break } Write-Debug "`$ScriptBlock: $($ScriptBlock | Out-String)" Write-Verbose "Creating runspace pool and session states" $sessionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() if ($ImportVariables) { if($UserVariables.count -gt 0) { foreach($Variable in $UserVariables) { $sessionstate.Variables.Add( (New-Object -TypeName System.Management.Automation.Runspaces.SessionStateVariableEntry -ArgumentList $Variable.Name, $Variable.Value, $null) ) } } } if ($ImportModules) { if($UserModules.count -gt 0) { foreach($ModulePath in $UserModules) { $sessionstate.ImportPSModule($ModulePath) } } if($UserSnapins.count -gt 0) { foreach($PSSnapin in $UserSnapins) { [void]$sessionstate.ImportPSSnapIn($PSSnapin, [ref]$null) } } } $runspacepool = [runspacefactory]::CreateRunspacePool(1, $Throttle, $sessionstate, $Host) $runspacepool.Open() Write-Verbose "Creating empty collection to hold runspace jobs" $Script:runspaces = New-Object System.Collections.ArrayList $bound = $PSBoundParameters.keys -contains "InputObject" if(-not $bound) { [System.Collections.ArrayList]$allObjects = @() } if( $LogFile ){ New-Item -ItemType file -path $logFile -force | Out-Null ("" | Select Date, Action, Runtime, Status, Details | ConvertTo-Csv -NoTypeInformation -Delimiter ";")[0] | Out-File $LogFile } $log = "" | Select Date, Action, Runtime, Status, Details $log.Date = Get-Date $log.Action = "Batch processing started" $log.Runtime = $null $log.Status = "Started" $log.Details = $null if($logFile) { ($log | convertto-csv -Delimiter ";" -NoTypeInformation)[1] | Out-File $LogFile -Append } $timedOutTasks = $false } Process { if($bound) { $allObjects = $InputObject } Else { [void]$allObjects.add( $InputObject ) } } End { Try { $totalCount = $allObjects.count $script:completedCount = 0 $startedCount = 0 foreach($object in $allObjects){ $powershell = [powershell]::Create() if ($VerbosePreference -eq 'Continue') { [void]$PowerShell.AddScript({$VerbosePreference = 'Continue'}) } [void]$PowerShell.AddScript($ScriptBlock).AddArgument($object) if ($parameter) { [void]$PowerShell.AddArgument($parameter) } if ($UsingVariableData) { Foreach($UsingVariable in $UsingVariableData) { Write-Verbose "Adding $($UsingVariable.Name) with value: $($UsingVariable.Value)" [void]$PowerShell.AddArgument($UsingVariable.Value) } } $powershell.RunspacePool = $runspacepool $temp = "" | Select-Object PowerShell, StartTime, object, Runspace $temp.PowerShell = $powershell $temp.StartTime = Get-Date $temp.object = $object $temp.Runspace = $powershell.BeginInvoke() $startedCount++ Write-Verbose ( "Adding {0} to collection at {1}" -f $temp.object, $temp.starttime.tostring() ) $runspaces.Add($temp) | Out-Null Get-RunspaceData $firstRun = $true while ($runspaces.count -ge $Script:MaxQueue) { if($firstRun){ Write-Verbose "$($runspaces.count) items running - exceeded $Script:MaxQueue limit." } $firstRun = $false Get-RunspaceData Start-Sleep -Milliseconds $sleepTimer } } Write-Verbose ( "Finish processing the remaining runspace jobs: {0}" -f ( @($runspaces | Where {$_.Runspace -ne $Null}).Count) ) Get-RunspaceData -wait if (-not $quiet) { Write-Progress -Activity "Running Query" -Status "Starting threads" -Completed } } Finally { if ( ($timedOutTasks -eq $false) -or ( ($timedOutTasks -eq $true) -and ($noCloseOnTimeout -eq $false) ) ) { Write-Verbose "Closing the runspace pool" $runspacepool.close() } [gc]::Collect() } } }
      
      







次のスクリプトは、ファイルStart-AuditFiles.psm1として保存する必要があります。



スクリプトStart-AuditFiles.psm1
 $Body = ",              .     ,            .     : 1)         2)         . Function Start-AuditFiles { <# .Synopsis     ,        .Description            (C$ D$ ..  .).   : 1.      OU      2.    3.     4.      ,   5.    6.   ,    ,    7.    ,       .Examples  1 Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder *Folder1*,*Folder2* -ReportPath \\server\reports\         OU,     (*.doc,*.docx,*.sys)   (*File1*,*File2*),   (*Folder1*,*Folder2*),     (\\server\reports\)  2 Start-AuditFiles -RemoteComputer ws-pc-4902,ws-pc-0982 -SMTP smtp.server.com -AdminMail administrator@server.com -Include *.doc,*.docx,*.sys -ExclusionFile *New*,*au* -AdminOnly        (ws-pc-4902,ws-pc-098),     (*.doc,*.docx,*.sys)   (*File1*,*File2*),     .Notes       OU  RemoteComputer, OU   , RemoteComputer          .Link ... #> [CmdletBinding()] Param ( [String]$OU, [String[]]$RemoteComputer, [String[]]$ExclusionFile, [String]$ReportPath, [String]$AdminMail, [String[]]$IncludeFile, [String[]]$ExclusionFolder, [Switch]$AdminOnly = $false, [String]$SMTP, [String]$Throttle = 5 ) If (!$RemoteComputer) {$Hosts = (Get-ADComputer -Filter * -SearchBase $OU -Properties * | where { ( $PSItem.HomePage -notlike 'pass' )} ).name} else { $Hosts = $RemoteComputer } invoke-parallel -InputObject $Hosts -throttle $Throttle -ImportVariables -ScriptBlock { if(Test-Connection -ComputerName $_ -BufferSize 16 -quiet -count 2) { $Object = $_ $ErrorActionPreference = 'SilentlyContinue' $ExclusionFolder2 = $ExclusionFolder -replace ",","|" $StartTime = (Get-Date).ToString() $Hosts (Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $Object | %{Get-ChildItem ('\\' + $Object + '\' + ($_.DeviceID).remove(1) + '$\*') -Include $IncludeFile -Exclude $ExclusionFile -Recurse -Force | ?{$PSItem.FullName -notmatch $ExclusionFolder2}}).FullName | Out-File -FilePath $env:TEMP\$Object.txt -Encoding unicode If (!$ReportPath) {} else {Copy-Item -Path $env:TEMP\$Object.txt -Destination $ReportPath -Force} $EndTime = (Get-Date).ToString() Write-Output ($Object) | Add-Content $env:TEMP\Online.txt Invoke-Item $env:TEMP\$Object.txt $Results = "" | Select ComputerName, "StartTime", "EndTime" $Results.ComputerName = $Object $Results.StartTime = $StartTime $Results.EndTime =$EndTime $Results If ((Get-Content $env:TEMP\$Object.txt) -eq $Null) {} else { Try { Send-MailMessage -SmtpServer $SMTP -to $AdminMail -Body $Object -From denis.pasternak@hotmail.com -Subject $Object -Attachments $env:TEMP\$Object.txt } Catch {''} If ($AdminOnly -eq $True) { Write-Host "  AdminOnly -    " -ForegroundColor Yellow} else { $Username=((gwmi win32_computersystem -computer $Object -ErrorAction SilentlyContinue).UserName -split '\\')[1] if($username -ne $null) { $Body = $Body $dispalyname = (Get-AdUser $username -properties DisplayName).DisplayName $email = (Get-AdUser $username -properties mail).mail sleep -Seconds 3 Send-MailMessage -SmtpServer $SMTP -Body ( ' ' + $Dispalyname + ' ' + $Body | out-string ) -To $email -From $AdminMail -Subject $Object -Attachments $env:TEMP\$Object.txt -Encoding Unicode } } } else{ } } else { (Write-Output ($Object + ' ' + (Get-Date).ToString()) | Add-Content $env:TEMP\Offline.txt)} } $OU= $null $RemoteComputer = $null $Hosts = $nul Get-Content $env:TEMP\Online.txt | Set-ADComputer -HomePage 'pass' } Function Remove-AuditFiles { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetFile ) Get-Content -Path "$env:TEMP\$Path" | %{Remove-Item $PSItem} } Function Reset-AuditComputers { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetOU ) Get-ADComputer -Filter * -SearchBase $TargetOU -Properties * | Set-ADComputer -HomePage 'notpass' '' | Set-Content -Path $env:TEMP\Online.txt }
      
      







スケジュールされた実行



サンプルディレクトリc:\ scriptsにファイルを作成します。



RunScript.ps1-ファイル



テキストをコピーします。



 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Invoke-Parallel.psm1 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1 #   ,       Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder *Folder1*,*Folder2* -ReportPath \\server\reports\ - Throttle 5
      
      





ファイル検索スケジュールを作成する





結果と作業ファイルに関する情報



スクリプトは、スキャン結果を%TEMP%ディレクトリに保存します。 例では、このディレクトリはC:\ Users \ Administrator \ AppData \ Local \ Tempです。 コンピューターが使用可能で、ファイルが見つかった場合、結果を含むファイルが作成されます。 コンピューターが使用できない場合、これに関する情報がoffline.txtファイルに追加されます。







見つかったファイルを削除する



PowerShellを起動してコマンドを実行します。



 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1 Remove-AuditFiles  Remove-AuditFiles - TargetFile ws-9281.txt,ws-8721.txt
      
      





Remove-AuditFiles-すべての検索結果を検索し、各結果を処理した後、ファイルを削除します。



特定のファイル(特定のコンピューター)を指定できます。例:



Remove-AuditFiles-TargetFile ws-9281.txt、ws-8721.txt



スキャンしたコンピューターのリストをリセットする



PowerShellを起動してコマンドを実行します。



Reset-AuditComputers



実行後、指定されたOUのコンピューターはスキャンされていないものとしてマークされます。



 Import-Module C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Start-AuditFiles.psm1 Reset-AuditComputers - TargetOU OU "OU=Test,DC=root,DC=local"
      
      





スクリプトの説明
$ Body変数-メッセージの本文に挿入されるテキストが含まれます。 将来、このテキストはエンドユーザーに手紙で送られます。



 $Body = ",              .     ,            .     : 1)         2)         .
      
      





派生名Start-AuditFilesが与えられた関数の始まり:



 Function Start-AuditFiles {
      
      





ヘルプテキストを伴うスクリプトの説明。 「Get-Help Start-AuditFiles」を使用して、ヘルプを使用し、例と構文に関する情報を取得できます。



 <# .Synopsis     ,        .Description            (C$ D$ ..  .).   : 1.      OU      2.    3.     4.      ,   5.    6.   ,    ,    7.    ,       .Examples  1 Start-AuditFiles -OU "OU=Test,DC=root,DC=local" -SMTP smtp.server.com -AdminMail administrator@server.com -IncludeFile *.doc,*.docx,*.sys -ExclusionFile *File1*,*File2* -ExclusionFolder *Folder1*,*Folder2* -ReportPath \\server\reports\         OU,     (*.doc,*.docx,*.sys)   (*File1*,*File2*),   (*Folder1*,*Folder2*),     (\\server\reports\)  2 Start-AuditFiles -RemoteComputer ws-pc-4902,ws-pc-0982 -SMTP smtp.server.com -AdminMail administrator@server.com -Include *.doc,*.docx,*.sys -ExclusionFile *New*,*au* -AdminOnly        (ws-pc-4902,ws-pc-098),     (*.doc,*.docx,*.sys)   (*File1*,*File2*),     .Notes       OU  RemoteComputer, OU   , RemoteComputer          .Link ... #>
      
      





関数で将来使用する変数について説明します。



$ OU-Active Directoryの組織単位へのパス

$ ExclusionFile-検索から除外されたファイルのリスト

$ ReportPath-レポートが複製されるディレクトリへのパス

$ AdminMail-レポートの送信元および管理者向けのコピーの送信元の管理者の電子メールアドレス

$ IncludeFile-検索されるファイル拡張子またはファイル名

$ ExclusionFolder-検索から除外されたフォルダーのリスト

$ AdminOnly-レポートを管理者のみに送信するかどうかを回答するパラメーター

$ SMTP-SMTPサーバーのアドレスまたは名前

$スロットル-並列スレッドの数。



 [CmdletBinding()] Param ( [String]$OU, [String[]]$RemoteComputer, [String[]]$ExclusionFile, [String]$ReportPath, [String]$AdminMail, [String[]]$IncludeFile, [String[]]$ExclusionFolder, [Switch]$AdminOnly = $false, [String]$SMTP, [String]$Throttle = 5 )
      
      





「RemoteComputer」キーが使用された場合、チェックが実行されます。この場合、スキャンは特定の(指定された)コンピューターでのみ行われ、「OU」キーが指定された場合-この場合リストは指定されたOU ADから取得され、HomePage属性を持つコンピューターが選択されます「パス」(これは、既に検索されたマシンで検索が繰り返されるのを防ぐために行われます)。



 If (!$RemoteComputer) {$Hosts = (Get-ADComputer -Filter * -SearchBase $OU -Properties * | where { ( $PSItem.HomePage -notlike 'pass' )} ).name} else { $Hosts = $RemoteComputer }
      
      





スクリプト実行の開始、ホスト値、およびスレッド数が置き換えられます。



 invoke-parallel -InputObject $Hosts -throttle $Throttle -ImportVariables -ScriptBlock {
      
      





ネットワーク上のコンピューターの可用性を確認します。



 if(Test-Connection -ComputerName $_ -BufferSize 16 -quiet -count 2) {
      
      





検索の実行に必要な変数の値は、上記の変数から取得されます。 検索の開始は記憶されます。



  $Object = $_ $ErrorActionPreference = 'SilentlyContinue' $ExclusionFolder2 = $ExclusionFolder -replace ",","|" $StartTime = (Get-Date).ToString() $Hosts
      
      





検索の実行:



  • 物理ディスクのリストの取得(Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $ Object)
  • UNCパスはドライブ文字(Get-ChildItem( '\\' + $ Object + '\' +($ _。DeviceID).remove(1)+ '$ \ *')で形成されます
  • 含まれるオブジェクトと除外の検索のキーを示します(-Include $ IncludeFile -Exclude $ ExclusionFile -Recurse -Force)
  • , (?{$PSItem.FullName -notmatch $ExclusionFolder2}}).FullName)
  • (Out-File -FilePath $env:TEMP$Object.txt -Encoding unicode)


 (Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $Object | %{Get-ChildItem ('\\' + $Object + '\' + ($_.DeviceID).remove(1) + '$\*') -Include $IncludeFile -Exclude $ExclusionFile -Recurse -Force | ?{$PSItem.FullName -notmatch $ExclusionFolder2}}).FullName | Out-File -FilePath $env:TEMP\$Object.txt -Encoding unicode
      
      





, «ReportPath», .

  If (!$ReportPath) {} else {Copy-Item -Path $env:TEMP\$Object.txt -Destination $ReportPath -Force}
      
      





.



  $EndTime = (Get-Date).ToString()
      
      





, .



 Write-Output ($Object) | Add-Content $env:TEMP\Online.txt
      
      





, , .



  Invoke-Item $env:TEMP\$Object.txt $Results = "" | Select ComputerName, "StartTime", "EndTime" $Results.ComputerName = $Object $Results.StartTime = $StartTime $Results.EndTime =$EndTime $Results
      
      





, , ( ), . .



 If ((Get-Content $env:TEMP\$Object.txt) -eq $Null) {}
      
      





, SMTP , , , .



  else { Try { Send-MailMessage -SmtpServer $SMTP -to $AdminMail -Body $Object -From denis.pasternak@hotmail.com -Subject $Object -Attachments $env:TEMP\$Object.txt } Catch {''}
      
      





, , .



 If ($AdminOnly -eq $True) { Write-Host "  AdminOnly -    " -ForegroundColor Yellow} else
      
      





.



 { $Username=((gwmi win32_computersystem -computer $Object -ErrorAction SilentlyContinue).UserName -split '\\')[1] if($username -ne $null)
      
      





, Active Directory, Email. Active Directory.



  { $Body = $Body $dispalyname = (Get-AdUser $username -properties DisplayName).DisplayName $email = (Get-AdUser $username -properties mail).mail sleep -Seconds 3
      
      





, $Body Active Directory.



 Send-MailMessage -SmtpServer $SMTP -Body ( ' ' + $Dispalyname + ' ' + $Body | out-string ) -To $email -From $AdminMail -Subject $Object -Attachments $env:TEMP\$Object.txt -Encoding Unicode
      
      





, , .



  } } } else{ } } else { (Write-Output ($Object + ' ' + (Get-Date).ToString()) | Add-Content $env:TEMP\Offline.txt)} }
      
      





.



 $OU= $null $RemoteComputer = $null $Hosts = $nul
      
      





«HomePage» Active Directory. , .



 Get-Content $env:TEMP\Online.txt | Set-ADComputer -HomePage 'pass' }
      
      





, , ( ), . $TargetFile – .



 Function Remove-AuditFiles { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetFile ) Get-Content -Path "$env:TEMP\$Path" | %{Remove-Item $PSItem} }
      
      





HomePage Active Directory. OU. -.



 Function Reset-AuditComputers { [CmdletBinding(SupportsShouldProcess=$True)] Param ( [String]$TargetOU ) Get-ADComputer -Filter * -SearchBase $TargetOU -Properties * | Set-ADComputer -HomePage 'notpass' '' | Set-Content -Path $env:TEMP\Online.txt }
      
      








All Articles