Quantcast
Channel: TechNet Blogs
Viewing all 34890 articles
Browse latest View live

Azure Hybrid Use Benefit Guidance Document Now Available

$
0
0
Headshot 4
Garrett Bundy
logo-microsoft-azure-retina-square

Hello Partners!

By now, I’m sure that you have heard us talk about the Azure Hybrid Use Benefit.  If you have not take a look here. Many of our partners have been looking for some guidance around how to leverage this functionality, especially now that it is available in the portal and doesn’t require any PowerShell scripting at all.  The team at Microsoft responsible for Azure Hybrid Use Benefit (affectionately called AHUB) has put together a document for you.  This document is specifically for CSP partners who want to know more about use cases, sample licensing scenarios, compliance issues and finally some deployment guidance.  Please take a few minutes to look through this document as it will help you understand more of what we are doing with AHUB and CSP.

Here is the direct link to the document.  Please feel free to comment on this post and provide any feedback you may have.

Azure Hybrid Use Benefit and CSP

Till Next Time,

Garrett


Windows Information Protection Explained – Windows 10 Creators Update

$
0
0

 

With the release of Windows 10 Creators Update there have been many enhancements to Windows 10. For this post, I’ll focus on an expanded feature that is only available in version 1704 (i.e. Creators Update).

In Windows 10 version 1607 we released Windows Information Protection where devices that are enrolled with Microsoft Intune (or SCCM) may receive policies that protect corporate application content from data leaks. In Windows 10 1704 (i.e. Creators Update) a new feature called Mobile Application Management or MAM is available. If you’re familiar with MAM policies for Intune for iOS and Android we’ve brought similar functionality to Windows 10 Creators Update for non-managed devices. This means that non-managed devices such a home user PC with Creators Update can access corporate data without risking data leakage because the MAM policy will prevent cutting and copying data to unmanaged applications.


Requirements

  • Intune licenses
  • Global Admin for Azure Active Directory
  • Windows 10 Creators Update (any version)

 

Getting started

Service setup

  1. Navigate to portal.azure.com from a browser
  2. Select Azure Active Directory
  3. Select Mobility (MDM and MAM)
  4. Add or select Microsoft Intune

 

clip_image002

 

Verify the settings look similar to those in the image below. Add a group as well to make sure the policies flow to the proper individuals:

Note: if the MAM Discovery URL is missing, select “Restore default MAM URLs”

clip_image004

 

Policy setup

From the Azure portal locate the Intune Mobile Application Management (MAM) service. It will look similar to the following:

clip_image006

 

Select “App Policy” and “Add a policy” at the top. Give the policy a name and select Windows 10 under Platform.

clip_image008

 

Now we need to configure what apps the MAM policy will apply to. Do this by selecting “Allowed apps” and then “Add app” at the top of the blade:

clip_image010

Fortunately, many Microsoft applications are already published to select from, for the purposes of this post I’m going to select Microsoft Edge, Notepad, and IE11. The apps in this list are what we call “enlightened apps” where they know about MAM policies. Refer to the links at the end of this post for how non-enlightened apps are supported.

Note: For custom apps, desktop apps, etc. that need to be added, information about these apps is easily found using App Locker via the local policy editor on the device where the apps are installed. More details: https://docs.microsoft.com/en-us/windows/threat-protection/windows-information-protection/app-behavior-with-wip

clip_image012

 

Data Protection

After selecting apps from the list, in my case Notepad, Edge, and IE11 we now need to configure the behavior of when protected data is moved from those apps to non-protected environments (e.g. WordPad).

Select “Required settings” from the policy. The only change I made is to select “Allow Overrides” which means the user will be prompted when they attempt to relocate corporate data outside of the managed app (very similar to how MAM works with iOS and Android):

clip_image014

 

Now move to “Advanced settings” where there are a number of options to further restrict and identify boundaries.  For this post I’ll keep it simple by adding a cloud resource as a network boundary, in this case SharePoint Online and turn on “Show the enterprise data protection icon” for the protected enlightened apps:

clip_image016

Note: Once service and client are configured, you may encounter site access issues, to remediate, add the Value “|/*AppCompat*/” (no quotes) string to the end of the URL string, more details here: https://docs.microsoft.com/en-us/windows/threat-protection/windows-information-protection/app-behavior-with-wip

 

Once the boundaries are set and saved, we need to assign the policy to a group of users.  Feel free to create any group you want in Azure AD, I created on called MAM-WE_Users:

Note: users may be dynamically assigned to Azure AD groups as well for auto assignment to apps, licenses, etc., more details here: https://docs.microsoft.com/en-us/azure/active-directory/active-directory-accessmanagement-groups-with-advanced-rules

clip_image018

 

Client setup

The end user will need to attach their non-managed (e.g. personal) Windows device with Creator Update to their workplace by selecting “Settings” then “Access work or school” and then “Connect” as shown below.  

Note: Non admin users may enroll in MAM.

clip_image020

 

The user will then be prompted to sign on to their corporate account (i.e. O365, Azure AD, Intune, etc. if available) account as shown below (do not join Azure AD or local AD, typically this is performed only for corporate issued/owned devices).

To summarize, there are two steps, add your email and select next.

clip_image022

 

Once the account is verified, and the device is registered, select the account and the Info:

clip_image024

 

The “Info” button will show the last time the device had a successful sync. Also make sure the Management Server Address is populated. Keep this in mind as we’ll refer to this process after we have the MAM policy set up.

clip_image026

 

End User Experience

Because I’m protecting “.cbenterprisemobility.sharepoint.com” and selected both IE11 and Edge (they’re both enlightened apps) when I navigate to them we see a little briefcase icon show up.  When I navigate away from this site, the briefcase will go away. 

clip_image028

clip_image030

 

For example, when I download a file from SharePoint Online, it will contain a little briefcase on the file icon as well as state the ownership of the file in “File ownership” column.  Additionally, the MAM policy can use either a custom EFS certificate or and Azure Information Protection template (RMS) to protect files.

clip_image032

 

When I open the file in a managed app (i.e. Notepad) and because the file is protected by policy, the app shows it’s managed by displaying a briefcase icon on the app itself:

clip_image034

Clicking on the briefcase icon we see the following:

clip_image036

 

When I attempt to cut, copy, and even open the file in an unmanaged app such as WordPad I receive the following prompt.  I can choose to give access in which case that action is logged to event viewer or cancel.  This prompt may be hidden from the user completely by changing the policy in Intune.  Separate policies may also be created and targeted at specific groups of users as well.  For example maybe you want to allow Executives to override as shown below and block certain users such as contractors, etc. 

clip_image038

 

Closer look at the prompt:

clip_image040

 

If you need to change the file ownership, I right click on a file and change the file ownership to Personal if needed:

clip_image042

 

That’s all, we configured Mobile Application Management for a non-managed or domain enrolled Windows 10 client and successfully protected corporate content from leaking outside of corporate sanctioned applications.

 

Troubleshooting

  • First place to look is to make sure the settings are correct and sync’s are successful under Windows 10 Settings/Accounts/Access work or school
  • Next steps are to look in event viewer under: Application and Services Logs/Microsoft/Windows/Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin
  • MAM policies also land under: c:windowssystem32AppLocker folder and you can open the “policy” files in notepad.
  • You’ll also find the MAM policy settings populated under the following registry keys: HKEY_LOCAL_MACHINESOFTWAREMicrosoftPolicyManagercurrentdevice
  • When adding apps to protect, the prepopulated apps should be adequate, however if you’re adding protected apps by hand make sure the format is correct or the MAM policy will not take effect on that app.
  • When users upgrade from MAM to MDM on Windows Home edition, they lose access to WIP. On the Home edition, we do not recommend pushing MDM policies to enable users to upgrade.  More details here: https://msdn.microsoft.com/en-us/windows/hardware/commercialize/customize/mdm/implement-server-side-mobile-application-management

 

Closing thoughts

With all the data theft that happens daily, it’s better to have increased security for non-managed devices than simply guessing if your data is secure from those devices.  Whether your users have iOS, Android, or Windows devices, Intune MAM will protect all three. 

Another option is to block unmanaged devices completely and Azure Active Directory Premium with or without Intune will address this scenario via Conditional Access.

For additional details about MAM with and without MDM as well as supporting desktop and custom apps, please refer to:

SDN Troubleshooting: Certificates

$
0
0

Software Defined Networking (SDN) Senior Program Manager Anirban Paul continues his contribution to his SDN Troubleshooting series on this blog with the following information about troubleshooting certificate issues in SDN. The rest of this post is provided by Anirban to assist you with your SDN deployment using Windows Server 2016 Datacenter edition.

*****

As you may be aware, Network Controller in Windows Server 2016 uses certificate based authentication for communicating with Hyper-V hosts and Software Load Balancer Multiplexor (MUX) virtual machines (VMs).

Some SDN customers have complained about communication issues between Network Controller and hosts, although certificates were correctly configured on both the entities.

On debugging, we found that the customer had installed a non self-signed certificate into the computer’s Trusted Root Certification Authorities store. Although this certificate was not involved in communication between Network Controller and the hosts, the presence of such a certificate breaks client authentication. Here is a view of some of the certificate properties:

 

cert-properties

The following Knowledge Base article provides information about this issue: Internet Information Services (IIS) 8 may reject client certificate requests with HTTP 403.7 or 403.16 errors

To resolve this issue, you can uninstall the non-self-signed certificate from the Trusted Root Certification Authorities certificate store for the Local Computer , or move the certificate to the Intermediate Certification Authorities store.

One more thing to note is that that the Personal (My – cert:localmachinemy) certificate store on the Hyper-V host must have exactly one X.509 certificate with Subject Name (CN) as the host FQDN. This certificate is used for communication with Network Controller.

This behavior is due to a bug in the system and will be fixed shortly. For now, please ensure that you have only one certificate with the Subject Name (CN) as the host FQDN.

For more information, see the following topics in the Windows Server 2016 Technical Library.

 

SMTP Folders in IIS 6

$
0
0

When you install the SMTP service it creates the following default folders in order to process mail:

The folder C:inetpubmailroot contains 4 folders; BadmailDropPickup & Queue.

Pickup:

The SMTP service will process messages in the Pickup folder as outbound messages and will attempt to deliver them.

Drop:

Incoming messages intended for the local domain are placed in the Drop folder. It is very unlikely that you will require the use of the Drop folder in a real-world scenario. Messages in the Drop folder must be retrieved using an email client such as Outlook but also require POP3 server software to be installed in order to enable end-users to connect to and retrieve those messages from the Drop folder.

Queue:

Messages that cannot be delivered  immediately are moved  from the Pickup folder to the Queue folder. The SMTP service will attempt repeatedly to deliver messages in the Queue folder. The number of times it will attempt to deliver the message is configured in the delivery tab.

Badmail:

Emails that could not be delivered to the intended recipient are left in the Badmail folder. After the number of attempts configured in the Delivery tab to deliver the message have not been successful, the message will be moved to the Badmail folder. Messages in the Badmail folder will remain there until administrators diagnose the cause and implement a fix.
Common causes of messages ending up in the Badmail folder are incorrect or invalid email addresses and DNS issues.

Once messages are in the Badmail folder, they can be opened up in notepad and examined. Open up the corresponding .BAD file(s) which will reveal the reason for the message delivery failure.

SMTP Domains:

It is very important to clarify the distinction between a local domain and a remote domain within the SMTP settings. Choosing the wrong SMTP domain type will result in unintended results.

Local Domains:

As stated in the Drop folder section above, a local domain is a DNS domain that is serviced by the local SMTP server.

