Powershell: Get file- and foldersize for given path

Quick and dirty little thing I use to get the file- and foldersize for any given path.

# Get-pathsize.ps1
# Use: C:scriptsget-pathsize.ps1 -path <your-path>

param (
$path
)

try {
 Get-ChildItem $path -Hidden -ErrorAction Stop
}

catch {
 $_.exception
 break
}

$colItems = (Get-ChildItem $path -recurse | Measure-Object -property length -sum) 
[int]$size = [math]::round($colItems.sum /1MB, 2) 
write-host "Files and foldersize in $path is: $size MB"

-F

Windows: Server stuck in shutdown after installing patches

One of my servers in my labenvironment refused to gently reboot after installing a ton of patches that I.. uhm.. forgot to install.
The “restart-computer -computername DC1” cmdlet wouldn’t do anything, as it returns with : Restart-Computer : Failed to restart the computer dc1 with the following message: A system shutdown is in progress.

Figures, the server is physical, and about an hour drive away.

The (somewhat crude) solution:
Use PSkill.exe to kill the TRUSTEDINSTALLER process. (Note: this is not recommended, but what the hell, this is a testenvironment).

1. Download the utility here
2. Extract it somewhere, open a elevated CMDlet window, and CD yourself into the exctracted folder.
3. Use this command to kill the respective hangig process: pskill.exe \your-server your-process (In my case: pskill.exe DC1 TRUSTEDINSTALLER).

The server then booted after about a minute, and about 15 minutes later it was available through RDP.

-F

Windows: Modify Automatic (Delayed start) windows service thresholds

I wanted to modify the delayed start time threshold for one of my services.
If you want to tweak your delaytime, do the following in regedit:

