Category Archives: Windows PowerShell

My Windows PowerShell blog. This is my personal review and opinion!

Bangalore PowerShell User Group DSC Work Shop – July 18, 2015

Bangalore PowerShell User Group DSC Work Shop – July 18, 2015

vs-powershell

  • Are you in INDIA?
  • Are you an IT Pro?
  • Are you a Dev?
  • Looking for Automation?
  • IT Manager looking for a bridge between IT Pro’s and Dev’s?
  • Want to learn or know about DEVOPS?

Just 1 day to go!

Bangalore PowerShell User Group announced a Work Shop event to showcase DSC Basics and Advanced topics. Let’s go declarative ! Stop not! @PSBUG opened a gate. Yeah! Book for the workshop and make use of it. Come and explore! Learn and Share!

 

Start-DSCConfiguration WMF 5.0 Multiple Nodes Issue

I am one among the many beginners in PowerShell Desired State Configuration. Recently I saw the TechNet Forum Post so thought of sharing my experience

Error

The WinRM client cannot process the request. The object contains an unrecognized argument: “JobId”. Verify that the spelling of the argument name is
correct.
    + CategoryInfo          : MetadataError: (root/Microsoft/…gurationManager:String) [], CimException
    + FullyQualifiedErrorId : HRESULT 0x803381e1
    + PSComputerName        : DSC2

How to Produce this in WMF 5.0?
Configuration DesiredStateConfigurationDemo
{
    Param([String[]]$ComputerName)
    Import-DscResource -ModuleName xWindowsUpdate
    Node $computerName
    {
        
        xHotFix InstallWMF5
        {
            Path = '\\DSC1\C$\DSCShare\Updates\Some.MSU'
            Id = 'KBsomeid'
            Ensure = 'Present'
        }
    }
}

DesiredStateConfigurationDemo -ComputerName DSC1 , DSC2
Start-DSCConfiguration .\DesiredStateConfigurationDemo -wait -verbose -force

In middle of demo I couldn’t think about anything else. Since few of my clients were eager to get advantages of DSC – So, I just applied configuration using below code – Our Own PowerShell 🙂

'DSC1' , 'DSC2' | %{Start-DSCConfiguration .\DesiredStateConfigurationDemo -ComputerName $_ -wait -verbose -force}

 

 

Upload High Resolution Picture in Exchange Online

Set-UserPhoto Error – Now Solved 🙂

Error:

 

Proxy method PSWS:
Request return error with following error message:
The remote server returned an error: (413) Request Entity Too Large…
+ CategoryInfo          : NotSpecified: (:) [Set-UserPhoto], CmdletProxyException
+ FullyQualifiedErrorId : Microsoft.Exchange.Configuration.CmdletProxyException,Microsoft.Exchange.Management.RecipientTasks.SetUserPhoto

More Information:

Logged an issue in Connect

Refer to the Workaround posted which might have helped some. Unfortunately it didn’t work in WMF 4.0 at all. Recently, I thought of testing the case in Connect to explore some foot prints.

Reason:

The reason for the error is quite simple – Exchange Online will not allow images greater than 10 KB and 96 x 96

 Solution:

I tried to upload an image using the below PowerShell Code

Set-UserPhoto "Chendrayan" -PictureData ([System.IO.File]::ReadAllBytes("C:\Temp\TestImage.jpg")) -Confirm:$false
Image Information:
2015-04-14_13-38-27
Conclusion:

Updated TechNet Article

Query AD and Update SQL Express Table Using PowerShell

Requirement

Query AD [Active Directory] computers and insert into SQL Express.

Considerations

Requirement is just an one liner. We need to consider a lot before we deliver this to production.

  • Do we need all computers from AD or just enabled? Yeah! We need only enabled computers. If Admin disables / enables a computer or remove / adds a computer in AD the SQL express table should update accordingly.
  • Do we need only client operating systems? Yeah! We need this is for Client OS reporting.

Summary

To summarize the requirement customer needs a solution which should do the below tasks.

  • Insert if new Computer found in AD.
  • Drop if computer is removed.
  • Update properties if any change identified.

Solution

  • Query AD with Filter ON [Enabled -eq $true and OperatingSystem -eq ‘Windows 7 Enterprise’].
  • Insert If exists.
  • Drop Row if SQL Express rows doesn’t match AD value.[Removed from AD but exists in SQL table]
  • If new computer found insert into table.

PowerShell Code

 #Establish Connection to SQL Express
$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=Localhost\SQLExpress; Initial Catalog=Employee; Integrated Security=SSPI")
$conn.Open()

#Query AD and Update SQL Table
Get-ADComputer -Filter {(Enabled -eq $true) -and (OperatingSystem -eq 'Windows 7 Enterprise')} -Properties * | %{

$Name = $_.Name 
$OS = $_.OperatingSystem 
$LastLogonDate  = $_.LastLogonDate 
$PasswordLastSet = $_.PasswordLastSet
$Description = $_.Description 
$DN = $_.DistinguishedName
$Enabled = $_.Enabled

$cmd = $conn.CreateCommand()
$query = @"
IF EXISTS (Select * from ComputerInformation Where ComputerName = '$Name')
Delete from ComputerInformation where ComputerName <> '$Name'
ELSE
INSERT INTO ComputerInformation VALUES ('$Name' , '$OS' , '$LastLogonDate' , '$PasswordLastSet' , '$Description' , '$DN' , '$Enabled')
"@
$cmd.CommandText = $query
$cmd.ExecuteNonQuery()
}