Messages that are received by an SMTP server that are destined for email addresses within the local domain will not be looked up in DNS, they will be dumped straight to the Drop folder. In the case of most environments the SMTP server is used simply to send mail and not to handle incoming mail for that domain. If this is the case for you, do NOT enable your DNS domain as a local domain within the SMTP server.

You can specify local domains as either default or alias. There can only be one default domain. An alias domain is an alias of the default domain. If you add a new domain and configure it as the new default, the previous default changes to an alias domain.

Remote Domains:

Domains that are not designated as local are remote domains. The SMTP service looks up remote domains in DNS and will process the mail according to the settings configured for that specific remote domain.

Azure Application Insights Enterprise as part of Operations Management Suite subscription

$
0
0

Update for Operations Management Suite customers: We recently added Azure Application Insights Enterprise to the Microsoft Operations Management Suite E1 and E2 as an additional component at no additional cost.

Specifically, each unit of Operations Management Suite E1 and E2 includes an entitlement to 1 node of the Enterprise tier of Application Insights. Each Application Insights node includes up to 200 MB of data ingested per day (separate from Log Analytics data ingestion), with 90-day data retention at no additional cost.

To learn more about Azure Application Insights click here.

Troubleshooting certificate issues in Software Defined Networking (SDN)

$
0
0

As you may be aware, Network Controller in Windows Server 2016 uses certificate based authentication for communicating with Hyper-V hosts and Software Load Balancer MUX virtual machines (VMs).

Some SDN customers have complained about communication issues between Network Controller and hosts, although certificates were correctly configured on both the entities.

On debugging, we found that the customer had installed a non self-signed certificate into the computer’s Trusted Root Certification Authorities store. Although this certificate was not involved in communication between Network Controller and the hosts, the presence of such a certificate broke client authentication. Here is a view of some of the certificate properties:

 

dd

The following Knowledge Base article provides information about this issue: Internet Information Services (IIS) 8 may reject client certificate requests with HTTP 403.7 or 403.16 errors

To resolve this issue, you can uninstall the non self-signed certificate from the Trusted Root Certification Authorities certificate store for the Local Computer, or move the certificate to the Intermediate Certification Authorities store.

One more thing to note is that that the Personal (My – cert:localmachinemy) certificate store on the Hyper-V host must have exactly one X.509 certificate with Subject Name (CN) as the host FQDN. This certificate is used for communication with the Network Controller.

This behavior is due to a bug in the system and will be fixed shortly. For now, please ensure that you have only one certificate with the Subject Name (CN) as the host FQDN.

For more information, see the following topics in the Windows Server 2016 Technical Library.

Anirban Paul, Senior Program Manager

WannaCrypt attacks: guidance for Operations Management Suite customers

$
0
0

Strengthening the security posture of your infrastructure is critical in protecting against evolving cyber threats. The following steps are recommended to safeguard your resources against the recent WannaCrypt ransomware attack:

  1. This recent WannaCrypt malware exploits a Service Message Block (SMB) vulnerability (CVE-2017-0145). Customers should immediately install MS17-010 to resolve this vulnerability.
  2. Review all SMB endpoints exposed to the internet, commonly associated with ports TCP 139, TCP 445, UDP 137, UDP 138. Microsoft recommends against opening any ports to the internet that are not essential to your operations.
  3. Disable SMBv1 – instructions located here: https://aka.ms/disablesmb1
  4. Utilize Windows Update to keep your machines up-to-date with the latest security updates.

Additional Steps for OMS Security

If you are using the Operations Management Suite (OMS) Security solution, we recommend additional steps to further protect your organization from attacks like these:

  1. Routinely assess that all systems are patched with latest updates. You can perform an update assessment to understand the current state of your computers and address the most critical threats in the Security and Audit dashboard. Follow the steps below to verify that all systems are patched with required security updates:
    • In the Microsoft Operations Management Suite main dashboard, click Security and Audit tile.
    • In the Security and Audit dashboard, click Update Assessment under Security Domains
  1. Use OMS Security to continuously monitor your environment for threats. Collect and monitor event logs and network traffic to look for potential attacks. Threat Intelligence option in the Security and Audit Dashboard will help you identify any potential threats in your environment and respond quickly:
    • In the Security and Audit dashboard, choose the 3 options in the Threat Intelligence tile
      1. Server with outbound malicious traffic will help you to identify if there is any computer that you are monitoring (inside or outside of your network) that is sending malicious traffic to the Internet.
      2. Detected threat types tile shows a summary of the threats that are detected. You can extract more information about each threat by clicking on it.
      3. Threat intelligence map will help you to identify the current locations around the globe that have malicious traffic and gather more details associated with those threats.
  1. Confirm that anti-malware is deployed and updated. If you are using Microsoft anti-malware for Azure or Windows Defender, Microsoft released an update last week which detects this threat as Ransom:Win32/WannaCrypt. If you are running anti-malware software from any number of security companies, you should confirm with your provider that you are protected. You can also use the OMS Security solution to verify that anti-malware, and other critical security controls, are configured for your computers:
    • Open Security and Audit dashboard, click Antimalware Assessment under Security Domains.
    • Use Malware Assessment tile to identify following issues-
      1. Active threats: computers that were compromised and have active threats in the system.
      2. Remediated threats: computers that were compromised but the threats were remediated.
      3. Signature out of date: computers that have malware protection enabled but the signature is out of date.
      4. No real-time protection: computers that don’t have antimalware installed

 

For more information on using Operations Management Suite Security, see the documentation.

For a comprehensive look at the Affected Software, Vulnerability Information and Security Update Deployment, see Microsoft Security Bulletin MS17-010.

For more information about this update, see Microsoft Knowledge Base Article 4013389.

Support

Help for installing updates: Windows Update FAQ

Security solutions for IT professionals: TechNet Security Support and Troubleshooting

Help for protecting your Windows-based computer from viruses and malware: Microsoft Secure

Broken DSC Reporting, RequestEntityTooLarge and some LCM internals

$
0
0

Abtract

After migrating partial configurations to composite resources, DSC reporting as described in Using SQL Server 2016 for a DSC Pull Server did not work any longer or was no longer reliable. This is about troubleshooting this and learning something about Event ID 4260.

Recently I have learned that the way to split large DSC configurations is not using partial configurations but composite resources. The conversion was actually much easier than expected and the result is the same. But one important part was missing: Reporting.

 

The effect on the database

When the LCM starts applying a configuration (Start-DscConfiguration), it writes an entry of type ‘Initial’ into the reporting database. This record has a StartTime but not yet a valid EndTime. Also, StatusData only contains some basic information about the node.

[code lang=”PowerShell”]
Invoke-Sqlcmd -Database DSC -Query ‘SELECT TOP 1 * FROM StatusReport’
[/code]

[code]
JobId : d7352efe-3ce2-11e7-836e-0017fa00000a
Id : 77baf262-3ca1-11e7-8365-0017fa00000a
OperationType : Initial
RefreshMode :
Status :
LCMVersion : 2.0
ReportFormatVersion : 2.0
ConfigurationVersion :
NodeName : XDC11
IPAddress : 192.168.88.129;127.0.0.1;fe80::99e2:71d5:6f53:7fe0%5;::2000:0:0:0;::1;::2000:0:0:0
StartTime : 5/20/2017 12:31:03 AM
EndTime : 12/30/1899 12:00:00 AM
Errors : []
StatusData : ["{"IPV4Addresses":["192.168.88.129","127.0.0.1"],"CurrentChecksum":"0926E211C6D8617558
55CED942CB734CC94BF620EC6E4F8D1B9889F5B57ED6C7","MACAddresses":["00-17-FA-00-00-0A","00-00
-00-00-00-00-00-E0"],"Type":"Initial","HostName":"XDC11","Locale":"en-US","StartDa
te":"2017-05-20T09:31:03.9100000+11:00","JobID":"{D7352EFE-3CE2-11E7-836E-0017FA00000A}",
"LCMVersion":"2.0","IPV6Addresses":["fe80::99e2:71d5:6f53:7fe0%5","::2000:0:0:0","::1
","::2000:0:0:0"]}"]
RebootRequested : False
AdditionalData : [{"Key":"OSVersion","Value":"{"VersionString":"Microsoft Windows NT 10.0.14393.0","ServiceP
ack":"","Platform":"Win32NT"}"},{"Key":"PSVersion","Value":"{"CLRVersion":"4.0.30319.4
2000","PSVersion":"5.1.14393.0","BuildVersion":"10.0.14393.0"}"}]
[/code]

 

After the LCM has finished the job, it sends an update statement with the same JobId to the pull server. The pull server then forwards this update query to the database server. In my case, this did not happen and the database was filling up with records, all without an EndTime and all did have the OperationType ‘Initial’ or ‘Consistency’. Additionally, all my nice report queries and PowerBI did not work anymore.

sqlstatusreportonlyinitial

 

 

 

One takeaway is that if something does not work with reporting, first take look at the DSC nodes operational log. I found an error with the ID 4260 there that was telling something about “RequestEntityTooLarge”.

eventviewer4260

 

Of course, you can also use PowerShell to find these event log entries using Get-WinEvent.

[code lang=”PowerShell”]
Get-WinEvent -FilterHashTable @{ LogName = ‘Microsoft-Windows-Dsc/Operational’; ID = 4260 } | Select-Object -Fir
st 1 | Format-List
[/code]

[code]
TimeCreated  : 5/20/2017 9:43:19 AM
ProviderName : Microsoft-Windows-DSC
Id           : 4260
Message      : Job {87B3A128-3CE4-11E7-836E-0017FA00000A} :
               Http Client 77BAF262-3CA1-11E7-8365-0017FA00000A failed for WebReportManager for configuration The
               attempt to send status report to the server https://xpull1:8080/PSDSCPullServer.svc/Nodes(AgentId=’77BAF
               262-3CA1-11E7-8365-0017FA00000A’)/SendReport returned unexpected response code RequestEntityTooLarge..
[/code]

 

The problem are some limitations on the pull server’s web configuration. After some research and testing I was confused by contradictory statements and resolutions. After trying without success for quite some time, I finally got it working by adding this into the web.config in ‘C:inetpubPSDSCPullServer’.

[code lang=”xml”]
<bindings>
<webHttpBinding>
<binding maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed">
</binding>
</webHttpBinding>
</bindings>
[/code]

 

Unfortunately the xWebConfigKeyValue does not yet support doing these settings when setting up the DSC pull server using DSC. As I do not want to make this a manual step that I can forget, I have added these lines into the pull server’s setup routine.

[code lang=”PowerShell”]
$path = ‘C:inetpubPSDSCPullServerweb.config’

