Advertisement
TDiff

WMI Simplified Commands - Distant Computers Managment

Sep 21st, 2018
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Author       : TDiff
  2. # Purpose      : Simplified WMI Commands to manage distant computers
  3. # Requirements : Launch powershell with credentials having WMI privileges
  4.  
  5. ####################################################
  6. ###################### Infos  ######################
  7. ####################################################
  8.  
  9. echo "DistantTools loaded.`n"
  10.  
  11. echo "Commands :`n"
  12. echo "* Distant Powershell :";
  13. echo "    - Execute-DistantCommand ComputerName `"Commands`"`n";
  14. echo "* Distant Services Managment :";
  15. echo "    - Get-DistantService ComputerName `"ServiceNa*`"";
  16. echo "    - Start-DistantService ComputerName `"ServiceNa*`"";
  17. echo "    - Stop-DistantService ComputerName `"ServiceNa*`"`n";
  18. echo "* Distant Processes Managment :";
  19. echo "    - Get-DistantProcess ComputerName `"ProcessNa*`"";
  20. echo "    - Start-DistantProcess ComputerName `"ProcessNa*`"";
  21. echo "    - Stop-DistantProcess ComputerName `"ProcessNa*`"`n";
  22. echo "* System Informations :";
  23. echo "    - Get-DistantSystemInfos ComputerName";
  24. echo "    - Get-DistantCompressedFiles ComputerName`n";
  25.  
  26. ###################################################################
  27. ###################### Powershell Execution  ######################
  28. ###################################################################
  29.  
  30. # Remove comments and linefeeds of a script and return a string object
  31. function Remove-Comments {
  32.     [CmdletBinding(DefaultParameterSetName='FilePath' )]
  33.     Param (
  34.             [Parameter(Position=0,Mandatory=$True,ParameterSetName='FilePath' )] [ValidateNotNullOrEmpty()] [String]$Path,
  35.             [Parameter(Position=0,ValueFromPipeline=$True,Mandatory=$True,ParameterSetName='ScriptBlock')] [ValidateNotNullOrEmpty()]
  36.             [ScriptBlock]$ScriptBlock
  37.           )
  38.     Set-StrictMode -Version 2;
  39.     if ($PSBoundParameters['Path']) {
  40.         gci $Path -ErrorAction Stop | Out-Null;
  41.         $ScriptBlockString=[IO.File]::ReadAllText((Resolve-Path $Path));
  42.         $ScriptBlock=[ScriptBlock]::Create($ScriptBlockString);
  43.     } Else { $ScriptBlockString=$ScriptBlock.ToString() }
  44.     $Tokens=[System.Management.Automation.PSParser]::Tokenize($ScriptBlock,[Ref]$Null) | Where{ $_.Type-ne'Comment' };
  45.     $StringBuilder=New-Object Text.StringBuilder;
  46.     $CurrentColumn=1;
  47.     $NewlineCount=0;
  48.     foreach($CurrentToken in $Tokens) {
  49.         if (($CurrentToken.Type -eq 'NewLine') -or ($CurrentToken.Type -eq 'LineContinuation')){
  50.             $CurrentColumn=1;
  51.             if ($NewlineCount -eq 0) { $StringBuilder.AppendLine()|Out-Null }
  52.             $NewlineCount++
  53.         } else {
  54.             $NewlineCount=0;
  55.             if (($CurrentColumn -lt $CurrentToken.StartColumn) -and ($CurrentColumn -ne 1)) { $StringBuilder.Append(' ') | Out-Null }
  56.             $CurrentTokenEnd = $CurrentToken.Start + $CurrentToken.Length-1;
  57.             if (($CurrentToken.Type -eq 'String') -and ($CurrentToken.EndLine -gt $CurrentToken.StartLine)) {
  58.                 $LineCounter = $CurrentToken.StartLine;
  59.                 $StringLines = $( -join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd] -split '`r`n');
  60.                 foreach ($StringLine in $StringLines) {
  61.                     $StringBuilder.Append($StringLine) | Out-Null;
  62.                     $LineCounter++;
  63.                 }
  64.             } else { $StringBuilder.Append(( -join $ScriptBlockString[$CurrentToken.Start..$CurrentTokenEnd])) | Out-Null }
  65.             $CurrentColumn = $CurrentToken.EndColumn
  66.         }
  67.     }
  68.     Write-Output([ScriptBlock]::Create($StringBuilder.ToString()))
  69. }
  70.  
  71. # Execute powershell command(s) or script (use Remove-Comments) on a distant computer
  72. function Execute-DistantCommand ([string] $ComputerName, [string] $Cmd) {
  73.     $ComputerName = [System.Net.Dns]::GetHostAddresses("$ComputerName")[0];
  74.     $sEncodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("&{" + $Cmd + "}"));
  75.     $oResult = iwmi -ComputerName $ComputerName -EnableAllPrivileges -Path win32_process -Name create -ArgumentList "powershell -NoE -enc $sEncodedCommand";
  76.     if ($oResult.ProcessId -gt 0) { return $true; } return $false;
  77. }
  78.  
  79. ################################################################
  80. ###################### Service Managment  ######################
  81. ################################################################
  82.  
  83. # Get service(s) from a distant computer
  84. function Get-DistantService ([string] $ComputerName, [string] $ServiceName) {
  85.     $ServiceName = $ServiceName -replace '\*','%';
  86.     $ComputerName = [System.Net.Dns]::GetHostAddresses("$ComputerName")[0];
  87.     return (gwmi -ComputerName $ComputerName -Query "SELECT * FROM Win32_Service WHERE Name LIKE '$ServiceName'");
  88. }
  89.  
  90. # Start a distant service
  91. function Start-DistantService ([string] $ComputerName, [string] $ServiceName) {
  92.     $aServices = Get-DistantService $ComputerName $ServiceName;
  93.     if ($aServices -ne $null) {
  94.         foreach ($oService in $aServices) {
  95.             if (!$oService.Started) {
  96.                 return $oService.StartService();
  97.             } else {
  98.                 echo "The service $ServiceName is already running on $ComputerName";
  99.             }
  100.         }
  101.     } else { echo "No service named $ServiceName has been found."; }
  102. }
  103.  
  104. # Stop a distant service
  105. function Stop-DistantService ([string] $ComputerName, [string] $ServiceName) {
  106.     $aServices = Get-DistantService $ComputerName $ServiceName;  
  107.     if ($aServices -ne $null) {
  108.         foreach ($oService in $aServices) {
  109.             if ($oService.Started) {
  110.                 return $oService.StopService();
  111.             } else {
  112.                 echo "The service $ServiceName is not running on $ComputerName";
  113.             }
  114.         }
  115.     } else { echo "No service named $ServiceName has been found."; }
  116. }
  117.  
  118.  
  119. ################################################################
  120. ###################### Process Managment  ######################
  121. ################################################################
  122.  
  123. # Get one or more distant process on a distant computer by name (accepts * wildcards)
  124. function Get-DistantProcess ([string] $ComputerName, [string] $ProcessName) {
  125.     $ProcessName = $ProcessName -replace '\*','%';
  126.     $ComputerName = [System.Net.Dns]::GetHostAddresses("$ComputerName"[0]);
  127.     return (gwmi -ComputerName $ComputerName -Query "SELECT * FROM win32_process WHERE Name LIKE '$ProcessName'");
  128. }
  129.  
  130. # Start a process on a distant computer
  131. function Start-DistantProcess ([string] $ComputerName, [string] $ProcessName) {
  132.     $ComputerName = [System.Net.Dns]::GetHostAddresses("$ComputerName")[0];
  133.     return (iwmi –ComputerName $ComputerName -Class win32_process -Name create -ArgumentList "$ProcessName");
  134. }
  135.  
  136. # Stop one or more processes on a distant computer (accepts * wildcards)
  137. function Stop-DistantProcess ([string] $ComputerName, [string] $ProcessName) {
  138.     $oProcesses = Get-DistantProcess $ComputerName $ProcessName
  139.    
  140.     if ($oProcesses -ne $null) {
  141.         foreach ($oProcess in $oProcesses) {
  142.             try {
  143.                 $sName = $oProcess.Name;
  144.                 $iRetVal = $oProcess.terminate();
  145.                 $iPID = $oProcess.handle;
  146.             } catch {
  147.                 $sName = "null";
  148.                 $iRetVal = "-1";
  149.                 $iPID = "-1";
  150.             }
  151.              
  152.             if($iRetVal.returnvalue -eq 0) {
  153.                 Write-Host "The process $sName `($iPID`) terminated successfully"
  154.             }
  155.             else {
  156.                 Write-Host "The process $sName `($iPID`) termination has some problems"
  157.             }
  158.         }
  159.     } else { echo "No process with this name has been found."; }
  160. }
  161.  
  162. #################################################################
  163. ###################### System Informations ######################
  164. #################################################################
  165.  
  166. # Get Operating System infos from a distant computer
  167. function Get-DistantSystemInfos ([string] $ComputerName) {
  168.     $ComputerName = [System.Net.Dns]::GetHostAddresses("$ComputerName")[0];
  169.     return (gwmi -ComputerName $ComputerName -Class Win32_OperatingSystem | Select-Object -Property *);
  170. }
  171.  
  172. # Get the list of compressed files on a distant computer
  173. function Get-DistantCompressedFiles ([string] $ComputerName) {
  174.     $ComputerName = [System.Net.Dns]::GetHostAddresses("$ComputerName")[0];
  175.     return (gwmi -ComputerName $ComputerName -Class CIM_DataFile -Filter "Compressed = 'True'");
  176. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement