PowerShell crea script automaticamente

Hola que tal ? He visto recientemente en el visor de sucesos un evento 4104 de Powe Shell que genera varios script . No se interpretar bien que es lo que hace . Alguien me puede orientar ? El scrip 4 de 4 dice esto :

Creando texto de bloque de script (4 de 4): r = $allRepairs[$i]; #get name and description of repair #don’t use DescriptionEx for unmanifested root causes SplitString $repair.Description ([ref]$Name) ([ref]$Desc) #add to outgoing param list $Params.value.Add(“RepairName”+$repairCount, $Name); $Params.value.Add(“RepairDescription”+$repairCount, $Desc); $Params.value.Add(“RepairID”+$repairCount, $repair.RepairID); }

#add security boundary safe data
$data = GetSBSData($Global:ndf.IncidentID)
$params.value.Add("SBSData", $data)

#keywords for escalation
$keywords = GetKeywords($RootCause.DescriptionEx);
if($keywords.Length -gt 0)
{
    $params.value.Add("Keywords", $keywords);
}

if(($LUACount -eq 1) -and ($elevateCount -eq 1))
{
    #return placeholder RC with mix of admin and LUA repairs
    return "{000000000-0000-0000-0000-000000000005}"
}
elseif($elevateCount -eq 1)
{
    #return placeholder RC with single elevation repair
    return "{000000000-0000-0000-0000-000000000002}"
}
elseif($elevateCount -eq 2)
{
    #return placeholder RC with two Admin repairs
    return "{000000000-0000-0000-0000-000000000004}"
}
elseif($LUACount -eq 1)
{
    #check whether the single repair is info only or help topic to use alternate root cause
    $repair = $LUARepairs[0];
    #########
    try { $uiInfo = $repair.UiInfo; } catch{ $uiInfo = $null }
    
    $repairFlags = $repair.Flags;

    if(($uiInfo -and ($uiInfo.Type -eq $UIT_HELP_PANE)) -or ($repairFlags -band $RF_INFORMATION_ONLY))
    {
        #return placeholder RC with single info only or help topic repair
        return "{000000000-0000-0000-0000-000000000006}"
    }
    else
    {
        #return placeholder RC with single LUA repair
        return "{000000000-0000-0000-0000-000000000001}"
    }
}
elseif($LUACount -eq 2)
{
    #return placeholder RC with two LUA repairs
    return "{000000000-0000-0000-0000-000000000003}"
}
elseif($localCount -eq 1)
{
    #return placeholder RC with a single Local user repair
    return "{000000000-0000-0000-0000-000000000007}"
}

return $null;

}

function CreateCab($FileList, $TargetFolder, $TargetCAB) {

$ddf = @" .OPTION EXPLICIT .Set CabinetNameTemplate=$TargetCAB .set DiskDirectoryTemplate=CDROM .Set CompressionType=MSZIP .Set UniqueFiles="OFF" .Set Cabinet=on .Set DiskDirectory1=$TargetFolder $($OFS=“rn”; $FileList) "@;

$ddfFile = "NetworkConfiguration.ddf";

$ddf | Out-File $ddfFile -Encoding Ascii;
makecab /f $ddfFile;
$succeeded = $?;
#del $ddfFile;

return $succeeded;

}

function HereString($text) { $here = “@‘n" + $text + "n’@” return $here }

#$Commands is an array of hash pairs “command”: the command line to run, “file”: the target filename, #appended to the end of the command line function AddCommandOutputToSession($Commands, $TargetCABName, $ReportHeader) { #lets create the temporary folder for all this data $tempFolder = [System.IO.Path]::GetTempFileName(); del $tempFolder; #delete the file mkdir $tempFolder; #make it into a folder

#go into the folder to avoid leaving side-effect files behind
pushd $tempFolder;

#run the commands in the list
$fileList = @();
$timeMeasure = @(); #keeps track of length of execution for commands
foreach($item in $Commands)
{
    #measure time it takes to execute commands
    $start = get-date

    $targetFile = $tempFolder + "\" + $item["file"];
    $cmdline = $item["command"] + " " + (HereString $targetFile);
    $err = $($out = Invoke-expression  $cmdline) 2>&1;
    if(!$err)
    {
        #the call succeeded, add the target file to the list to CAB
        $fileList += @($item["file"]);
    }
    $runtime = (get-date) - $start;
    $timeMeasure += @(@{"command"=$item["command"];"runtime (ms)"=$runtime.TotalMilliseconds});
}

