Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

changing powershell output

$
0
0
$ServerListFile = "C:\Servers.txt"  
$ServerList = Get-Content $ServerListFile -ErrorAction SilentlyContinue 
$Result = @() 
ForEach($computername in $ServerList) 
{

$AVGProc = Get-WmiObject -computername $computername win32_processor | 
Measure-Object -property LoadPercentage -Average | Select Average
$OS = gwmi -Class win32_operatingsystem -computername $computername |
Select-Object @{Name = "MemoryUsage"; Expression = {“{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }}
$vol = Get-WmiObject -Class win32_Volume -ComputerName $computername -Filter "DriveLetter = 'C:'" |
Select-object @{Name = "C PercentFree"; Expression = {“{0:N2}” -f  (($_.FreeSpace / $_.Capacity)*100) } }

$operatingSystem = Get-WmiObject -computername $computername Win32_Service | select-object Name, State | where {$_.Name -eq "ALG"} 

$result += [PSCustomObject] @{ 
    ServerName = "$computername"
    CPULoad = "$($AVGProc.Average)%"
    MemLoad = "$($OS.MemoryUsage)%"
    CDrive = "$($vol.'C PercentFree')%"
    Uptime = "$operatingsystem"
}
$Outputreport = "<HTML><TITLE> Server Health Report </TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Server Health Check </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=White align=center><TD><B>Server Name</B></TD><TD><B>Avrg.CPU Utilization</B></TD><TD><B>Memory Utilization</B></TD><TD><B>Drive C Free Space</B></TD><TD><B>Service</B></TD></TR>"

Foreach($Entry in $Result) 

    { 
      if(($Entry.CpuLoad) -or ($Entry.memload) -ge "80") 
      { 
        $Outputreport += "<TR bgcolor=White>" 
      } 
      else
       {
        $Outputreport += "<TR>" 
      }
      $Outputreport += "<TD>$($Entry.Servername)</TD><TD align=center>$($Entry.CPULoad)</TD><TD align=center>$($Entry.MemLoad)</TD><TD align=center>$($Entry.CDrive)</TD><TD align=leftr>$($Entry.Uptime)</TD></TR>" 
    }
 $Outputreport += "</Table></BODY></HTML>" 
    } 

$Outputreport | out-file "C:\test.html"
my question is how can i remove @{Name=ALG; State=Stopped} to just say running 

PS script Foreach / loop bypasses the first value on the list

$
0
0
The list is stored on a table when runs as SQL Server job, no problem if executed in PS ISE. Any help, thank you

How to install Pester on Windows 7 and PS 3.0

$
0
0

Hello,

How to install Pester on Windows 7 and PS 3.0?

PS C:\Windows\system32> $PSVersionTable

Name                           Value                                                                                   
----                           -----                                                                                   
PSVersion                      3.0                                                                                     
WSManStackVersion              3.0                                                                                     
SerializationVersion           1.1.0.1                                                                                 
CLRVersion                     4.0.30319.42000                                                                         
BuildVersion                   6.2.9200.22198                                                                          
PSCompatibleVersions           {1.0, 2.0, 3.0}                                                                         
PSRemotingProtocolVersion      2.2                                                                                     

PS C:\Windows\system32> Get-Module -ListAvailable|select-object -Property Name

Name                                                                                                                   
----                                                                                                                   
AppLocker                                                                                                              
BitsTransfer                                                                                                           
CimCmdlets                                                                                                             
ISE                                                                                                                    
Microsoft.PowerShell.Diagnostics                                                                                       
Microsoft.PowerShell.Host                                                                                              
Microsoft.PowerShell.Management                                                                                        
Microsoft.PowerShell.Security                                                                                          
Microsoft.PowerShell.Utility                                                                                           
Microsoft.WSMan.Management                                                                                             
PSDiagnostics                                                                                                          
PSScheduledJob                                                                                                         
PSWorkflow                                                                                                             
PSWorkflowUtility                                                                                                      
TroubleshootingPack                                                                                                    
AppvClient                                                                                                             
ThirdPartyNotice                                                                                                       
AzureInformationProtection                                                                                             

PS C:\Windows\system32> Import-Module Pester
Import-Module : The specified module 'Pester' was not loaded because no valid module file was found in any module
directory.
At line:1 char:1
+ Import-Module Pester
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (Pester:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
 
 
 
PS C:\Windows\system32> Install-Module Pester
Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
+ Install-Module Pester
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Install-Module:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Thanks,

Vladimir

Calling attributes of objects returned by Get-AzureADAuditSignInLogs

$
0
0

Hi,

I've written a script to pull sign-in logs for Azure AD guest user accounts from the past 90 days. I'm struggling to figure out how to pull specific attributes from the sign-in log entries, and it's just returning the whole object. Can anyone point me in the right direction please?

$queryStartDateTime = (Get-Date).AddDays(-90)
$queryStartDateTimeFilter = '{0:yyyy-MM-dd}T{0:HH:mm:sszzz}' -f $queryStartDateTime

Connect-AzureAD
$guestUsers = Get-AzureADUser -Filter "UserType eq 'Guest' and AccountEnabled eq true"
foreach ($guestUser in $guestUsers) {
    $guestUserSignIns = Get-AzureADAuditSignInLogs -Filter "UserID eq '$($guestUser.ObjectID)' and createdDateTime ge $queryStartDateTimeFilter"
    if ($guestUserSignIns -eq $null) {
        Write-Output "No logins for $guestUser.displayname within the past 90 days"
    } else {
        foreach ($guestUserSignIn in $guestUserSignIns) {
            Write-Output "$guestUserSignIn.UserDisplayName logged into $guestUserSignIn.AppDisplayName on $guestUserSignIn.CreatedDateTime from IP $guestUserSignIn.IpAddress"
        }
    }
}

Thanks

How to get NIC port number and connection type (copper/fiber)

$
0
0
I have tried a long list of powershell cmdlets, WMI calls, config files, etc and no joy on getting the simplest of things from the NIC. I am down to getting the NIC port number (active) and Port Type (copper, fiber, other)

Any ideas?

Thx

Run PS script of PS5 in PS7

$
0
0

I try to run script below in PS5 working but get error in PS7. Any suggestion? Thanks

Line |
   7 |  $Form.Size = '745,1000'
     |  ~~~~~~~~~~~~~~~~~~~~~~~
     | Exception setting "Size": "Cannot convert the "745,1000" value of type "System.String" to type
     | "System.Drawing.Size"."

[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
[System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')

$Form        = New-Object System.Windows.Forms.Form
$DataGridView= New-Object System.Windows.Forms.DataGridView

$Form.size = New-Object System.Drawing.Size(745,1000)
$Form.StartPosition = 'Manual'
$Form.Location = New-Object System.Drawing.Point(0,0)
$Form.MaximizeBox = $False
$Form.TopMost = $True

$DataGridView.Size = New-Object System.Drawing.Size(720,875)
$DataGridView.Location = New-Object System.Drawing.Point(5, 50)
$DataGridView.ColumnHeadersHeight = 50
$DataGridView.RowHeadersVisible = $False
$DataGridView.BorderStyle = 'Fixed3D'
$DataGridView.ReadOnly = $True
$DataGridView.EnableHeadersVisualStyles = $False

$Form.Controls.Add($DataGridView)
$Form.ShowDialog() | Out-Null


PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADUser

$
0
0

Hi All,

I get PositionalParameterNotFound error while executing the below code. Please help me.

$b = get-date "17-Feb-2020"
Get-ADUser - filter {whenChanged - le $b} -Server "vsat.kunder.com" -SearchBase "OU=TPA Accounts,OU=User Directory,DC=vsat,DC=kunder,DC=com" -Properties shellGGDComputerUserId,enabled,DN,whenChanged|Select-Object shellGGDComputerUserId,enabled,DN,whenChanged| Export-Csv C:\Apps\Data\VSAT.csv -Append 
(Get-ADUser - filter {whenChanged - le $b} -Server "vsat.kunder.com" -SearchBase "OU=TPA Accounts,OU=User Directory,DC=vsat,DC=kunder,DC=com" -Properties shellGGDComputerUserId |Select-Object shellGGDComputerUserId).count


Get AD snapshot for a specific date using Powershell

$
0
0

Hi all. Is there way to generate the AD report for a specific date using powershell. I want to see all the user details as on 17th Feb 2020. As we have already crossed 17th Feb can we expect the powershell to generate the report of all the Users that were on 17th Feb 2020. Please let me know.

Example: Something like below.

$b= get-date  "17-Feb-2020"

Get-ADUser -Filter  -{whenchanged -le $b}


Split Members to different columns

$
0
0

Hello, 

I am trying to pull the list of Members for a ADObject Named Contacts , when i am trying to pull the contacts it is showing up in the single column

I need to split the members alone to different columns and also want to get the managers of the DL . 

I am using two different scripts to get the information using the following and need to make them into one script to split the members of the DL in to same sheet and members 

Get-ADobject -LDAPfilter "objectClass=contact" -Properties objectClass,givenName,cn,displayName,Name,mail,mailNickName,sn,distinguishedName,whenCreated,whenChanged,manager,managedby,memberOf,msExchCoManagedByLink | 
Select-Object name,objectClass,givenName,cn,displayName,mail,mailNickName,sn,distinguishedName,whenCreated,whenChanged,manager,
managedby,@{n='memberOf';e={(($_.memberOf).split(",") |where-object {$_.contains("CN=")}).replace("CN=","")-join ','}},@{Name="msExchCoManagedByLink";Expression ={(($_.msExchCoManagedByLink).split(",")|
 where-object {$_.contains("CN=")}).replace("CN=""")-join ','}}|Export-Csv C:\Temp\contact.csv -Append -NoTypeInformation

$csv=Import-Csv C:\Temp\contactsdl.csv
foreach($users in $csv)
{
Get-ADGroup -Identity $users.memberOf -Properties displayname,enabled,GroupCategory,mail,description,info,manager,managedby,members,msExchCoManagedByLink,distinguishedName,kPMG-User-GOAccountType | 
Select-Object -Property sAMAccountName,displayname,enabled,distinguishedName,kPMG-User-GOAccountType,GroupCategory,mail,description,info,manager,
managedby,@{Name="Members"; Expression ={(($_.Members).split(",") | where-object {$_.contains("CN=")}).replace("CN=","")-join ','}},@{Name="msExchCoManagedByLink";Expression ={(($_.msExchCoManagedByLink).split(",")| where-object {$_.contains("CN=")}).replace("CN=","")-join ','[5]}}|Export-Csv C:\Temp\contactsdlinfo1.csv -Append -NoTypeInformation
}


How to Create Teams for groups in office 365 as a bulk?

$
0
0

HI.

I tried to create teams for groups that i am having already in my office 365 tenant. It can be done manually by going to the group and then clicking on create team. But in my case I am having more than 1300 groups in my tenant and I need to create teams for each of them. I’ll will take too much time and will be exhaustive to create teams for groups by above said way. Is there any way to create team for each group that I have as a bulk using powershell? I searched but coulsnt find any answer and tried alone but failed to perform that as a bulk.

Is there any possible way to do this.

MSEdgeChromium launch from powershell with hwdrm options enabled.

$
0
0

Stuck at launching MSEdgeChromium launch from powershell with hwdrm options enabled.

Intent is to run the below command

Start-Process msedge.exe  --disable-features=msDisablePlayReadyHardwareDrm25668132

Is this possible, tried few options, doesnt seem to work.


Regards, Kishore

Get-ADComputer foreach loop error

$
0
0

COuld any one help on below script I get error : 

Script : 

 

$comps = Get-Content -Path C:\Users\adey\Desktop\computers.txt

foreach ($comp in $comps)

{  

$compdata = get-adcomputer $comp -properties PasswordLastSet |ft Name,PasswordLastSet

   write-host "$comp" 
   Write-Host "$compdata"

   }

-----------------------------------------------------------------------------------------------------------------------------------

Out Put : 

PS H:\> S:\Ares\GetLastPwdChange.ps1

-----------------------------------------------------------------------------------------------------------------------------------

I'm new to PS. Could any one please suggest correction on this script

Convert Strings To Numbers

$
0
0
I have some script that outputs string values where they should be numeric values (with 2 decimal places) and I just need the script to output them with numeric values instead of strings with quotation marks around them.  Please help.

All Project Files are here.
https://mega.nz/file/4tckTQSB#voXExrndNk_PvDMC8880XjioVl946FVAu_i_uRZ4HZ0

Here's a video explaining how it works.
https://www.screencast.com/t/beLka3XBIdJr

The exported data needs to be in this format.
https://postimg.cc/dZLTcD0q

Thank you for your help.

Regards, PC User

Events are missing when if use Start-Job

$
0
0

Hello,

currently my script runs directly when api receive data. Script initializes by this command:

C:\ADSync\PS\main.ps1 -payload $payload -meta $meta -debugMode:$false

but now I don`t want wait when script will finish. And I want run script as job like this:

Start-Job -ScriptBlock {C:\ADSync\PS\main.ps1 -payload $args[0] -meta $args[1] -debugMode:$args[2] } -ArgumentList $payload, $meta, $false

In this way "job" become finish without any error. But my script generate events in event log for each step. If it runs as job, there is not event in event log and in other way, there is events when scripts is initializing directly from api.

Sample how errors are creating:

Write-EventLog -LogName $LogName -Source "Main Script" -EventID 4 -EntryType Error -Message "ADSync found more than one account in Active Directory. `nID or Mail in not unique in domain."

Thank you.




Test-Path : Access is denied

$
0
0
I use Test-Path to check if a file exists but often get error "Test-Path : Access is denied". Is there other way to do that? Thanks.

Unexpected token error when executing script

$
0
0

Hello All,

I'm having issues running a script and I've just included the relevant snippets below..

Below are variables declared and the assigned values.

$path = "\\abcdef.eu.domain.com\Reports"
$mp_address = "server.domain.com"
$site_code = "PR2"

The script throws an error a

$path\ccmsetup.exe /mp:$mp_address SMSSITECODE=$site_code

Error output below :

PS C:\Users\M123\Documents> .\SCCM_Client.ps1
At C:\Users\M123\Documents\SCCM_Client.ps1:87 char:7
+     $path\ccmsetup.exe /mp:$mp_address SMSSITECODE=$site_code
+          ~~~~~~~~~~~~~
Unexpected token '\ccmsetup.exe' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

Any advice please?

Full script is available at the below location

https://gallery.technet.microsoft.com/SCCM-Client-Health-Check-7a17d672#content

Thank You.

SAMUEL


SamSV

Installing OpenSSHUtils module in PS.

$
0
0

Hello!

  May someone help me with this error?

PS C:\temp> Import-Module C:\temp\opensshutils.1.0.0.1\OpenSSHUtils.psd1
PS C:\temp> Get-Command -Module OpenSSHUtils

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Enable-Privilege                                   1.0.0.1    OpenSSHUtils
Function        Get-UserAccount                                    1.0.0.1    OpenSSHUtils
Function        Get-UserSID                                        1.0.0.1    OpenSSHUtils
Function        Repair-AuthorizedKeyPermission                     1.0.0.1    OpenSSHUtils
Function        Repair-FilePermission                              1.0.0.1    OpenSSHUtils
Function        Repair-SshdConfigPermission                        1.0.0.1    OpenSSHUtils
Function        Repair-SshdHostKeyPermission                       1.0.0.1    OpenSSHUtils
Function        Repair-UserKeyPermission                           1.0.0.1    OpenSSHUtils
Function        Repair-UserSshConfigPermission                     1.0.0.1    OpenSSHUtils

PS C:\temp> Register-PSRepository -Name 'localrepo' -SourceLocation 'C:\temp\opensshutils.1.0.0.1' -InstallationPolicy Trusted
PS C:\temp> Get-PSRepository

Name                      InstallationPolicy   SourceLocation
----                      ------------------   --------------
PSGallery                 Trusted              https://www.powershellgallery.com/api/v2
localrepo                 Trusted              C:\temp\opensshutils.1.0.0.1

PS C:\temp> Install-Module -Force OpenSSHUtils -Scope AllUsers -RequiredVersion 1.0.0.1 -Repository 'localrepo'
PackageManagement\Install-Package : No match was found for the specified search criteria and module name 'OpenSSHUtils'. Try
Get-PSRepository to see all available registered module repositories.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.2.4\PSModule.psm1:9709 char:34+ ... talledPackages = PackageManagement\Install-Package @PSBoundParameters+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Exception+ FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage


Doria

How to convert Nested data into json data using Powershell

$
0
0

Hi,

I am trying to convert below formatted data into json data using below power command but i am not able to see nested json data properly converted and it showing empty.

Example: store nested data is available in object data but when we converted to json it is showing empty. Can you please help how to display store data as well. 

$json = @'
{"value":[{"id":"/subscriptions/xxxxxxxxx/resourceGroups/xxxxxx/providers/Microsoft.DataFactory/factories/xxxx/linkedservices/xxxx
xxx","name":"xxxxxx","type":"Microsoft.DataFactory/factories/linkedservices","properties":{"annotations":[],"type":"AzureKeyVault","typeProperties":{"baseUrl":"https://ak
xxxxxx.vault.azure.net/"}},"etag":"xxxxx"},{"id":"/subscriptions/xxxxx/resourceGroups/xxxxx/providers/
Microsoft.DataFactory/factories/xxxxx/linkedservices/xxxx","name":"xxxxx","type":"Microsoft.DataFactory/factories/linkedservices","properties":{"an
notations":[],"type":"AzureDataLakeStore","typeProperties":{"dataLakeStoreUri":"adl://xxxxx.azuredatalakestore.net/","servicePrincipalId":"xxxxxxx","servicePrincipalKey":{"type":"AzureKeyVaultSecret","store":{"referenceName":"xxxxx","type":"LinkedServiceReference"},"secretName":"data-client-secret"},"tenant":"xxxxx","subscriptionId":"xxxxx","resourceGroupName":"xxxxxx"}},"etag":"xxxxxx"}]}
'@ | ConvertFrom-Json

$json.value | Where-Object{$_.properties.type -eq "AzureDataLakeStore"} | ConvertTo-Json

Output:

{
    "id":  "/subscriptions/xxxxx/resourceGroups/xxxxx/providers/\r\nMicrosoft.DataFactory/factories/xxxxx/linkedservices/xxxx",
    "name":  "xxxxx",
    "type":  "Microsoft.DataFactory/factories/linkedservices",
    "properties":  {
                       "an\r\nnotations":  [

                                           ],
                       "type":  "AzureDataLakeStore",
                       "typeProperties":  {
                                              "dataLakeStoreUri":  "adl://xxxxx.azuredatalakestore.net/",
                                              "servicePrincipalId":  "xxxxxxx\r\n",
                                              "servicePrincipalKey":  "@{type=AzureKeyVaultSecret; store=; secretName=data-client-secret}",
                                              "tenant\r\n":  "xxxxx",
                                              "subscriptionId":  "xxxxx",
                                              "resourceGroupName":  "xxxxxx"
                                          }
                   },
    "etag":  "xxxxxx\r\n"
}


Routing and Remote Access Automated CSV

$
0
0
Hi all,

I was wondering if I could get some help on this script that I have been working on.

It's a small script and it works perfectly fine but the only issue I am having is getting the script to run by itself at a certain time.

The server that this will be running on will be a Windows Server 2012 R2. I have tried to add this script to the task scheduler and nothing has worked.

This happens even though I have told the Task Scheduler to run as an administrator.

The script I created is just a small script so HR can know who's really working from home and who's not, its basically an attendance sheet if you think of it.


Start-Process powershell -ArgumentList '-nonprofile -file C:\Users\lesliej\Desktop\VPN\working script.ps1' -verb RunAs
$startDate = Get-Date -Date "04/06/2020"
$endDate = Get-Date -Date "12/06/2020"
$Day = Get-Date -format "08:00:00"
$endDate = Get-Date -format "17:30:00"
$Path = "C:\Users\lesliej\Desktop\VPN\filelist.csv"
Get-RemoteAccessConnectionStatistics -StartDateTime $Day|Export-Csv "\\KL-FS01\Data\Home\LeslieJ\VPN List of users\June\VPN User List - $((Get-Date).ToString('dd-MM-yyyy - HH-mm-ss')).csv" -NoTypeInformation

Any help would be appreciated as this is getting really annoying having to do this manually.

PowerShell: Post Patching Server Validation Script

$
0
0
I've found a script online to help our organization check our server infrastructure after Windows Server Patching. This single script will look at and run against several windows servers. The code contained below has many customizations I added from the original author. What I am trying to learn to modify is listed below;
  • You'll see in the HTML output file, the script is looking for "Auto Services" I want to change this to reach out and check if certain critical services (pulled from like a text file) are in the "Running" status. If not, post the non-running services for that respected server to the output HTML file to display Red. This will give the admin the visual ability to apply a script to fix.

Here is my code;

PS C:\Windows\system32>
# Descritption : This {Service Report} PS script will check uptime, auto services and pending reboot and export result into HTML file.

cls
$comps = Get-Content 'D:\Post-Patching Validation\Serverlist.txt'
$total = $null
del 'D:\Post-Patching Validation\result.html'  -Force -ErrorAction SilentlyContinue
del 'D:\Post-Patching Validation\result.csv' -Force -ErrorAction SilentlyContinue
#$Now = Get-Date
$html = @'
<html><head><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'><title>Moffitt Application Validation</title><STYLE TYPE="text/css"><!--
td {
font-family: Tahoma;
font-size: 11px;
border-top: 1px solid #999999;
border-right: 1px solid #999999;
border-bottom: 1px solid #999999;
border-left: 1px solid #999999;
padding-top: 0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
}
body {
margin-left: 5px;
margin-top: 5px;
margin-right: 0px;
margin-bottom: 10px;

table {
border: thin solid #000000;
}
--></style></head><body><table width='100%'><tr bgcolor='#CCCCCC'><td colspan='7' height='25' align='center'><strong><font color="#003399" size="4" face="tahoma">Service Report </font></strong></td></tr></table><table width='100%'><tbody><tr bgcolor=#CCCCCC><td width='14%' height='15' align='center'> <strong> <font color="#003399" size="2" face="tahoma" >Server Name</font></strong></td><td width='23%' height='15' align='center'> <strong> <font color="#003399" size="2" face="tahoma" >Uptime</font></strong></td><td width='51%'height='15' align='center'> <strong> <font color="#003399" size="2" face="tahoma"  >Auto-Services</font></strong></td><td width='12%' height='15' align='center'> <strong> <font color="#003399" size="2" face="tahoma" >Pending Reboot</font></strong></td></tr>" </table><table width='100%'><tbody>
'@

Function Uptime($comp){
		function WMIDateStringToDate($Bootup) {
		 [System.Management.ManagementDateTimeconverter]::ToDateTime($Bootup)
		}
		$NameSpace = "Root\CIMV2"
        $wmi = [WMISearcher]""
      	$wmi.options.timeout = '0:0:15' #set timeout to 30 seconds
      	$query = 'Select * from Win32_OperatingSystem'
      	$wmi.scope.path = "\\$comp\$NameSpace"
		$wmi.query = $query
	    Try{
		    $wmiresult = $wmi.Get()
		    #$wmiresult
            foreach ($wmioutput in $wmiresult){
               $Bootup = $wmioutput.LastBootUpTime
               $LastBootUpTime = WMIDateStringToDate($Bootup)
			   $now = Get-Date
               $Reporttime = $now - $lastBootUpTime
               $d = $Reporttime.Days
               $h = $Reporttime.Hours
               $m = $Reporttime.Minutes
               $ms= $Reporttime.Milliseconds
               $a = "Up for: {0} days, {1} hours, {2:N0} minutes" -f $d,$h,$m
               return $a 
			}
		}
		Catch [Exception] {
    		$uperr = '<font color="#FF0000"> RPC Issue : </font>'+ $_
			return $uperr 
		}
	}

function Service($comp){
	#region Ignore 	
		$Ignore = @( 
		    'Microsoft .NET Framework NGEN v4.0.30319_X64', 
		    'Microsoft .NET Framework NGEN v4.0.30319_X86', 
		    'Performance Logs and Alerts', 
		    'Shell Hardware Detection', 
		    'Software Protection'; 
		)
	#endregione
	
		try {
			$autoservices = Get-WmiObject -Namespace 'root\cimv2' -Class Win32_Service -ComputerName $comp -ErrorAction Stop | Where {$_.StartMode -eq 'Auto' -and $Ignore -notcontains $_.DisplayName -and $_.State -ne 'Running'} | % {$_.Displayname}  # | FT Displayname -HideTableHeaders | Out-String  -Stream
			if ($autoservices -ne $null){  #Implement $? last error checking pending 
				foreach ($service in $autoservices) {
				$totalfailednew += $service
				$totalfailednew += " ; "
				}
			}
			else{
				$totalfailednew = "OK"
			}
			return $totalfailednew 
		}
		Catch [Exception] {
    		$serviceerr = '<font color="#FF0000"> RPC Issue : </font>'+ $_ 
			return $serviceerr
		}

	}

function PendingReboot ($comp) {
	process {
		try {
			$WMI_OS = ""
		  	$RegCon  = ""
			$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $comp -ErrorAction Stop
			if ($?){
	     	try{ 
				$RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"LocalMachine",$comp) 
			    If ($WMI_OS.BuildNumber -ge 6001){ 
					$RegValueSetupex = ""
					$RegValuePFRO2k8 = ""
					$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\") 
					$RegValueSetupex = $RegSubKeySM.GetValue("SetupExecute",$null) 
					if ($RegValueSetupex){
						$RegValueSetupex = $true
					}
					$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\") 
					$RegValuePFRO2k8 = $RegSubKeySM.GetValue("PendingFileRenameOperations",$null) 
					if ($RegValuePFRO2k8 ){
						$RegValuePFRO2k8  = $true
					}
					$RegCon.Close()
					if ( $RegValueSetupex -eq $true -or $RegValuePFRO2k8 -eq $true){
						return '<font color="#FF0000">'+$true
					}
					else {
						return $false 							
					}
				}
	            else{   
					$RegValuePFRO2k3 = $false;
					$RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"LocalMachine","$comp") 
					$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\") 
					$RegValuePFRO2k3 = $RegSubKeySM.GetValue("PendingFileRenameOperations",$null) 
					$RegCon.Close()
					If ($RegValuePFRO2k3) { 
						return  '<font color="#FF0000">'+$true; 
					}
					else {
						return $false; 
					} 
				}
			}
			catch {
				return '<font color="#FFFF00">'+"Remote Registry Service KO"
			}
			}
			else {
	       		throw $error[0].Exception
	   		}
		}	
		catch {
				return '<font color="#FF0000">'+"RPC Issue" 		
		}
    }
}

$i=0 # for Progress bar
	
foreach($comp in $comps){
	$i++
	$ErrorActionPreference = "SilentlyContinue" 
	Write-Progress   -Activity "Server Health Check v1.0" -Status ("Checking : {0}" -f $comp) -PercentComplete ($i/$comps.count*100) -Id 0 
	$ErrorActionPreference = "Continue"
	#region Var_Nulling :p  
	$autoservices= $null
	$Reporttimestatus  = $null
	$service = $null;
	$services = $null;
	$totalfailednew = $null
	#endregion
	$Reporttimestatus = uptime -comp $comp
	$services = Service -comp $comp
	$pd = PendingReboot $comp
	$newobj = $null
	$newobj = new-object psobject
	$newobj | add-member -membertype noteproperty -name "Server" -value $comp 
	$newobj | add-member -membertype noteproperty -name "Uptime" -value $Reporttimestatus #-PassThru 
	$newobj | add-member -membertype noteproperty -name "AutoServices" -value $services 
	$newobj | add-member -membertype noteproperty -name "PendingReboot" -value $pd
	$newobj | ConvertTo-Csv -NoTypeInformation | Out-File "D:\Post-Patching Validation\result.csv" -Append
	$htmlserver = $newobj.Server
	$htmluptime = $newobj.Uptime
	$htmlautoservices = $newobj.AutoServices
	$htmlpendingreboot =  $newobj.PendingReboot
$current = "<tr bgcolor=#CCCCCC><td width='14%' align='center'>$htmlserver</td><td width='23%' align='center'>$htmluptime</td><td width='51%' align='center'>$htmlautoservices</td><td width='12%' align='center'>$htmlpendingreboot</td></tr>"
	$total += $current 
	#$newobj | ConvertTo-html -Fragment 
	#$newobj | ConvertTo-html -Fragment -CssUri D:\Post-Patching Validation\Style.css | Out-File D:\Post-Patching Validation\result.html -Append


}

$HTMLEnd = @"</div></body></html>"@

$MainHtml= $html + $total + $HTMLEnd
$MainHtml  | Out-File "D:\Post-Patching Validation\result.html" 

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>