#Close the connection
$conn.Close()

 

Exploring LYNC Contacts Using PowerShell

Exploring LYNC Contact folders using PowerShell.

Get-MailboxFolderStatistics will display all the folders information in users mailbox. So using this we can explore LYNC Contacts with the folder type ‘Quick Contacts’.

Get-MailboxFolderStatistics -Identity <MailboxID> | 
? {$_.FolderType -eq 'QuickContacts'}

Lync Contact Folders with 0 EntriesLync Contact Folders with 0 Entries

If we delete lync contacts programmatically it may appear as GUID as well. Like shown below.

Get-MailboxFolderStatistics -Identity <MailboxID> | 
Select Name , ItemsinFolder | ft -AutoSize

2Underneath Contacts we can see two GUID – That’s LYNC and GAL Contacts

Refer this article to remove LYNC contact entries using PowerShell and EWS

How to Explore all folders?

PowerShell Tip: String Manipulation using Regular Expression

Summary

  • Regular Expression is very Powerful and best way to play with strings.
  • Using REGEX in PowerShell is best way to query log files, pattern matching etc.., however we should use it as applicable.

Example Code

#Given Name : Chendrayan Venkatesan
#Required Output: Venkatesan , Chendrayan
"Chendrayan Venkatesan" -replace "([a-z]+)\s([a-z]+)" ,'$2, $1' 

#Given Name : Chendrayan12345 Venkatesan
#Required Output: Venkatesan, Chendrayan
'Chendrayan12345 Venkatesan' -replace "\d+" -replace "([a-z]+)\s([a-z]+)" ,'$2, $1'

 

Get OU Included in SharePoint User Profile Synchronization Configurations

Summary

This TechNet Wiki is to share PowerShell Snippet which retrieves Included OU in SharePoint 2010 User Profile Synchronization. Ensure you are farm admin while executing the script. Please do read the code and execute in acceptance and then in Production.

Background

This morning we received some email alerts “Your Mysite is marked for deletion”. Indeed user ID is not disabled but moved from one OU to other OU So what’s wrong in it. Nothing much if your SharePoint 2010 UP SYNC Connections has all the OU’s. If not it’s a challenge. You can review more articles in web. We started analyzing the issue – Technically each and every SP admin had different opinion.

Conclusion

Hey SP Admins get me the Included OU list in SharePoint UPS SYNC. Follow the below process

  1. Disable MySite Clean Up Timer Job.
  2. Edit Sync settings.
  3. Drill down the Forest and get me the OU names.

Solution

Above steps are easy to draft as solution document but it’s huge work for SP Admins (Indeed I am part of SP Admin Team). Running Mysite clean up job manually will become an operational task. We do have one step solution – Open SharePoint Shell Management and execute the below code

Add-PSSnapin Microsoft.SharePoint.PowerShell
$userprofileService = @(Get-SPServiceApplication | Where-Object {$_.TypeName -eq 'User Profile Service Application'})[0]
$context = [Microsoft.SharePoint.SPServiceContext]::GetContext($ups.ServiceApplicationProxyGroup,[Microsoft.SharePoint.SPSiteSubscriptionIdentifier]::Default)
$ConfigMgr = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($context)
$AD = $ConfigMgr.ConnectionManager
$AD | Select -ExpandProperty NamingContexts | Select -ExpandProperty ContainersIncluded

 

SharePoint 2010 Publishing Feature Activation

One of our clients reported an issue while editing the home page of SharePoint portal.

Error: “An Unexpected Error Occurred”

Impact: Unable to save the changes made.

Reason Provided by the customer: Power User tried to deactivate and activate the publishing feature.

Team tried reactivating the publishing feature which caused more pain. The Navigation bar was broken in the home page. (Expected SP 2010 Behavior).

Fix: Activate SP 2010 Publishing Feature using PowerShell (Force it with Proper Bag Parameter)

1. Installed SharePoint Manager 2010

2. Explored the property bag to identify the TRUE value of Publishing Feature

3. Though the User Interface shows the feature as ACTIVATED and PowerShell output gave the same result. But, the knot is the [“__PublishingFeatureActivated”] was set to FALSE in property bag.

4. No option to right click to activate (Sounds More Cranky) – But no other go, I took a chance to implement the below PowerShell code.

#Solution: SharePoint 2010 - PowerShell
#To activate the publishing feature in SP2010 portal
[System.Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null 
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null 
$site = Get-SPSite "http://www.yourportal.com/"
$web = $site.openweb()
$Web.AllProperties["__PublishingFeatureActivated"]="True" 
$Web.Update()
#If SP 2010 fails to read the __PagesListsID (Internal Name). I prefer to do the below
 
$web = get-spweb "http://www.yourportal.com/"
$correctId = $web.Lists["Pages"].ID
$web.AllProperties["__PagesListId"] = $correctId.ToString()
$web.Update()