#create a CAB of the files
$start = get-date
if(CreateCab ($fileList) (".\") ($TargetCABName))
{
    $runtime = (get-date) - $start;
    $timeMeasure += @(@{"command"="makecab.exe";"runtime (ms)"=$runtime.TotalMilliseconds});
    Update-DiagReport -ID NetworkData -name $ReportHeader -File ($tempFolder + "\"+ $TargetCABName)
}

$timeMeasure | convertto-xml | Update-DiagReport -ID ConfigCollectionRuntime -Name "Data Collection Time" -Verbosity Debug

popd;

remove-item -recurse -force $tempFolder;

}

function AddNetworkInfoToSession() { Write-DiagProgress -activity $localizationString.progress_Collecting_Config

$commands = @(
    @{"command"="ipconfig /all >"; "file"="ipconfig.all.txt"};
    @{"command"="route print >"; "file"="route.print.txt"};
);

AddCommandOutputToSession ($commands) ("NetworkConfiguration.cab") ($localizationString.OtherNetworkConfigReportName);

Write-DiagProgress -activity " "

}

function GetUniqueFileName($IncidentID, $Operation) { #get temp folder location $tempFolder = get-childitem -path env:temp

 #strip { } at the ends of the incident ID GUID, generate file name
 $uniqueFileName = $tempFolder.Value+"\"+$IncidentID.Substring(1,$IncidentID.Length-2)+"." + $Operation

#append whether it's admin or not (to avoid name clashes, as op count resets after elevation)
$isAdmin = IsAdmin
if($isAdmin)
{
    $uniqueFileName += ".Admin";
}

#initialize or increment op count
if($Global:OpCount -eq $null)
{
   $Global:OpCount = 0
}
else
{
    $Global:OpCount++;
}

$uniqueFileName += "." + $Global:OpCount + ".etl";

return $uniqueFileName

}

function AddTraceFileToSession($Ndf, $Name, $Operation) { #NDF flushes the trace file every time we query for it #A unique name needs to be generated each time we add the file to the report, #otherwise it will overwrite the existing ETL file #The naming convention is as follows: # IncidentID.Operation([Admin]).Counter.etl

Write-DiagProgress -activity $localizationString.progress_Collecting_Logs

$traceFile = $Ndf.TraceFile
if($traceFile)
{
    #get unique name
    $newFileName = GetUniqueFileName $Ndf.IncidentID $Operation

    #rename file
    move "$traceFile" "$newFileName"
    #add it to the report
    Update-DiagReport -ID NDFDebugLog -name $Name -File $newFileName
    #add HC events to the report
    AddNewHCEventsToSession $newFileName
    # delete the file name edited by Claton 
    #del "$newFileName"
}
else
{
    $Name | convertto-xml | Update-DiagReport -id TraceFile -name "Trace File" -description "Failed while trying to retrieve the trace file for the session." -verbosity Debug
}

Write-DiagProgress -activity " "

}

function AddNewHCEventsToSession($TraceFile) { #we keep track of all the events added to the report, so we don’t add duplicates (this function is called multiple times) if($Global:ReportEvents -eq $null) { $Global:ReportEvents = @{}; }

$script:ExpectingException = $false

&{
    $script:ExpectingException = $true
    $events = get-winevent -path $TraceFile -Oldest -FilterXPath "*[System[Provider[@Name='Microsoft-Windows-Diagnostics-Networking'] and (EventID=6100)]]" -ErrorAction SilentlyContinue
    $script:ExpectingException = $false
    foreach($event in $events)
    {
        #events indexed by time they were emitted
        if(($event -ne $null) -and !$Global:ReportEvents.ContainsKey($event.TimeCreated))
        {
            #Add helper class name to title so that it's easily distinguishable in the report without having to expand it
            $eventTitle = [System.String]::Format([System.Globalization.CultureInfo]::InvariantCulture, $localizationString.HelperClassEventNameWithHCName,
                                [System.Globalization.CultureInfo]::CurrentUICulture.TextInfo.ToTitleCase($event.Properties[0].Value));

            "<Objects><Object Type=""System.String""><PRE><![CDATA["+$event.Message +"]]></PRE></Object></Objects>" | Update-DiagReport -id DiagInformation -name $eventTitle
            $Global:ReportEvents.Add($event.TimeCreated, $event)
        }
    }
}
trap [Exception]
{
    if($script:ExpectingException)
    {
        "No admin helper class events were found." | convertto-xml | Update-DiagReport -id DiagEvents -name "Helper Class Events" -verbosity Debug
    }
    else
    {
        "Exception: " + $_.Exception.GetType().FullName + " Message: " + $_.Exception.Message  | convertto-xml | Update-DiagReport -id DiagEventsFailure -name "Helper Class Events" -description "Failed while retrieving helper class events." -verbosity Debug
    }
    return
}

}

function LoadResourceString($ResourceString) { [string]$bufStr = $null $dll = “NetworkDiagnosticSnapIn.dll”

try
{
    RegSnapin $dll
    
    $bufferSize = 512
    $buffer = New-Object System.Text.StringBuilder $bufferSize
    [Microsoft.Windows.Diagnosis.Network.NativeShellMethods]::SHLoadIndirectString($ResourceString, $buffer, $bufferSize, [IntPtr]::Zero)
    $bufStr = $buffer.ToString()
}
finally
{
    UnregSnapin $dll
}

return $bufStr

}

function IsDPSStarted() { $dpsService = get-service “DPS” if($dpsService) { if($dpsService.Status -ne “Running”) { return $false; } } return $true; }

function IsDPSDisabled() { $dpsService = gwmi win32_service -f “name=‘DPS’” if($dpsService) { if($dpsService.StartMode -eq “Disabled”) { return $true; } } return $false; }

function IsSafeMode() { [void] [Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”) return [System.Windows.Forms.SystemInformation]::BootMode -ne 0 }

function IsHelpTopicAllowed($Link) { $regValue = get-itemproperty -path hklm:\SYSTEM\CurrentControlSet\Control\NetDiagFx\Config\HelpTopic -name $Link -ErrorAction SilentlyContinue -ErrorVariable regError if($regValue) { # check the DWORD value (the key to the value is the Value name: i.e., $Link) # 1 - enabled # otherwise - disabled $filterValue = $regValue.$Link; if($filterValue -eq 1) { return $true; } else { return $false; } } elseif ($regError) { if(!($regError[0].CategoryInfo.Category -eq “InvalidArgument”) -and !($regError[0].CategoryInfo.Category -eq “ObjectNotFound”)) { " Warning: Unexpected error when reading Help Topic Cause key : " + $regError[0].CategoryInfo.Category | convertto-xml | Update-DiagReport -id UnexpectedRegError -name “Unexpected Registry Error” -verbosity Debug } return $false; } }

Id. de bloque de script: c15d75d0-11f6-4829-9f6f-71b66942878f Ruta de acceso: C:\Users\begoña\AppData\Local\Temp\SDIAG_32adf88f-e7dc-4f32-870f-69a5baf184a7\UtilityFunctions.ps1