$doc = [xml](Get-Content -Path $path)
$serviceModelNode = ($doc | Select-Xml -XPath ‘//system.serviceModel’).Node

$bindingsNode = ($doc | Select-Xml -XPath ‘//system.serviceModel/bindings’).Node
if (-not $bindingsNode)
{
$bindingsNode = $doc.CreateElement(‘bindings’)
[void]$serviceModelNode.AppendChild($bindingsNode)
}

$webHttpBindingNode = ($doc | Select-Xml -XPath ‘//system.serviceModel/bindings/webHttpBinding’).Node
if (-not $webHttpBindingNode)
{
$webHttpBindingNode = $doc.CreateElement(‘webHttpBinding’)
[void]$bindingsNode.AppendChild($webHttpBindingNode)
}

$bindingNode = ($doc | Select-Xml -XPath ‘//system.serviceModel/bindings/webHttpBinding/binding’).Node
if (-not $bindingNode)
{
$bindingNode = $doc.CreateElement(‘binding’)
[void]$webHttpBindingNode.AppendChild($bindingNode)
}

$bindingNode.SetAttribute(‘maxBufferPoolSize’, [int]::MaxValue)
$bindingNode.SetAttribute(‘maxReceivedMessageSize’, [int]::MaxValue)
$bindingNode.SetAttribute(‘maxBufferSize’, [int]::MaxValue)
$bindingNode.SetAttribute(‘transferMode’, ‘Streamed’)

$doc.Save($path)
[/code]

 

After this change, it requires restarting the pul server’s app pool. The easiest way is calling iisreset.exe.

Reporting works again

After having altered the web.config and restarted the app pool, the event ID 4260 on the DSC nodes got replaced by 4266, which looks much better.

eventviewer4266

 

Also the records in the database are being updated again, as you can see by the valid EndTime.

Note: What is not visible in the screenshots is the column StatusData which stores the most interesting data.

sqlstatusreportcomplete

 

Some Richer Reporting

If you create the database with the script references in SQL Server 2016 for a DSC Pull Server you have a view that parses the Json data and returns also some valuable information like Duration (how long has it taken applying the configuration) and how many resources are or are not in desired state. The non-compliant resources are also names in the column ResourceIdsNotInDesiredState.

sqlfilledrawstatusdata


How to Remove and Regenerate an Expired RDP Certificate using Custom Script Extension

$
0
0

Symptom:
Unable to connect to VM corrupt or expired RDP Certificate

Resolution: 

  1. Open up a Blank Notepad and paste the following into it:

    #sets the Certificate Store path
    $path = get-childitem -Recurse ‘Cert:LocalMachineRemote Desktop’
    #Check the certificate date
    $path.NotAfter
    #sets the thumbprint from the cert
    $thumb = $path |Select-Object -ExpandProperty Thumbprint
    #pulls just the Machine Key Name based thumbprint
    $cert = $path.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
    #Machine key properties based on the thumbprint
    $key = Get-ChildItem C:ProgramDataMicrosoftCryptoRSAMachineKeys |Where-Object {$_.Name -eq $cert}
    ###destructive part###
    #Removes the certificate
    Remove-Item -path “Cert:LocalMachineRemote Desktop$thumb”
    #deletes the key
    $key | % { $_.Delete() }
    #reboot to generate a new cert
    restart-service TermService -force

  2. Save the file as RemoveMachineKeyCert.ps1
  3. Navigate to the Azure Portal
  4. Select the impacted VM
  5. Select extensions
    1
  6. Select Add
  7. Select Custom Script Extension
    2
  8. Select Create
  9. Select the RemoveMachineKeyCert.ps1 created in the previous steps
  10. Install the .ps1 file. No arguments are needed.
    3
  11. Go back to the extensions tab and wait for the Custom Script to report as successful
  12. Restart the virtual machine so the certificate can be regenerated
  13. Attempt to RDP to the machine.

常識を打ち破る画期的なテクノロジのウソとホント【5/20 更新】

$
0
0

(この記事は 2017 年 3 月 31  日にMicrosoft Partner Network blog に掲載された記事 Disruptive Technology: Fact or Fiction? の翻訳です。最新情報についてはリンク元のページをご参照ください。)

MPN-Team-author-block_1

 

毎年エイプリル フールの時期になると、インターネット上は読者の関心を引こうとするイタズラ記事や知名度アップをねらう記事 (英語) で溢れかえります。MPN ブログはいつもどおり真面目にやっていきますが、今回の記事では、社内の私たちでさえ目を疑うような、マイクロソフトのおもしろいプロジェクトや製品をご紹介します。業界では既成概念をくつがえす新しいテクノロジが日々登場しており、パートナーの皆様はそうしたテクノロジについてよくご存じかと思います。しかし、あなたの知っている情報は、はたして本当に事実なのでしょうか。この記事を読んで、確かめてみてください。

 

ロボットが人間の仕事を奪う

ホント – AI と産業オートメーション

PwC が行った最近の調査 (英語) によれば、米国では約 40% の職種が近い将来ロボットに取って代わられるリスクにさらされています。そのほか、英国は 30%、ドイツ 35%、日本では 21% にとどまっています。業種別に見ると、新しいテクノロジによって自動化できる可能性が高いのは運送業、製造業、小売業です。米国では、定型的な事務作業などの自動化できる仕事に従事している人口が多いため、他の国よりも高いリスクが見込まれます。一方、日本ではファスト フード店で自動販売機が導入されているなど、既に自動化が進んでいることから、比較的リスクが小さいと考えられています。

 

宇宙飛行士が仮想現実を利用している

ホント – HoloLens

仮想現実 (VR) はゲームや映画だけに使われるものだと思っていませんか。VR の使い道はそれだけではありません。マイクロソフトの HoloLens などのデバイスが登場したことで、創造性を存分に発揮して現実世界の問題に取り組めるようになっています。2015 年、マイクロソフトは NASA と共同で、国際宇宙ステーション (英語) に滞在している宇宙飛行士に仮想アシスタントを届ける「Sidekick」プロジェクトをスタートさせました。この HoloLens には 2 つのモードが搭載されています。まず「リモート エキスパート モード」では、宇宙飛行士の見ているものが映像として地上のオペレーターに送られ、オペレーターは宇宙飛行士にリアルタイムに指示することができます。もう 1 つの「プロシージャ モード」では、作業の手順がホログラフィックのアニメーションで表示されます。

また、スミソニアン博物館でも、未来の宇宙探検家を育てるべく VR を活用しています。同館が進める「Smithsonian X 3D」プロジェクトでは、さまざまな 3D キャプチャ方法を駆使してアポロ 11 号の司令船 (英語) などの代表的な展示物のスキャンを行い、3D データとして公開しました。HoloLens はまだリリースされたばかりではありますが、大きな可能性を秘めていることは明らかです。博物館でこのテクノロジを活用すれば、まったく新しい展示方法を実現し、これまで歴史的な大事業や文化を象徴する品々を目にする機会がなかった世界中の子どもたちにも学びの場を提供できるようになるでしょう。

 

データを保管するならオンプレミスよりもクラウドが安全

ホント – Office 365、Windows、Azure

データの保管や社内システムのホスティングは、オンプレミスの方が安全。もしまだそう思っているなら、その考えは時代遅れです。Office Blogs の記事 (英語) にも書かれているとおり、オンプレミスのシステムはその性質上、クラウド上のシステムに比べて安全性が確保されていません。その理由として挙げられるのは、サイバー犯罪やデジタル セキュリティ全般の問題が増えつつあることなどです。しかし、たとえ社内のセキュリティ チームや委託先のパートナー企業に包括的に対応してもらえる体制が整っていない企業であっても、Office 365 をはじめとするマイクロソフトのクラウド製品を利用することで、エンタープライズ レベルのセキュリティ機能が利用できます。しかもサブスクリプション ベースの料金体系なのでコスト管理も簡単です。

マイクロソフトにはセキュリティに精通した優秀なスタッフが揃っているため、セキュリティ機能が Office 365 や Azure といった製品の主な特長となっているのは自然な流れだと言えるでしょう。Office 365 セキュリティ チームは最新のサイバー セキュリティ保護機能を搭載できるように、セキュリティ開発ライフサイクルを採用し、トラフィックを調整し、セキュリティ侵害を回避・検出・軽減しています。こうした対応を行うためのリソースを確保できる企業はほとんどありません。さらに Office 365 では 99.9% の稼働率が保証されています (返金制度付き)。このため「クラウド テクノロジは安全」という説は、事実と言ってよいでしょう。

 

VR デバイスが人間関係を深め、生産性を高める

ホント – HoloLens と Windows 10 対応 VR ヘッドセット

ソーシャル ネットワーキング サイト (SNS) の普及によって人々のコミュニケーション方法が変化したように、VR にも同じ効果が期待 (英語) されています。ただし、だれもが VR の世界に引きこもってしまうといった都市伝説が現実になるわけではありません。VR デバイスは、人とつながり、作業をこなすための強力なツールとなります。HoloLens を使用すれば、たとえば遠くにいる友達とも一緒にゲームを楽しむ (英語) ことができます。Skype for HoloLens では、家族や友達、同僚とビデオ チャットで話しながらホログラムを共有できるので、共同作業に便利です。

また、Windows 10 対応 VR ヘッドセットはスクリーン部分を跳ね上げられるように設計され、マルチタスク機能も備わっているため、Twitter などの使い慣れたアプリと没入型のソフトウェア プログラムやゲームとを簡単にすばやく切り替える (英語) ことができます。VR エクスペリエンスに没頭しながら、よく使う Windows アプリにアクセスできるので、ユーザーは生産性を維持できるのです。

 

 

据え置き型ゲーム機はいずれ姿を消す

ウソ – Xbox と Project Scorpio

VR や AR (拡張現実) に対応したデバイスの普及は確かにゲーム業界に影響を与えますが、だからと言って据え置き型ゲーム機が終わりを迎えるとは断定できません。マイクロソフトで Xbox ゲームのマーケティング責任者を務める Aaron Greenberg は昨年、Engadget のインタビュー (英語) において次のように語りました。「Xbox One 用のゲームやアクセサリをお持ちであれば (中略) Project Scorpio でもお使いいただけます。下位互換性やゲーム タイトル数も気になるかと思いますが、Scorpio に買い替えても同じコンテンツをそのまま使えるので、その点についてはユーザーの皆様にアピールしていきたいです。つまりこれは 1 つのエコシステムなのです。Xbox One S と Project Scorpio、どちらをお持ちだとしても決して置き去りにされることはありません」

SF の世界を現実のものにする、この画期的なテクノロジについてどのようにお考えですか。ぜひ皆様のご意見をお聞かせください。

 

Display friendly file sizes in PowerShell

$
0
0

 

At one of my recent classes, while discussing hashtables and calculated properties I showed an example of how to list the file’s size in kilobytes instead of the default bytes size.

This can be accomplished with {$_.Length/1kb} as the expression in the property’s hash, but then the output can be… not too pretty… and from some reason, the folders have a non-zero size:

PS> dir | Select-Object -Property Mode, LastWriteTime, @{N=’SizeInKb’;E={$_.Length/1kb}}, Name

 

Mode   LastWriteTime              SizeInKb Name            

—-   ————-              ——– —-            

d—– 20/05/2017 20:10:51    0.0009765625 Logs            

-ar— 03/01/2017 15:58:42     3.041015625 differentfile.exe

-ar— 30/11/2016 09:40:47    0.2705078125 file.txt        

-a—- 21/03/2017 19:46:16           12044 large.msi       

-a—- 21/03/2017 19:46:18 2902.8388671875 medium.pkg      

-a—- 20/05/2017 21:02:19    1.2568359375 otherfile.txt   

 

A possible solution to this, can be truncating some numbers after the decimal point, and then casting it to a double to still be able to sort the files by their size:

PS> dir | Select-Object -Property Mode, LastWriteTime, @{N=’SizeInKb’;E={[double](‘{0:N2}’ -f ($_.Length/1kb))}}, Name | Sort-Object -Property SizeInKb

 

Mode   LastWriteTime       SizeInKb Name            

—-   ————-       ——– —-            

d—– 20/05/2017 20:10:51        0 Logs            

-ar— 30/11/2016 09:40:47     0.27 file.txt        

-a—- 20/05/2017 21:02:19     1.26 otherfile.txt   

-ar— 03/01/2017 15:58:42     3.04 differentfile.exe

-a—- 21/03/2017 19:46:18  2902.84 medium.pkg      

-a—- 21/03/2017 19:46:16    12044 large.msi       

 

But why only in kilobytes? Why not have the size display in human readable format?

So this brought me to write the Get-FriendlySize function:

function Get-FriendlySize {

    param($Bytes)

    $sizes=‘Bytes,KB,MB,GB,TB,PB,EB,ZB’ -split ‘,’

    for($i=0; ($Bytes -ge 1kb) -and

        ($i -lt $sizes.Count); $i++) {$Bytes/=1kb}

    $N=2; if($i -eq 0) {$N=0}

    “{0:N$($N)} {1}” -f $Bytes, $sizes[$i]

}

 

So I could call it with the Select-Object cmdlet:

PS> dir | Select-Object -Property Mode, LastWriteTime, @{N=’FriendlySize’;E={Get-FriendlySize -Bytes $_.Length}}, Name

 

Mode   LastWriteTime       FriendlySize Name            

—-   ————-       ———— —-            

d—– 20/05/2017 20:10:51 1 Bytes      Logs            

-ar— 03/01/2017 15:58:42 3.04 KB      differentfile.exe

-ar— 30/11/2016 09:40:47 277 Bytes    file.txt        

-a—- 21/03/2017 19:46:16 11.76 MB     large.msi       

-a—- 21/03/2017 19:46:18 2.83 MB      medium.pkg      

-a—- 20/05/2017 21:02:19 1.26 KB      otherfile.txt    

 

But wait! Now I can’t sort them. The FriendlySize is just a string:

PS> dir | Select-Object -Property Mode, LastWriteTime, @{N=’FriendlySize’;E={Get-FriendlySize -Bytes $_.Length}}, Name | Sort-Object -Property SizeInKb

 

Mode   LastWriteTime       FriendlySize Name            

—-   ————-       ———— —-            

d—– 20/05/2017 20:10:51 1 Bytes      Logs            

-ar— 03/01/2017 15:58:42 3.04 KB      differentfile.exe

-ar— 30/11/2016 09:40:47 277 Bytes    file.txt        

-a—- 21/03/2017 19:46:16 11.76 MB     large.msi       

-a—- 21/03/2017 19:46:18 2.83 MB      medium.pkg      

-a—- 20/05/2017 21:02:19 1.26 KB      otherfile.txt  

 

Then it occurred me, why not just override the ToString method on the Length’s FileInfo object property when it’s displayed and leave the original length’s value as it was?

This can be accomplished by changing the format data for the object.

So I wrote some lines of code that read the default FileSystem.format.ps1xml file and change the property length to a scriptblock, and update the format data with the Update-FormatData cmdlet:

(Note the double dollar sings before the under-score ($$_) in the here-string, this is to avoid the substitution with the match group)

 

$file = ‘{0}myTypes.ps1xml’ -f ([System.IO.Path]::GetTempPath())

$data = Get-Content -Path $PSHOMEFileSystem.format.ps1xml

$data -replace ‘<PropertyName>Length</PropertyName>’, @’

<ScriptBlock>

if($$_ -is [System.IO.FileInfo]) {

    $this=$$_.Length; $sizes=’Bytes,KB,MB,GB,TB,PB,EB,ZB’ -split ‘,’

    for($i=0; ($this -ge 1kb) -and ($i -lt $sizes.Count); $i++) {$this/=1kb}

    $N=2; if($i -eq 0) {$N=0}

    “{0:N$($N)} {1}” -f $this, $sizes[$i]

} else { $null }

</ScriptBlock>

‘@ | Set-Content -Path $file

Update-FormatData -PrependPath $file

 

After running the code, I can simply list the files and get their friendly sizes with sorting and everything!

PS> dir | Sort-Object -Property Length

 

 

    Directory: C:TestDirectory

 

 

Mode                LastWriteTime         Length Name                                                                                                                                                       

—-                ————-         —— —-                                                                                                                                                       

-ar—       30/11/2016     09:40      277 Bytes file.txt                                                                                                                                                   

-a—-       20/05/2017     21:02        1.26 KB otherfile.txt                                                                                                                                              

-ar—       03/01/2017     15:58        3.04 KB differentfile.exe                                                                                                                                          

-a—-       21/03/2017     19:46        2.83 MB medium.pkg                                                                                                                                                 

-a—-       21/03/2017     19:46       11.76 MB large.msi                                                                                                                                                  

d—–       20/05/2017     20:10                Logs                                                                                                                                                        

 

If you want to always have this, put the new myTypes.ps1xml file somewhere on your drive, and add the call to  Update-FormatData -PrependPath $file your profile.

 

HTH,

Martin.

Windows Server 2016 Essentials Videos

$
0
0

Over on the OEMTV channel on channel9.msdn.com there are a couple of recent videos covering Windows Server 2016 Essentials.
Get the Lowdown on Windows Server 2016 Essentials


This video will get you up to speed all things Windows Server 2016 Essentials. It covers who should use Essentials edition, scenarios it is good for, organizational sizing considerations, licensing and pricing considerations. Also learn about the easy dashboard experience and how Essentials edition gives customers a hybrid cloud pathway for moving to the cloud if and when they are ready.

  • [1:16] Small Business Server is now Windows Server Essentials. Why the change?
  • [4:05] Can you give us an overview of Essentials? What are some of its limitations?
  • [6:00] What can users expect with Essentials? Should small businesses be worried to use it?
  • [10:34] How does Essentials integrate with Office 365 and Azure?
  • [16:32] Virtualizing Essentials is an interesting concept. What are some of the benefits and how does that actually work?
  • [18:22] Can you use Essentials as the host OS and VM in this scenario?
  • [20:29] What are some scenarios where you see running on-premise server applications to Azure?
  • [24:28] What happens if someone has Essentials and grows past the 25 user size limitation? What upgrade options do they have?

Windows Server 2016 Essentials Dashboard

Windows Server 2016 Essentials is the lowest-cost edition of Windows Server intended for a small company’s first server. With Windows Server 2016 Essentials comes a dashboard which simplifies the tasks that you perform to manage your network and server. Common tasks include setting up your server, managing user accounts, managing backups, integrating with cloud services, and more. In this episode we’ll provide an overview of Windows Server 2016 Essentials edition and a demo of how to use it.

  • [3:24] DEMO: Windows Server 2016 Essentials Dashboard walkthrough

Microsoft Build 2017 の発表まとめ【5/21 更新】

$
0
0

msbuild2017-201705

去る 5 月 10 日から 12 日までの間、米国シアトルで開発者向けイベント Microsoft Build 2017 が行われました。Day 1/Day 2で最新の クラウド プラットフォーム、開発ツール、AI、IoT、データ分析からWindows 動向まで、実に様々なことが発表され共有されました。いままで Build はずっとサンフランシスコで開催されていましたが、今年はマイクロソフトや Amazon Web Service が本社を構えていることをはじめ、Google や Facebook もオフィスを構える「クラウドシティー」と呼ばれるシアトルで開催されたことも印象的でした。

Microsoft Build 2017 でどういう内容が発表されたかについては、すでに良質のまとめ記事がいくつかありますので、この記事では新たにまとめることはせずに、最も読むべき記事の一覧、発表された重要な数字、および追加情報へのリンク集を提供することにします。

 

読むべき 7 本の記事

以下の記事を読んでおけば、Microsoft Build 2017 で発表された内容について、だいたいの内容を把握することができますので、まず読んでおくことをお勧めします。Day 1 はクラウドと AI、Day 2 は Windows 10 と複合現実 (Mixed Reality) が中心でした。

これだけは覚えておきたいキーワード

  • 「インテリジェントクラウド」と「インテリジェントエッジ」: クラウド上で作成したAIや機械学習のモデルをエッジデバイスに展開することで、デバイス側で直接判断が可能になります。一方、データはクラウドに吸い上げて全体のモデル作成などに利用します。リアルタイム性とビッグデータの活用を両立するモデル。これまでマイクロソフトは、「モバイルファースト」「クラウドファースト」という言い方をしていましたが、それを進化させたもの。インテリジェントクラウドとインテリジェントエッジは「対」であることがポイント。デバイスへのモデルの展開には Azure IoT Edge を利用します。
  • Azure IoT Edge: WindowsとLinuxでの両方で稼働するクロスプラットフォームの IoT ランタイム。IoTのエッジ側の物理デバイスが Azure IoT Hub、Azure Stream Analytics、Azure Machine Learningなどの Azure 上のサービスと通信するためのクライアントアプリを、Dockerイメージとしてパッケージングし、物理デバイス側の Docker コンテナホストに展開します。
  • Azure Cosmos DB: 今まで存在した、非構造化データを格納できる DocumentDB をはじめ MongoDB、Table storage、Gremlin Graph、Spark などの複数 API をサポートしたマルチモデルの分散データベース。IoT、AI、モバイルといった地球規模のクラウドサービスとデータ集約型アプリケーションをサポートするために一から設計されました。業界初のグローバルに分散したマルチモデルのデータベースサービスであり、保証されたアップタイム、スループット、データ一貫性、そして、99パーセントの処理において 10 ミリ秒以下のレイテンシーを実現できる水平スケーラビリティを提供します。
  • MySQL/PostgreSQL Managed Service: Azure SQL Database に追加される新しいマネージドサービス。これにより開発者の選択肢がより豊富になります。
  • Windows 10 Fall Creators Update: 2017 年秋に予定されている次期大型アップデート。新しいクロスデバイスのデザイン システムにより、創造力のさらなる可能性が広がります。Windows、iOS、Android 間でユーザーがデバイスを切り替えても、エクスペリエンスの一貫性が保たれます。また、Windows ストアからは、iTunes、Spotify、SAP Digital Boardroom の提供が開始されることも発表されました。さらに、新しいツールにより、すべての開発者が Windows をホームとして利用できるようになります。

 

Microsoft Build 2017 で語られた主なモメンタム

  • Windows 10 の月間アクティブデバイス: 5 億人
  • Office 365 の月間アクティブユーザー: 1 億人
  • Cortana の月間アクティブユーザー: 1 億 4,000 万人以上
  • Azure Active Directory を利用する組織数: 1,200 万
  • マイクロソフト クラウドを利用するフォーチュン 500 企業の割合: 90% 以上
  • Azure のリージョン数: 38

 

より詳細な情報

以下に主な記事やニュースをまとめました。

以下にマイクロソフトのブログやプレスリリース記事をまとめました。

System Center Mayıs 2017 Bülten

$
0
0

System Center Configuration Manager (SCCM)
Update 1704 for Configuration Manager Technical Preview Branch – Available Now!

Summary of changes in System Center Configuration Manager current branch, version 1702

Configuring Email Notification for Configuration Manager Reports

Enabling BranchCache for Configuration Manager using Client Settings

Configuration Manager SQL queries to help IT Pros report on KBs related to WannaCrypt

Configuration Manager Client Messaging SDK available on NuGet.org

KB: Configuration Manager clients reinstall every five hours because of a recurring retry task and may cause an inadvertent client upgrade

 

Intune / Enterprise Mobility

The new Azure AD Admin Console is GA

Get Intune PowerShell samples for Microsoft Graph API

Intune on Azure Migration Blocker Guidance

New webinar – EMS in action: Managing mobility for Office 365 and beyond

Getting Started with Microsoft Intune for Education

Build and integrate your App with EMS to reach new customers

New resources for deployment with Microsoft FastTrack for Enterprise Mobility + Security

New Enhancements to the Azure AD Pass Through Authentication Preview are live

Partner with Enterprise Mobility + Security to drive your customers’ digital transformation

 

System Center Operations Manager (SCOM)

Introducing the Security Monitoring Management Pack for SCOM

Agent Management Pack – Making a SCOM Admin’s life a little easier

Creating helpful HTML reports from SCOM Management Packs

SCOM 2016 System Center Core Monitoring Fix

How does CPU monitoring work in the Windows Server 2016 management pack?

Monitoring Windows Server 2003 with SCOM 2016

Reporting on SCOM Data: Piecing the data together (Part 1)

MP Authoring – Q&A

Azure AD Connect Sync Custom Management Pack (OpsConfig) -Beta

SCOM Alert Update connector example for SCOM 2016

Reporting on SCOM Data: A Single Pane of Glass

Monthly System Center Operations Manager Technology Update–May 2017

Outlook Public Folder Monitoring using SCOM

NiCE DB2 Management Pack updated

Savision Live Maps Service Health Index

SCOM 2012 Heartbeat Alerts Won’t Stop

Mobile First–Cloud First’ Strategy – How About System Center

Calculating the Overall Availability of Distributed Applications in Percentage

SCOM Printer Monitoring Management Pack Supplement

SCOM Operations Manager Shell PowerShell Error When Launched as Administrator

Registry tweaks for SCOM – measure twice cut once

Monitoring Commvault with SCOM

Updated MP: ConfigMgr (SCCM) MP, For Hybrid Scenario’s

SQL Query for getting SCOM Recovery Tasks Results

System Center Management Pack (CTP) for SQL Server vNext Replication

SCOM Dolphin tools V1.0

SCOM 2016 – Error EventID 1199  GetOpsMgrDBWatcherDiscovery.ps1

System Center Internal Library MP (QuickFix for SCOM2016)

 

Operations Management Suite (OMS)

 

IT Service Management Connector Public Preview

Announcing the general availability of OMS Solutions for Nutanix by Comtrade software

MSOMS management pack version 1705 released

Synthetic Web Test for Microsoft OMS

Connect your Linux Computers to Operations Management Suite (OMS)

Monitoring containers running on Service Fabric with OMS Insights and Analytics – Container Monitoring Solution

The OMS Agent for Azure Government – A Cheat Sheet

Programmatically Performing OMS Log Search Against a Large Result Set

Inside the Operations Management Suite e-book

 

Virtualization (SCVMM)

Hyper-V authentication in Windows Server 2016 for managing remote Hyper-V servers through RSAT

Using Hyper-V Resource Pools to ease migration between different configurations

Free webinar on what’s new in Hyper-V

Upload VHD and create new VM with managed disk

 

Data Protection (SCDPM)

Azure Backup and Azure Site Recovery available in Azure Germany

 

Automation
Sending messages to Microsoft Teams from Visual Studio Code

Deploying ARM Templates with Artifacts Located in a Private GitHub Repository

Visualize DSC Reporting with PowerBI

$
0
0

Abstract

Reporting is an essential component of DSC and one of the main advantages. Always knowing the status about your nodes and even being able to know which settings are not compliant is a big advantage compared to classical scripting or Group Policies. However, the reporting feature is not so easy to use and there are no graphical reports available yet. Dashboards and diagrams are always good to draw people’s attention. This article describes you to achieve exactly this
Having the graphical reports should also help explaining to non-technical people the importance of Infrastructure as Code and DSC.

Requirements

This article based on Using SQL Server 2016 for a DSC Pull Server. You need to move from EDB to an MDB with linked tables. All the steps required and additional details are mentioned in this article. The script to create the SQL database referenced in this article adds some views, functions and a trigger to convert the data into proper JSON, also required.

Another requirement may be – depending on the size of the configuration – described in Broken DSC Reporting, RequestEntityTooLarge and some LCM internals.

If you want to test this out without investing too much time, you may want to take a look at and the script respectively. This script deploys a lab that has a DSC Pull Server, SQL Server 2016 and PowerBI already configured.

 

Desired Result

The result after having implemented the reporting as described here looks like this:

dscdashboard1

This dashboard lets you very easily see the overall status of your DSC nodes. In the current version, you get these information:

  1. Node Status, count of success and failure
  2. Count of compliant / non-compliant configuration items per node
  3. Average duration it takes to apply the configuration
  4. Status reports and configurations per node

The dashboard is quite extensible and can visualize almost anything that is covered with the data in the DSC database.

The heavy lifting behind the scenes

Note: This section is not essential to read of you just want to use the reporting solution and do not face issues.

The pull server stores most of the data as JSON into the database. However, the JSON data cannot be converted back from JSON so easy and seems to be serialized more than once.

This is how the data looks like

[code lang=”powershell”]
Invoke-Sqlcmd -Query ‘SELECT TOP 1 StatusData FROM Statusreport’ -Database DSC | Select-Object -ExpandProperty StatusData
[/code]

["{"StartDate":"2017-05-21T18:20:51.5710000+02:00","IPV6Addresses":["fe80::2c81:cc87:4f57:e1d9%2","::2000:0:0:0","::1","::2000:0:0:0"],"DurationInSeconds":"5","JobID":"{74703B6E-3E41-11E7-8365-0017FA00000C}","CurrentChecksum":"30B2DD729B96A4DFCB882379448A9183C00B77EE754CCA5C84D76124AE16B151","MetaData":"Author: Install; Name: PullClient; Version: 2.0.0; GenerationDate: 05/21/2017 18:04:02; GenerationHost: XPULL1;","Status":"Success","IPV4Addresses":["192.168.88.8","127.0.0.1"],"LCMVersion":"2.0","NumberOfResources":"0","Type":"LocalConfigurationManager","HostName":"XDC13","RebootRequested":"False","MACAddresses":["00-17-FA-00-00-0C","00-00-00-00-00-00-00-E0"],"MetaConfiguration":{"AgentId":"1B664F0D-3E3F-11E7-8365-0017FA00000C","ConfigurationDownloadManagers":[{"RegistrationKey":"","ServerURL":"https://xpull1:8080/PSDSCPullServer.svc","ResourceId":"[ConfigurationRepositoryWeb]PullServer","ConfigurationNames":["Complete_xDC13"],"SourceInfo":"C:\\Users\\Install.BMW\\Desktop\\DscScripts\\2.2 SetupDScClients.ps1::26::9::ConfigurationRepositoryWeb"}],"ActionAfterReboot":"ContinueConfiguration","LCMCompatibleVersions":["1.0","2.0"],"LCMState":"Idle","ResourceModuleManagers":[],"ReportManagers":[{"RegistrationKey":"","ServerURL":"https://xpull1:8080/PSDSCPullServer.svc","ResourceId":"[ReportServerWeb]ReportServer","SourceInfo":"C:\\Users\\Install.BMW\\Desktop\\DscScripts\\2.2 SetupDScClients.ps1::34::9::ReportServerWeb"}],"StatusRetentionTimeInDays":"10","LCMVersion":"2.0","ConfigurationMode":"ApplyAndAutoCorrect","RefreshFrequencyMins":"30","RebootNodeIfNeeded":"True","SignatureValidationPolicy":"NONE","RefreshMode":"Pull","DebugMode":["NONE"],"LCMStateDetail":"","AllowModuleOverwrite":"False","ConfigurationModeFrequencyMins":"15","SignatureValidations":[]},"Locale":"en-US","Mode":"Pull"}"]

PowerShell cannot convert this data using ConvertFrom-Json and SQL Server cannot read it either using OPENJSON. The data needs to be converted first. The solution was mentioned first in Get DSC Pull Client Status and is actually quite simple. To make the conversion happen completely transparent to the user and without manual interaction, I have created a database trigger that takes care of that.
After the conversion, the StatusData column looks like this:

{"StartDate":"2017-05-21T18:57:28.2910000+02:00","IPV6Addresses":["fe80::e466:5405:663c:6ac3%3","::2000:0:0:0","::1","::2000:0:0:0"],"DurationInSeconds":"12","JobID":"{91CB841E-3E46-11E7-8365-0017FA00000D}","CurrentChecksum":"0FA45B9AE2E7CA252D64AA40DE8AFD1F9B19E02844F57498F22C1FD700F31E90","MetaData":"Author: Install; Name: Complete; Version: 2.0.0; GenerationDate: 05/21/2017 18:03:44; GenerationHost: XPULL1;","RebootRequested":"False","Status":"Success","IPV4Addresses":["192.168.88.9","127.0.0.1"],"LCMVersion":"2.0","NumberOfResources":"1","Type":"Initial","HostName":"XDC14","ResourcesInDesiredState":[{"SourceInfo":"C:UsersInstall.BMWDesktopDscScripts1.2 NewDscConfig.ps1::61::21::File","ModuleName":"PSDesiredStateConfiguration","DurationInSeconds":"0.019","InstanceName":"TestFile","StartDate":"2017-05-21T18:57:40.6890000+02:00","ResourceName":"File","ModuleVersion":"1.1","RebootRequested":"False","ResourceId":"[File]TestFile","ConfigurationName":"Complete","InDesiredState":"True"}],"MACAddresses":["00-17-FA-00-00-0D","00-00-00-00-00-00-00-E0"],"MetaConfiguration":{"AgentId":"1B67D9E9-3E3F-11E7-8365-0017FA00000D","ConfigurationDownloadManagers":[{"RegistrationKey":"","ServerURL":"https://xpull1:8080/PSDSCPullServer.svc","ResourceId":"[ConfigurationRepositoryWeb]PullServer","ConfigurationNames":["Complete_xDC14"],"SourceInfo":"C:UsersInstall.BMWDesktopDscScripts2.2 SetupDScClients.ps1::26::9::ConfigurationRepositoryWeb"}],"ActionAfterReboot":"ContinueConfiguration","LCMCompatibleVersions":["1.0","2.0"],"LCMState":"Idle","ResourceModuleManagers":[],"ReportManagers":[{"RegistrationKey":"","ServerURL":"https://xpull1:8080/PSDSCPullServer.svc","ResourceId":"[ReportServerWeb]ReportServer","SourceInfo":"C:UsersInstall.BMWDesktopDscScripts2.2 SetupDScClients.ps1::34::9::ReportServerWeb"}],"StatusRetentionTimeInDays":"10","LCMVersion":"2.0","ConfigurationMode":"ApplyAndAutoCorrect","RefreshFrequencyMins":"30","RebootNodeIfNeeded":"True","SignatureValidationPolicy":"NONE","RefreshMode":"Pull","DebugMode":["NONE"],"LCMStateDetail":"","AllowModuleOverwrite":"False","ConfigurationModeFrequencyMins":"15","SignatureValidations":[]},"Locale":"en-US","Mode":"Pull"}

Now the data can be just taken to PowerShell and converted with ConvertFrom-Json and also SQL Server is happy.

When the LCM starts applying a configuration (Start-DscConfiguration), it writes an entry of type ‘Initial’ into the reporting database. This record has a StartTime but not yet a valid EndTime. Also, StatusData only contains some basic information about the node.

Note: The OperationType ‘Initial’ indicates that the node applies a configuration the first time. All subsequent applications are logged with the OperationType ‘Consistency’. The OperationType ‘LocalConfigurationManager’ logs the configuration of the LCM.

The trigger fires after an update happens. When the pull server send the StatusData to the database, backslashes are removed and the characters indicating an array in JSON.

[code lang=”sql”]
CREATE TRIGGER [dbo].[DSCStatusReportOnUpdate]
ON [dbo].[StatusReport]
AFTER UPDATE
AS
SET NOCOUNT ON
BEGIN
DECLARE @JobId nvarchar(50) = (SELECT JobId FROM inserted);
DECLARE @StatusData nvarchar(MAX) = (SELECT StatusData FROM inserted);
IF @StatusData LIKE ‘[%’ ESCAPE ”
SET @StatusData = REPLACE(SUBSTRING(@StatusData, 3, Len(@StatusData) – 4), ”, ”)

DECLARE @Errors nvarchar(MAX) = (SELECT [Errors] FROM inserted);
IF @Errors IS NULL
SET @Errors = (SELECT Errors FROM StatusReport WHERE JobId = @JobId)

IF @Errors LIKE ‘[%’ ESCAPE ” AND Len(@Errors) &gt; 4
SET @Errors = REPLACE(SUBSTRING(@Errors, 3, Len(@Errors) – 4), ”, ”)

UPDATE StatusReport
SET StatusData = @StatusData, Errors = @Errors
WHERE JobId = @JobId

END
[/code]

After the conversion, SQL Server can parse and query the data in the column StatusData as JSON. This is the process of getting to the details in a JSON-formatted column.

How to retrieve data from a JSON column

This query is getting just the “StartDate” for all nodes. StartDate is a value in the JSON column “StatusData”.

[code lang=”sql”]
SELECT dbo.StatusReport.NodeName, JSON_VALUE([StatusReport].StatusData, ‘$.Status’)
FROM dbo.StatusReport
[/code]

or

[code lang=”sql”]
SELECT dbo.StatusReport.NodeName,(
SELECT [Value]
FROM OPENJSON ([StatusData])
WHERE [Key] = ‘StartDate’
) AS StartDate
FROM dbo.StatusReport
[/code]

The functions “tvfGetNodeStatus” and “tvfGetRegistrationData” are for combining the data accessible directly using SQL and what is store as JSON. The queries in these functions are more complex, as there is JSON stored in JSON stored in SQL.

These two functions can be access through the views “vRegistrationData” and “vNodeStatusComplex” and these views are used by PowerBI.

PowerBI – the interesting part

Starting with a new workbook

So, after having the database in place and some nodes registered and have them already send some feedback, it is time to make the data visible.

After opening PowerBI you will see a welcome screen. There is an option named “Get data”. After clicking on that option, you will be guided through the process of setting up the connection. Please select “SQL Server database”, then you have to provide a server and database name and decide if you want to import the data or use DirectQuery. After finishing that you should see a list of all available sources. Please select all the views here (v*) and click on load.

powerbi_selectsource

After finishing this step, you have to choose a visualization. Click on the Pie Chart and you get a grey template on your empty workbook. Keep the focus on the Pie Chart and in the Fields menu on the right side expand the node “vNodeStatusComplex”. Please select from the field “Status” first and then “NodeName”. This will move “Status” to “Legend” and “NodeName” to “Details”.

powerbi_piechart1

Obviously, this does not work. Please drag and drop the “NodeName” from “Details” to “Values”. Voila, if all your DSC nodes are compliant, you have now a Pie Chart with just one big piece. In my environment, 2 out of 8 does have problems so it looks like this:

powerbi_piechart2

 

Using an existing workbook

If you want to get started quickly, you can download the PowerBI file Dashboard.pbix, the first screenshot has been taken from this file. You have to change the data source as your SQL Server pretty likely has a different name. Click on “Edit Queries -> Data source settings” and then on “Change Source”.

powerbi_changesource1

 

Summary

After walking through this article, you have a database on SQL Server 2016 that presents the node status data in a way that can be visualized with PowerBI or other tools. This moves DSC on a new level and should makes it more appealing for IT managers.


Calling SharePoint REST API with POST from Fiddler

$
0
0

This is a quick one act drama about how to use Fiddler to issue POST requests to a SharePoint REST API.

Act 1

Fiddler has a nice feature called Composer which can be used to create your own request with your own verb, header and content information.

Certain SharePoint web services will require GET, others POST calls. The POST call is just slightly different from a GET. There are a few things you need to keep in mind:

  1. Fiddler cannot authenticate against POST, so you should have a cookie available.
  2. You need to post an X-RequestDigest header.
  3. You might need to have a payload in the Message Body.

How you do the authentication, is up to you, as for me, I just issue a query from a browser, record the traffic, steal the cookie information and there you go. In theory Fiddler does the authentication for you (If you have the checkbox Automatically Authenticate set on the Options tab.) but that did not work reliably for me for SPO, so I dropped it.

So to get the Request Digest token, you just call a POST query against the _api/contextinfo web service.

Calling ContextInfo from Fiddler

The information will be in the FormDigestValue attribute:

FormDigestValue in the response

Now you can put this information into your next POST request’s header and there you go, you can test the API’s behavior.

POST call to an SPO web service

How To Create a Technet Blog (Microsoft employees only)

$
0
0

A lot of people have been asking ‘how do I create and post to a TechNet blog as a Microsoft Employee?’. Never fear, here is a clear and up to date set of steps to start your own MS Corp blog.

  1. Sign in with you personal account here
  2. Signing in for the first time will automatically direct you to the ‘Create your TechNet Profile’ page. Otherwise click the ‘Create a Profile’ link in the top toolbar. Follow the steps and you will now have a TechNet Profile.
  3. Affiliate your TechNet Profile with your MS Corp account here
    • For more info about different affiliations click here
  4. Next step is to create your blog.
    • Give your site a name (what will appear in the address i.e. blogs.technet.microsoft.com/becstech) – cannot be edited later
    • Give your site a title – can be edited later
    • Click ‘Create Site’
  5. You will be directed to your new blog site i.e. blogs.technet.microsoft.com/YOUR_SITE. Log in with your TechNet Profile and you will be able to post to the site.
  6. Create your first blog post by hovering over ‘New’ in the top toolbar and selecting ‘Post’.
    • NOTE: if you are not logged in with your Microsoft affiliated account you will not be able to post.

Looking forward to posting more myself and seeing what others have to share as well. Happy blogging fellow techies!

登録締め切り迫る!CSPリセラーの皆様へ期間限定インセンティブキャンペーンのご案内 ~マイクロソフトCSPパートナー企業様はどなたでもご参加可能!~【5/22 更新】

$
0
0

csp-0522

 

先日Blogでお知らせしておりましたCSP Power-upインセンティブキャンペーンの登録締め切りは61日(木)となっております。

CSP Power-upキャンペーンとは、CSPリセラーの皆様のご販売実績に応じてマイクロソフトがパートナー様に対してインセンティブをお支払いする期間限定キャンペーンで、CSPリセラーの皆様はどなたでもご登録いただけます。今から登録してもキャンペーンの全期間が対象になりますので、参加ご希望されるパートナー様はお急ぎご登録ください。

▼ CSP Power-upインセンティブキャンペーンご登録はこちらから 

 

インセンティブご獲得のためには、対象となるCSPサービスの販売が必要です。対象製品カテゴリは、CSP Office 365 / EMS / Dynamics 365 / Azureです。一つの製品カテゴリにおいて、対象期間中で、4社以上の新規顧客(※)に所定量を超えるご販売をいただければインセンティブが発生します。なお、所定量、対象期間、対象製品SKUや最低お支払い金額など、キャンペーンの詳細について、こちらからダウンロードいただける資料を必ずご確認ください。(資料のダウンロードはマイクロソフトパートナーネットワークIDが必要です。)

※新規顧客とは?:マイクロソフトクラウドサービスを初めて導入頂く企業様を指します。

 

本キャンペーンについてご不明な点等ございましたら下記事務局へメールにてお問合せください。

お問い合わせ先 :
CSPパートナー様向け キャンペーン事務局(csppwrr@microsoft.com)

お問い合わせ対応範囲 :
・キャンペーン登録方法

・登録後のダッシュボードサイトの見方
※本事務局窓口は、20176月末までの期間限定の運用です。

 

Коллекции и скорость их работы

$
0
0

 

Коллекции являются одним из ключевых элементов Configuration Manager. Приложения, обновления, конфигурационные элементы, политики – все это назначается на коллекции, и если с коллекциями начались проблемы, вы это быстро почувствуете.

 

Если вы нашли эту статью, пытаясь срочно разрешить уже возникшие проблемы со скоростью работы коллекций, переходите сразу к разделу “Устранение проблем” в конце текста.

Проблемы с коллекциями, по большей части, создают администраторы Configuration Manager, когда пишут правила членства. В особо тяжелых случаях, неудачное правило-запрос может остановить SQL серверы нескольких первичных сайтов иерархии. Эту статью я решил написать как раз после того, как я увидел такое у одного заказчика . Статья ориентирована на администраторов крупных или сильно нагруженных иерархий с несколькими сайтами и большим количеством клиентов. Если система маленькая, проблем, скорее всего, не возникнет.

 

Представьте себе ситуацию, когда на всех серверах SQL первичных сайтов иерархии начинает расти tempdb.log. Файл журнала Temp DB может расти только если какая-то транзакция не завершается, и продолжает собирать данные. Одновременно с этим, администраторы назначений жалуются, что все коллекции “подвисли” с “песочными часами”, и они не могут работать. Файл tempdb.log достигает размера уже 170 ГБ, место на диске с tempdb подходит к концу, SQL может встать на паузу. Если перезапустить SQL, процесс повторяется, место снова начинает заканчиваться.

 

Посмотреть в чём дело оказалось несложно, и об этом мы поговорим ниже. Была найдена коллекция, которая “вешала” Collection Evaluator’ы и нагружала все сервера SQL первичных сайтов иерархии.

Вот её, вроде как ничем не примечательный, WQL запрос:

 

select SMS_R_SYSTEM.ItemKey,
 SMS_R_SYSTEM.DiscArchKey,
 SMS_R_SYSTEM.Name0,
 SMS_R_SYSTEM.SMS_Unique_Identifier0,
 SMS_R_SYSTEM.Resource_Domain_OR_Workgr0,
 SMS_R_SYSTEM.Client0
 from vSMS_R_System AS SMS_R_System
 INNER JOIN SB_SCCM_Programs_DATA AS SMS_G_System_SCCM_Programs
 ON SMS_G_System_SCCM_Programs.MachineID = SMS_R_System.ItemKey
 INNER JOIN vSMS_G_System_SoftwareFile AS SMS_G_System_SoftwareFile
 ON SMS_G_System_SoftwareFile.ClientId = SMS_R_System.ItemKey
 where (SMS_G_System_SoftwareFile.FileName = N'PATCHSET13.dll'
 OR SMS_G_System_SCCM_Programs.PkgID00 = N'PR10028A' OR SMS_G_System_SCCM_Programs.PkgID00 = N'PR20028A'))

 

В среде заказчика (260 тысяч клиентов) запрос при своем выполнении “разносил” tempdb.log до 170+ ГБ, и не завершался.

 

Нюанс в том, что в запросе берутся все записи о компьютерах из представления v_R_System, и все файлы на этих компьютерах из v_GS_Software_File, для каждого компьютера. v_GS_Software_Files содержит данные Software Inventory, и в БД заказчика занимает объем 35 гигабайт. К этому добавляется представление SCCM_Programs из расширенной инвентаризации, содержащие перечень выполнявшихся на каждом клиенте пакетов и программ из реестра. Проще говоря, количество строк в одном представлении умножается на количество строк в остальных представлениях, и это ещё раз умножается на следующие представления. В комплекте идут два оператора ‘Or’, что тоже сказывается на скорости запроса и объеме обрабатываемых данных.

 

На выходе запрос выдавал десятки, а может и сотни миллионов строк, и мы не стали дожидаться его завершения. Ситуацию удалось исправить только сделав так, что все критерии в секции OR стали отдельными правилами этой коллекции, и обрабатывались отдельно. Такая коллекция наполнялась быстро и правильно.

 

Как работают коллекции

Прежде чем решать проблемы с коллекциями, нужно знать в общих чертах, как они работают. Представим это на примере иерархии из CAS и нескольких Primary сайтов и процесса администрирования. В этой статье мы не рассматриваем ConfigMgr 2007 и говорим лишь о последних версиях продукта.

 

  1. Администратор, подключившись консолью к CAS, создает новую коллекцию или изменяет уже имеющуюся. Он создает Collection Query Rule на языке WQL, которое по какому-то признаку отбирает компьютеры в эту коллекцию. Коллекция теперь отображается в консоли с “песочными часами”, так как ждет обновления.
  2. Через механизм DRS (Data Replication Service, репликация на основе собственного кода Configuration Manager в SQL Service Broker) эта коллекция попадает в БД других первичных сайтов. Коллекции глобальны, и попадают на все первичные сайты, где бы в иерархии они ни были бы созданы, то есть, если администратор подключается консолью к перичному сайту, и создает коллекцию “там”, она все равно попадает на CAS, и реплицируется на остальную иерархию. В этом случае процесс удлиняется на один шаг (Pri > CAS > Вся иерархия), поэтому работать все же рекомендуется с CAS (именно по этому он его назвали “Центральный административный сайт”).
  3. Компонент SMS_COLLECTION_EVALUATOR (Colleval) посредством триггеров в БД и служебных файлов в инбоксе colleval.box на каждом первичном сайте получает задание на пересчет правил членства нашей коллекции, и помещает его в один из своих пяти потоков-очередей (подробнее об этих потоках написано ниже). Если в очереди есть другие коллекции, то наша коллекция ожидает, когда обработаются те. За нашей коллекцией также может собраться очередь, пока членство в ней вычисляется. На центральном сайте компонент SMS_COLLECTION_EVALUATOR не присутствует, его там нет.
  4. Опять-таки на каждом первичном сайте, Colleval на сервере SQL выполняет запрос, который написал администратор в начале нашего процесса, но конвертированный из WQL в язык T-SQL. Это ключевой момент. Скорость обработки этого запроса – главное, что оказывает влияние на работу коллекций. Пока наш запрос вычисляется на сервере, другие коллекции ждут с “песочными часами”. Эту активность можно наблюдать в логе Colleval.log (включите повышенную детальность логов и SQL логирование в реестре, если хотите видеть больше), в SQL Management Studio в разделе Activity Monitor, в продвинутом случае – SQL Profiler. В работе Colleval задействована также папка инбоксов- InboxColleval.box.
  5. Когда членство в коллекции определено, с каждого сайта список машин через DRS посылается на CAS. Как только все первичные сайты пришлют свою часть информации, коллекция на CAS наполняется, “песочные часы” снимаются, администратор видит список компьютеров, а на первичных сайтах формируются политики из назначений, которые администратор поставил на эту коллекцию. Если на каком-то сайте линк репликации работает плохо, или SQL сервер не справляется с нагрузкой, коллекции могут “подвиснуть”, в этом один из многих недостатков иерархии из нескольких первичных сайтов и CAS.

 

Таким образом мы видим, что созданные самостоятельно коллекции – это фактически код, который самостоятельно создает администратор, и который выполняется в SQL. Запросы WQL система автоматически транслирует в язык запросов SQL. Сам транслированный в T-SQL запрос, как он пойдёт к базе данных, вы можете оценить в таблице Collection_Rules_SQL.

 

Если коллекций много, и написаны запросы неоптимально, “тормозит” написанный код, а не сам Configuration Manager. Если система большая, не стоит ждать работы в реальном времени, обновление коллекций может занимать от 10 минут до получаса и даже больше. Администраторы сами создают и должны контролировать нагрузку, то есть количество и “тяжесть” коллекций, ресурсы серверов SQL, которые не бесконечны.

 

Если коллекций несколько тысяч, то даже когда запросы в них не очень медленные, все равно может появиться задержка с обновлением. Это зависит от расписания обновления коллекций (вкладка Properties > Membership Rules). Когда администраторы выставляют слишком частое расписание, отдельные коллекции могут начинать обновляться раньше, чем заканчивает просчитываться предыдущий круг. Возникает очередь, и мы опять видим “песочные часы”. Как этого избежать – в разделе с рекомендациями по работе с коллекциями.

 

Подытожим – скорость обновления коллекций зависит от следующих факторов:

 

  • Качество WQL запросов в правилах коллекций
  • Количество коллекций и частота их обновления по расписанию
  • Ресурсы и быстродействие серверов SQL
  • Объем данных, из которых идет выборка
  • Своевременное обслуживание БД (индексы, статистика), которое штатной Mantenance Task не обеспечивается
  • Корректная работа межсайтовой репликации с первичными сайтами, если их несколько и есть CAS. Если с одним из сайтов линк отказал, коллекции могут оставаться в состоянии обновления

 

Потоки и работа SMS_COLLECTION_EVALUATOR

По сравнению с Configuration Manager 2007, в современных версиях продукта Colleval работает в несколько потоков. Разные виды обновления коллекций выполняются в разных потоках, это действительно важно знать, если нужно разобраться, почему плохо обновляются коллекции.

Colleval имеет четыре “основных” потока и два вспомогательных. Каждый поток является, по сути, отдельной очередью. Работу потоков можно наблюдать в логе colleval.log и дополнительной утилите CEViewer (часть Configuration Manager 2012 R2 Toolkit) .

Посмотрим, за что каждый из них отвечает:

 

  • Primary (также известен в colleval.log как Full)- отвечает за Full Collection Update по расписанию, установленному в свойствах коллекции.
  • Express (Incremental) – выполняет инкрементальное обновление тех коллекций, где оно включено.
  • Manual (обозначен как Single) – здесь обрабатываются коллекции, на которых администратор выполнил Update Collection Membership. В Manual попадают коллекции, у которых нет зависимостей.
  • Auxiliary является дочерним потоком Manual, и обрабатывает зависимости обновляемых вручную коллекций.
  • New – Для новых коллекций есть отдельный выделенный поток. Сюда попадают только что созданные коллекции, которые сразу же начинают просчитываться.

Incremental Update

Инкрементальные обновления коллекции можно включить, поставив соответствующую отметку в ее свойствах. Термин “инкрементальный” говорит нам о том, что выборка будет производиться только из тех записей, которые изменились в таблицах, на которые направлено правило коллекции. Это позволит делать выборку не из десятков миллионов строк, а лишь из тысяч изменившихся, и сэкономить время обновления коллекции.

Как это реализовано?

На многих таблицах, содержащих данные клиентов мы можем найти триггер trCollTrack_имя_таблицы. Когда вы создаете какой-нибудь новый класс инвентаризации, триггер также появляется там. Триггер срабатывает, когда какие-то записи в таблице меняются, и помечает их для выборки инкрементальным обновлением коллекций, если у вас есть какие-то запросы, ориентированные на эту таблицу.

Обратите внимание, что на таблицах с данными CI Compliance нет таких триггеров, и инкрементальные обновление там не работает.

Частота инкрементального обновления коллекций задается в свойствах сайта, и влияет на все инкрементальные коллекции. По умолчанию эта частота – раз в 5 минут. Старайтесь, чтобы количество коллекций со включенным инкрементальным обновлением не превышало 200.

 

Как работает расписание?

Как известно, начиная с Configuration Manager 2012, любая коллекция должна быть ограничена (т.е. делать выборку из) какой-то коллекцией. В итоге, все иерархическое дерево коллекций компьютеров у вас ограничено All Systems. Вы можете иметь где-то расписание обновления коллекций, или нет, но каждая ваша коллекция будет обновляться хотя бы раз в сутки, а именно в 4 часа ночи. Именно в это время выполняется Full Update коллекции All Systems, который вызывает каскад полного пересчета всех запросов каждой коллекции в иерархии. И это плавно подводит нас к теме цепочек зависимости коллекций друг от друга.

Цепочки обновления коллекций и зависимости

Как известно, любые созданные нами коллекции должны быть ограничены какой-то другой коллекцией, хотя бы All Systems. Они также могут исключать членов другой коллекции (Exclude Collection) или включать их (Include Collection).

Возьмем Коллекцию А, и ограничем ее All Systems (хоть это и не рекомендуется – для наглядности). Включим (Include rule) в нее Коллекцию B. Исключим (Exclude Rule) Коллекцию С.

По логике SMS_COLECTION_EVALUATOR, теперь наша Коллекция А зависит от трех коллекций: All Systems, B и C. Компонент так устроен, что обновление и добавление нового ресурса в любой из этих коллекций вызовет обновление нашей Коллекции А.

В 4 часа ночи All Systems выполняет full update, и Коллекция А тоже будет (как и все коллекции вообще – All Systems же).

Если на Коллекции B Full Update происходит каждый час – и Коллекция А будет обновляться каждый час, вне зависимости от расписания.

Если на Коллекции А включено инкрементальное обновление, она будет обновляться так же вслед за теми из своих зависимостей, где тоже включено инкрементальное обновление, и наоборот.

Вы можете наблюдать процесс построения цепочек или таблиц зависимости (Graph) в логе Colleval.log.

Чем больше у коллекции зависимостей, тем больше она будет обрабатываться.

Рекомендации по работе с коллекциями

Документация к продукту содержит рекомендацию не включать инкрементальное обновление более чем на 200 коллекциях. Помимо этого, существуют ещё нигде не описанные правила из жизни, которые могут помочь вам ускорить работу коллекций. Советы ниже пригодятся предприятиям с количеством клиентов 10 000 и более. При малых нагрузках оптимизировать коллекции не так необходимо.

Будьте осторожны с Direct Rule каждый раз, когда вы добавляете прямым правилом компьютер в коллекцию, это вызывает внеочередной Full Update данной коллекции, и всех коллекций, которые ограничены ей. То есть целый каскад полного обновления. Я много слышал нескольких заказчиках в Европе, которые используют Direct Rule в своем ПО автоматизации сервис деска, и которые испытывали проблемы с производительностью от десятков тысяч прямых правил.

Преимущества Query Rule перед Direct Rule:

  • Возможность обновляться по расписанию, и динамически добавлять/удалять членов без вмешательства администратора.
  • Query Rule может обновляться по расписанию, Direct Rule же остается привязанным к Resource ID добавленной машины навечно.
  • Не требует обслуживания (написал запрос и забыл)

Отдавайте себе отчет о стоимости запросов, содержащих оператор LIKE – используете его только где необходимо.

Поменьше используйте LIKE обрамленный двумя символами ‘%’, например Where SoftwareName LIKE ‘%Office%’. Такой запрос не использует преимущества индексов на полях, и проходит через каждую строчку в столбце, что может быть в десятки раз медленней.

Старайтесь еще меньше использовать NOT LIKE. С точки зрения производительности, это то же самое, что и LIKE, только еще медленней.

Стройте коллекции по индексируемым полям таблиц. Запросы по индексированным полям работают в 10-15 раз быстрей чем запросы по “обычным” полям. Когда пишете запрос, посмотрите, нет ли подходящего индексированного поля.

Как выяснить, на каких полях существуют индексы?

Выполните следующий запрос, чтобы получить список индексированных полей в таблицах БД Configuration Manager:

SELECT
     TableName = t.name,
     IndexName = ind.name,
     IndexId = ind.index_id,
     ColumnId = ic.index_column_id,
     ColumnName = col.name,
     ind.*,
     ic.*,
     col.*
FROM
     sys.indexes ind
INNER JOIN
     sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
     sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
     sys.tables t ON ind.object_id = t.object_id
WHERE
     ind.is_primary_key = 0
     AND ind.is_unique = 0
     AND ind.is_unique_constraint = 0
     AND t.is_ms_shipped = 0
ORDER BY
     t.name, ind.name, ind.index_id, ic.index_column_id;

 

Практический пример, как можно сделать правило коллекции медленным и быстрым способом.

Представим, что мы ищем машины с Microsoft Office Professional Plus 2013, и решили использовать представление v_gs_installed_software. В этом представлении есть два поля с названием ПО, одно из которых индексировано, другое – нет.

 

Медленный запрос, длящийся 100 секунд:

 

select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_INSTALLED_SOFTWARE on SMS_G_System_INSTALLED_SOFTWARE.ResourceId = SMS_R_System.ResourceId where SMS_G_System_INSTALLED_SOFTWARE.ARPDisplayName = "Microsoft Office Professional Plus 2013"

 

Быстрый запрос на 6 секунд:

 

select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_INSTALLED_SOFTWARE on SMS_G_System_INSTALLED_SOFTWARE.ResourceId = SMS_R_System.ResourceId where SMS_G_System_INSTALLED_SOFTWARE.ProductName = "Microsoft Office Professional Plus 2013"

 

Таким образом, найдя поле с индексом, мы ускорили время обработки коллекции в 15 раз. Попробуйте посмотреть теперь, что можно сделать с вашими коллекциями?

 

Найдите коллекции с неоптимальными запросами. Как это сделать?

(select vc.SiteID as [CollID],
vc.CollectionName, 'Not_Like' as Category, s.SQL
from v_Collections vc
inner join Collection_Rules_SQL s
on vc.CollectionID=s.CollectionID
where
s.SQL like '%not like%')
UNION
(select vc.SiteID as [CollID],
vc.CollectionName,
'Not_Equal'
as CAT,
s.SQL
from v_Collections vc
inner join Collection_Rules_SQL s
on vc.CollectionID=s.CollectionID
where s.SQL like '%<>%')

 

В случае “тяжелых” запросов, переносите нагрузку на клиентов, используя Compliance Settings.

Сделайте Configuration Baseline с набором CI, содержащими сложные вычислениямя, например, “если IP компьютера такой-то, и он содержит такой-то файл, при этом у него есть такая-то служба и запись в реестре, то он будет соответствовать этому базовому шаблону”. Стройте коллекции уже на основе бинарного признака Compliant = Yes/No относительно этого шаблона, и коллекции будут выполняться моментально. Ещё раз отметим, что не стоит включать такие коллекции для инкрементального обновления – таблицы, связанные с CI, не содержат триггеров механизма инкрементальных обновлений. Вам придется полагаться на полное расписание для обновления членства. Тем не менее, подсчет соответствующих или нет машин должен происходить быстро, и на загружать сервер.

 

Устранение проблем с работой коллекций

Обычно проблемы с коллекциями начинают выражаться в том, что множество колекций в консоли повисает с “песочными часами”. Правила создаются, но ресурсы в коллекции не попадают. Либо коллекций слишком много и они слишком часто обновляются, либо существует одна или несколько коллекций с неудачными правилами-запросами.

 

Поиск и устранение проблем с производительностью можно свести к одному алгоритму:

  1. Проверьте межсайтовую репликацию, если у вас есть CAS. Если один из сайтов испытывает проблемы с SQL или связью с иерархией, коллекции на CAS могут прекратить обновляться, пока проблема не будет устранена.
  2. Проверьте нагрузку на серверы SQL всех первичных сайтов, прежде всего по процессорам, записи на диск с БД, памятью. Если серверы с трудом справляются с нагрузкой, коллекции будут работать медленно.
  3. Почитайте логи <ConfigMgr>Logscolleval.log и статусные сообщения нашего компонента в консоли (Monitoring > System Status > Component Status > SMS_COLLECTION_EVALUATOR) на наиболее занятых первичных сайтах, можно начать с одного. Есть ли в логах ошибки в работе с SQL сервером? Проблемы со связью, записью в таблицы? Идёт ли работа в colleval.log? Если ошибки с SQL есть, необходимо устранить их, дело не в коллекциях. Установите фильтр cmtrace.exe (вы же ей открывали colleval.log?) на слово seconds. Вы увидите в реальном времени, сколько секунд уходит на обработку правил. Если нормальная работа в colleval.log видна, переходите к следующему пункту. Помните, что все потоки Colleval пишут в этот лог, и если один из них застрял на определенной коллекции, лог все равно не встанет колом, а будет обновляться и дальше от других потоков. Обновляющийся лог это не показатель безпроблемной работы коллекций.Обратите внимание, что сообщения в логе “Failed to manage all files in inbox. Will retry on next processing cycle” не являются проблемой и не мешают работе системы – это косметический дефект, возникающий когда коллекцию создали и быстро удалили, а файлы-триггеры в инбоксе остались. Старые файлы можно удалить вручную, это не навредит.В случае необходимости, можно увеличить максимальный размер файла лога, и включить SQL логирование через реестр на сервере сайта.
  4. Запустите CEViewer на одном или нескольких первичных сайтах. Предпочтение отдайте тому сайту, где больше всего клиентов, либо у которого самый медленный SQL – там запросы идут наиболее тяжело. Оцените общую ситуацию. Закладка All Queues даст представление о том, насколько быстро обновлятся коллекции, какова очередь, что вообще происходит. Что происходит в Running Evaluations? Двигается ли очередь?Зайдите во вкладки с разными видами очередей (это потоки, которые описаны в этой статье выше) и проверьте время обновления коллекций в секундах. Если у вас есть коллекции, обновляющиеся больше 60-100 секунд, это повод крепко задуматься над их оптимизацией. Есть вероятность, что ваши коллекции “висят” из-за того, что накопилась критическая масса долго выполняющихся правил. Если это так, посмотрите раздел “Рекомендации по построению коллекций”, и попробуйте оптимизировать свои правила. Если проблема возникла внезапно и раньше задержек не было, скорее всего кто-то создал долго выполняющийся запрос, который мы сможем выявить в следующем шаге.
  5. Откройте SQL Management Studio и выполните на SQL первичного сайта запрос, который покажет процессы SMS_COLLECTION_EVALUATOR, работающие или приостановленные прямо сейчас:
    SELECT sess.program_name,
    sqltext.TEXT,
    req.session_id,
    req.status,
    req.command,
    req.cpu_time,
    req.total_elapsed_time
    FROM sys.dm_exec_requests req
    Left join sys.dm_exec_sessions sess on sess.session_id = req.session_id
    
    CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
    WHERE sess.program_name like 'SMS_COLLECTION%'
    ORDER BY req.total_elapsed_time DESC

    Запросы выводятся в порядке времени выполнения (поле total_elapsed_time). В поле SQLText мы видем текст этих запросов. Один из них, вероятно, является “тяжелым” запросом из вашей коллекции. Может так случиться, что этот запрос никогда не завершается, поэтому в предыдущем шаге, в CEViewer вы его времени выполнения никогда не увидете. Именно этот случай произошел в начале статьи. Если запрос какой-то коллекции выполняется весьма долго, то в colleval.log вы этого также можете не увидеть. Лог будет бежать дальше, так как другие коллекции в других потоках будут считаться нормально. Например, инкрементальное обновление коллекций будет работать, в то время как обсчет новых коллекций будет введен в ступор вашим запросом.

     Посмотрите текст запроса в поле TEXT, найдите в нём откуда идет выборка данных (после оператора FROM).

    Скопируйте названия этих таблиц или небольшой кусок запроса вокруг них, выполните новый запрос, чтобы найти проблемную коллекцию

    select * from v_Collections
     where CollectionID in
     (select CollectionID from collection_rules where collectionID in
     (select collectionid from collection_rules_sql
     where sql like‘%ЧАСТЬ ТЕКСТА ПРОБЛЕМНОГО ЗАПРОСА%’
     ))

    В результате вы найдете проблемную коллекцию, и сможете приступить к её оптимизации. Если этот конкретный запрос прямо сейчас в статусе Running в списке задач –
    Зайдите на сервер SQL и проверьте размер файлов TempDB, tempdb.log. Растут ли эти файлы прямо сейчас? Если рост некотролируемо продолжается, попробуйте изменить запрос коллекции на тот, что будет работать нормально, или просто удалив неудачное правило.Затем на ваших SQL серверах в SQL Management Studio зайдите в Activity Monitor (прав. кнопка мыши на сервер, Activity Monitor), далее Processes, и завершите процесс от SMS_COLECTION_EVALUATOR с вашим неудачным запросом.

 

Вот, собственно, и всё, что я пока могу рассказать вам о работе с коллекциями. Если у уважаемых читателей есть какие-то дополнения или комментарии, мы будем рады их прочитать!

 

 

Mitigate risk and capitalize on profitable new opportunities with SiteZeus

$
0
0

SiteZeus Logo large RGB

Located in Tampa, Florida, SiteZeus is a startup company developing cloud-based location intelligence platforms that are intended to help businesses locate and capitalize on profitable opportunities. The company’s flagship service, Synergy, is a big-data platform that uses machine learning and artificial intelligence to help businesses visualize market potential and analyze the specific features driving their local, regional, and national sales. In other words, Synergy will help you predict store revenues for your existing business locations, as well as analyze which locations will be the most profitable to open new stores. Synergy also provides you with specific details on which methods of advertising will be most effective in a given area or neighborhood – helping your new stores mitigate risks and increase profitability.

Founded in 2013 by brothers Keenan and Hannibal Baldwin, SiteZeus has quickly achieved acclaim in the national startup community. In 2016 SiteZeus was honored to be recognized as Startup of the Year by the Business Intelligence Group (BIG), and was also included in the CIO Review’s list of the Top 100 Big Data Solution Providers.

The Baldwins’ prior experience investing in a variety of retail brands led the pair to realize that they would need a powerful technology stack to deliver SiteZeus. After workshopping several cloud platforms, the brothers decided that Azure’s seamless integration and advanced analytics made it their ideal solution. Hosted in the Azure cloud, SiteZeus’s back-end solution leverages SQL Azure as a primary database and SQL R-Services to facilitate their platform’s complex statistical models. On the front end, the SiteZeus team utilized Visual Studio because of its deep integration with Azure, and ASP.NET for its agile deployment capabilities. The application also uses Web Roles for business intelligence, and Service Web Roles to distribute complex analytics.

“The Azure technology stack and development tools have been instrumental in allowing us to release our product at a much faster pace,” says SiteZeus Marketing Director Jorge Hermez, “We host our application on Azure which has eliminated the need to sink a lot of money into building our own secure data center. Building our environment on Azure couldn’t have been easier. Microsoft takes care of everything from the hardware to the Operating System, and we can focus on building a great application. We are very happy we chose to build on Azure.”

working-in-the-office-8
View SiteZeus product demo here.

+++++++++++++++++++++++++

Microsoft is helping these startups succeed through its BizSpark program. To join or see other startup stories, visit us at our website here. To listen to our startups, check out these podcasts on devradio here

About BizSpark:  Microsoft BizSpark is a global program that helps startups succeed by giving free access to Microsoft Azure cloud services, software and support. BizSpark members receive up to $750 per month of free Microsoft Azure cloud services for 3 years: that’s $150 per month each for up to 5 developers. Azure works with Linux and open-source technologies such as Ruby, Python, Java and PHP. BizSpark is available to startups that are privately held, less than 5-years-old and earn less than $1M in annual revenue.

Viewing all 34890 articles
Browse latest View live