1. Open Regedit.
2. Navigate to your service, in my case it was HKLMSYSTEMCurrentControlSetservicesPlexService
You should see that the “DelayedAutostart is set to 1.
3. To increase the default delay of 120 seconds, right click the registry key and add new key AutoStartDelay (DWORD (32-bit), like mine: HKLMSYSTEMCurrentControlSetservicesPlexServiceAutoStartDelay
4. Set the decimal to your default value. Like mine: 300
5. Reboot, and see if the service autostarts after x seconds.

– F

Windows: Autologon for Domain User

I have some machines in my lab at home that, due to heavy testing and other stuff, reboots often.
Some of my applications are dependent on the user beeing logged on to function properly – so instead of manually logging on each time my server boots, I fiddled around in registry to make the domain user log on automatically.

This, of course, is not recomended in any production environment, but for lab purposes, I find this trick very useful.

1. First, open regedit on the machine you want to fiddle with.
2. Navigate to HKLMSoftwareMicrosoftWindows NTCurrentVersionwinlogon
3. Make a backup of winlogon.
4. Change the following values (you may need to add some of them if they’re not present).

AutoAdminLogon = 1 (String Value Key) (0 means off, 1 means automatic)
DefaultUserName = Username (String Value Key)
DefaultPassword = Password (String Value Key)
DefaultDomainName = yourdomain.com (String Value Key) (Only needed if this computer has joined a domain)

4. Reboot

The user should now log on automatically.
As you see, the password is displayed in clear text, so beware.

– F

SCOM: DeltaSynchronization Error

This error appeared in out environment recently, and didn’t go away until we changed some configuration settings in a config file on all the management servers.

Symptoms:

  • EventID 29181 in the OpsMgr eventlog.
  • Newly pushed agents show up as “Not Monitored”
  • Changes you do to a Management Pack, ex. overriding a rule, does not work.
  • Discovery of new objects is insanely slow, or does not work all together.

Example Event: 

Log Name:      Operations Manager
Source:        OpsMgr Management Configuration
Event ID:      29181
Level:         Error
User:          N/A
Computer:      server.domain.com
Description:
OpsMgr Management Configuration Service failed to execute ‘DeltaSynchronization’ engine work item due to the following exception
Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.DataAccessOperationTimeoutException: Exception of type ‘Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.DataAccessOperationTimeoutException’ was thrown.
at Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.DataAccessOperation.ExecuteSynchronously(Int32 timeoutSeconds, WaitHandle stopWaitHandle)
at Microsoft.EnterpriseManagement.ManagementConfiguration.SqlConfigurationStore.ConfigurationStore.ExecuteOperationSynchronously(IDataAccessConnectedOperation operation, String operationName)
at Microsoft.EnterpriseManagement.ManagementConfiguration.SqlConfigurationStore.ConfigurationStore.WriteConfigurationDelta(IConfigurationDeltaDataSet dataSet)
at Microsoft.EnterpriseManagement.ManagementConfiguration.Engine.DeltaSynchronizationWorkItem.TransferData(String watermark)
at Microsoft.EnterpriseManagement.ManagementConfiguration.Engine.DeltaSynchronizationWorkItem.ExecuteSharedWorkItem()
at Microsoft.EnterpriseManagement.ManagementConfiguration.Interop.SharedWorkItem.ExecuteWorkItem()
at Microsoft.EnterpriseManagement.ManagementConfiguration.Interop.ConfigServiceEngineWorkItem.Execute()

 

We went as far as opening a support case with Microsoft.
In the end, we managed to fix the problem, changing some timeoutvalues in the Config Service configfile on each and every Management Server.

Check workitem duration:

First of all, run this query against the OperationsManager database to check if you see errors in the WorkItemState table;

SELECT * FROM cs.WorkItem WHERE WorkItemName = ‘DeltaSynchronization’

If you see alot of 10’s and not all 20’s, you have a problem with syncronization.
The states are:
WorkItemStateId WorkItemStateName
1 Running
10 Failed
12 Abandoned
15 Timed out
20 Succeeded

How to fix the issue:

You may stumble upon this support tip if you did what we did – google’d the crap out of the problem: http://blogs.technet.com/b/momteam/archive/2013/01/29/support-tip-config-service-deltasynchronization-process-fails-with-timeout-exception.aspx

This provides most people with a fix to the problem, but we had to change another parameter to get stuff working again.
In addition to thanging the <Category Name=”Cmdb”> TimeoutSeconds values, we needed to change the <Category Name=”ConfigStore”> TimeoutSeconds values.

Our config now looks like this:

<Category Name=”Cmdb”>
<OperationTimeout DefaultTimeoutSeconds=”300″>
<Operation Name=”GetEntityChangeDeltaList” TimeoutSeconds=”300″ />

<Category Name=”ConfigStore”>
<OperationTimeout DefaultTimeoutSeconds=”300″>

After changig this on EVERY management server, and restarting the Config Service, things started to work again.

SCOM: Get Subscriber in Subscription

This little thing will search through, and get all subscribers containing your searchword in any subscription you may have set up in SCOM.

param(
    [String]$searchword
    )

$sub = Get-SCOMNotificationSubscription | select displayname,torecipients

write-host "Searchword: ""$searchword"" exists in the following subscriptions:"
foreach ($s in $sub){
    $recipient = $s.torecipients.name
    if ($recipient -like "$searchword"){
    write-host ""$s.displayname""
        }
    }

– F

SCOM: Get Maintenance Mode History

I use this query whenever I need to investigate Maintenace Mode history for SCOM agents.

USE OperationsManagerDW
SELECT ManagedEntity.DisplayName, MaintenanceModeHistory.*
FROM ManagedEntity WITH (NOLOCK) 
INNER JOIN
MaintenanceMode ON ManagedEntity.ManagedEntityRowId = MaintenanceMode.ManagedEntityRowId 
INNER JOIN
MaintenanceModeHistory ON MaintenanceMode.MaintenanceModeRowId = MaintenanceModeHistory.MaintenanceModeRowId
where DisplayName Like '%SERVERNAME%'
order by ScheduledEndDateTime

– F

Useful SQL queries for OpsMgr DB

Here are some of the SQL scripts I usually use in case of… whatever.
Many of these must be credited to Kevin Holman

Set ALL agents to Remotely Managable

UPDATE MT_HealthService 
SET IsManuallyInstalled=0 
WHERE IsManuallyInstalled=1

Get Agents not Remotely Managable

select bme.DisplayName from MT_HealthService mths 
INNER JOIN BaseManagedEntity bme on bme.BaseManagedEntityId = mths.BaseManagedEntityId 
where IsManuallyInstalled = 1

Set Agent Remotely Managable

UPDATE MT_HealthService 
SET IsManuallyInstalled=0 
WHERE IsManuallyInstalled=1 
AND BaseManagedEntityId IN 
(select BaseManagedEntityID from BaseManagedEntity 
where BaseManagedTypeId = 'AB4C891F-3359-3FB6-0704-075FBFE36710' 
AND DisplayName = '-- Servername Here --')

Get Unix Duplicates (Run if the *Nix agent view in console fails)

DECLARE @NeededTypeName NVARCHAR(256)
DECLARE @ManagedTypeIdForManagedEntitiesByManagedTypeAndDerived UNIQUEIDENTIFIER
SET @NeededTypeName = 'Microsoft.Unix.OperatingSystem'
SET @ManagedTypeIdForManagedEntitiesByManagedTypeAndDerived = (
SELECT ManagedTypeId
FROM ManagedType
WHERE TypeName = @NeededTypeName
)

SELECT
[ManagedEntityGenericView].[Id],
[ManagedEntityGenericView].[Name],
[ManagedEntityGenericView].[Path],
[ManagedEntityGenericView].[FullName],
[ManagedEntityGenericView].[LastModified],
[ManagedEntityGenericView].[TypedManagedEntityId],
NULL AS SourceEntityId

FROM dbo.ManagedEntityGenericView
INNER JOIN (
SELECT DISTINCT [BaseManagedEntityId]
FROM dbo.[TypedManagedEntity] TME WITH(NOLOCK)
JOIN [dbo].[DerivedManagedTypes] DT
ON DT.[DerivedTypeId] = TME.[ManagedTypeId]
WHERE
DT.[BaseTypeId] = @ManagedTypeIdForManagedEntitiesByManagedTypeAndDerived AND
TME.IsDeleted = 0
) AS ManagedTypeIdForManagedEntitiesByManagedTypeAndDerived
ON ManagedTypeIdForManagedEntitiesByManagedTypeAndDerived.[BaseManagedEntityId] = [Id]
WHERE
[IsDeleted] = 0 AND
[TypedMonitoringObjectIsDeleted] = 0 AND
[ManagedEntityGenericView].[Path] IN (
SELECT [BaseManagedEntity].[Path]
FROM [BaseManagedEntity]
GROUP BY [BaseManagedEntity].[Path]
HAVING COUNT([BaseManagedEntity].[Path]) > 1
)

ORDER BY [ManagedEntityGenericView].[Path]

Remove *NIX Duplicates

DECLARE @TypedManagedEntityId uniqueidentifier
DECLARE @LastErr INT
DECLARE @TimeGenerated DATETIME
SET @TimeGenerated = GETUTCDATE()
DECLARE EntitiesToBeRemovedCursor CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR
SELECT TME.TypedManagedEntityId
FROM TypedManagedEntity TME

WHERE TME.TypedManagedEntityId IN (' ID 1 OF THE DUPLICATE SERVER ',' ID 2 OF THE DUPLICATE SERVER')
OPEN EntitiesToBeRemovedCursor
FETCH NEXT FROM EntitiesToBeRemovedCursor
INTO @TypedManagedEntityId
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRAN
EXEC @LastErr = [p_TypedManagedEntityDelete] @TypedManagedEntityId, @TimeGenerated

IF @LastErr <> 0
GOTO Err
COMMIT TRAN
FETCH NEXT FROM EntitiesToBeRemovedCursor
INTO @TypedManagedEntityId
END
CLOSE EntitiesToBeRemovedCursor

DEALLOCATE EntitiesToBeRemovedCursor
GOTO Done

Err:
ROLLBACK TRAN
GOTO Done
Done:
SELECT '!!! SUCCESS !!!'

Get Alerts where CustomField1 is used, and ResolutionState is 1

select  alertname, alertdescription, statesetbyuserid, resolutionstate, statesetdatetime, severity, repeatcount, ars.alertguid, customfield1
from Alert.vAlertResolutionState ars 
join alert.valert alt on ars.alertguid = alt.alertguid
join alert.valertdetail on ars.AlertGuid = vAlertDetail.AlertGuid
where ResolutionState like '1' AND customfield1 IS NOT NULL
order by statesetdatetime

Get the reason why your agent was gray

SELECT
ME.FullName,
HSO.StartDateTime AS OutageStartDateTime,
DATEDIFF (DD, hso.StartDateTime, GETDATE()) AS OutageDays,
HSO.ReasonCode,
DS.Name AS ReasonString
FROM  vManagedEntity AS ME
INNER JOIN     vHealthServiceOutage AS HSO ON HSO.ManagedEntityRowId = ME.ManagedEntityRowId
INNER JOIN     vStringResource AS SR ON HSO.ReasonCode =
REPLACE(LEFT(SR.StringResourceSystemName, LEN(SR.StringResourceSystemName)
- CHARINDEX('.', REVERSE(SR.StringResourceSystemName))), 'System.Availability.StateData.Reasons.', '')
INNER JOIN     vDisplayString AS DS ON DS.ElementGuid = SR.StringResourceGuid
WHERE (SR.StringResourceSystemName LIKE 'System.Availability.StateData.Reasons.[0-9]%')
AND DS.LanguageCode = 'ENU'
AND ME.FullName like '% SERVERNAME HERE %'
ORDER BY OutageDays

– F