PowerShell or Command Prompt, Change Folder

For the new breed of SharePoint developers, and using VS-Code for many projects, and even PowerShell, I’m jumping into a command window A LOT these days.

Click the Windows key

Type ‘cmd’ or ‘powershell’

Often, I need to switch over to a specific folder – and type in :

cd “C:\folder\whatever client\project name”

OR – Copy the folder address from Windows Explorer :

image

And then have to paste the address (right-mouse-click) – not forgetting quotes :

image

BUT – there’s a great quick shortcut to this – and it’s AWESOME.

Really.   Awesome.

Within the Windows Explorer bar – just type “PowerShell” (or “cmd”)

Hit ENTER on the keyboard

image

And – you instantly get a PowerShell window – starting in the same folder.image

Same works for CMD – how amazing is that !! 

Smile

Advertisements

Deploy Azure Function, using PowerShell

One of my favourite parts of AZURE is the way you can incorporate a set of PowerShell, in a callable wrapper – or via a Timer – aka, scheduled task.

You can then call this from within a Microsoft Flow – in Office 365 – or have a timer that then awakens, and does something.

My function is simple enough – it logs in to SharePoint, and checks a document library – and then emails a combined reminder list – once a day.

Deploying is easy – when you have access to the Azure tenant – but for a SCRIPTED deployment, I had a bunch of tasks to get through :

  1. Coffee
  2. Create Azure Resource Group – ie. a bucket for all the elements
  3. Create Azure Storage Account
  4. Create Azure Function App
  5. Update some Azure Function App Settings
  6. Upload the Azure Function code (PowerShell)
  7. Upload the MODULE files also
  8. Beer

** I can’t help with step #1 (long black or “Americano”) – or #8 (Sample, or 150 Lashes) – but here’s some tips/code for the other bits.

Smile 

1. Coffee (and login)

Execute the command to connect to Azure – you get a dialog box for username/password :

2. Create Azure Resource Group

image

3. Create Azure Storage Account

image

4. Create Function App

image

5. Update Azure Function Settings

Some of these are necessary for the operation of the Azure Function – others are just CUSTOM for my use/needs – eg. connecting to Office 365 has a User/Password + URL

image

6. Upload Azure Function – from PowerShell file

The contents of the PS1 file are loaded, and the set in the “props” when adding a new Azure Resource – I’m using a timer trigger – you could also do a HTTP trigger.

image

7. Upload the MODULE files for the Azure Function

I used an updated version of the code within this blog post – to push files into the “modules” folder – which is needed for SharePoint Client / CSOM and such.

http://blog.octavie.nl/index.php/2017/03/03/copy-files-to-azure-web-app-with-powershell-and-kudu-api

I have a subfolder called “modules” – with the actual files.    (eg. C:\dev\modules)

image

8. Beer

Well, before we do that – here’s the entire script – using a heap of Azure RM PowerShell functions – you’ll need to install those, if you don’t have them.

Here’s a list of all the commands I’ve used :

  • Get-AzureRmResource
  • Get-AzureRmResourceGroup
  • Get-AzureRmStorageAccountKey
  • Get-PublishingProfileCredentials
  • Invoke-AzureRmResourceAction
  • New-AzureRmResource
  • New-AzureRmResourceGroup
  • New-AzureRmStorageAccount
  • Set-AzureRMWebApp
  • Test-AzureName

Source Code

Hope this works for you – it was a fun process to piece it all together :

$location = ‘Australia Southeast’

$resourceGroupName = ‘rgqwerty’

$storageAccount = ‘saqwerty’

$functionAppName = ‘faqwerty’

$functionName = ‘azurefunctionqwerty’

$SourceFile = ‘sourcefile.ps1’

# =========================================================================

$resourceGroup = Get-AzureRmResourceGroup | Where-Object { $_.ResourceGroupName -eq $resourceGroupName }

if ($resourceGroup -eq $null)

{

New-AzureRmResourceGroup -Name $resourceGroupName -Location $location -force

}

# =========================================================================

if (!(Test-AzureName -Storage $storageAccount))

{

New-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -AccountName $storageAccount -Location $location -SkuName “Standard_LRS”

}

# =========================================================================

$functionAppResource = Get-AzureRmResource | Where-Object { $_.ResourceName -eq $functionAppName -And $_.ResourceType -eq ‘Microsoft.Web/Sites’ }

if ($functionAppResource -eq $null)

{

New-AzureRmResource -ResourceType ‘Microsoft.Web/Sites’ -ResourceName $functionAppName -kind ‘functionapp’ -Location $location -ResourceGroupName $resourceGroupName -Properties @{} -force

}

# =========================================================================

$keys = Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -AccountName $storageAccount

$accountKey = $keys | Where-Object { $_.KeyName -eq “Key1” } | Select Value

$storageAccountConnectionString = ‘DefaultEndpointsProtocol=https;AccountName=’ + $storageAccount + ‘;AccountKey=’ + $accountKey.Value

$AppSettings = @{}

$AppSettings = @{‘AzureWebJobsDashboard’ = $storageAccountConnectionString;

‘AzureWebJobsStorage’ = $storageAccountConnectionString;

‘FUNCTIONS_EXTENSION_VERSION’ = ‘~1’;

‘WEBSITE_CONTENTAZUREFILECONNECTIONSTRING’ = $storageAccountConnectionString;

‘WEBSITE_CONTENTSHARE’ = $storageAccount;

‘CUSTOMSETTING1’ = ‘CustomValue1’;

‘CUSTOMSETTING2’ = ‘CustomValue2’;

‘CUSTOMSETTING3’ = ‘CustomValue3’}

Set-AzureRMWebApp -Name $functionAppName -ResourceGroupName $resourceGroupName -AppSettings $AppSettings

# =========================================================================

$baseResource = Get-AzureRmResource -ExpandProperties | Where-Object { $_.kind -eq ‘functionapp’ -and $_.ResourceType -eq ‘Microsoft.Web/sites’ -and $_.ResourceName -eq $functionAppName }

$SourceFileContent = Get-Content -Raw $SourceFile

$functionFileName = ‘run.ps1’

#schedule – run every 1am every day

$props = @{

config = @{

‘bindings’ = @(

@{

‘name’ = ‘myTimer’

‘type’ = ‘timerTrigger’

‘direction’ = ‘in’

‘schedule’ = ‘0 0 1 * * *’

}

)

}

}

$props.files = @{$functionFileName = “$SourceFileContent”}

$newResourceId = ‘{0}/functions/{1}’ -f $baseResource.ResourceId, $functionName

# now deploy the function itself

New-AzureRmResource -ResourceId $newResourceId -Properties $props -ApiVersion 2015-08-01 -force

# =========================================================================

function Get-PublishingProfileCredentials($resourceGroupName, $webAppName)

{

$resourceType = “Microsoft.Web/sites/config”

$resourceName = “$webAppName/publishingcredentials”

$publishingCredentials = Invoke-AzureRmResourceAction -ResourceGroupName $resourceGroupName -ResourceType $resourceType

-ResourceName $resourceName -Action list -ApiVersion 2015-08-01 -Force

return $publishingCredentials

}

function Get-KuduApiAuthorisationHeaderValue($resourceGroupName, $webAppName)

{

$publishingCredentials = Get-PublishingProfileCredentials $resourceGroupName $webAppName

return (“Basic {0}” -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes((“{0}:{1}” -f

$publishingCredentials.Properties.PublishingUserName, $publishingCredentials.Properties.PublishingPassword))))

}

function UploadFile($kuduApiAuthorisationToken, $functionAppName, $functionName, $fileName, $localPath )

{

$kuduApiUrl = “https://$functionAppName.scm.azurewebsites.net/api/vfs/site/wwwroot/$functionName/modules/$fileName”

$result = Invoke-RestMethod -Uri $kuduApiUrl `

-Headers @{“Authorization”=$kuduApiAuthorisationToken;”If-Match”=”*”} `

-Method PUT `

-InFile $localPath `

-ContentType “multipart/form-data”

}

# =========================================================================

$accessToken = Get-KuduApiAuthorisationHeaderValue $resourceGroupName $functionAppName

$moduleFiles = Get-ChildItem ‘modules’

$moduleFiles | % {

Write-Host “Uploading $($_.Name) … ” -NoNewline

UploadFile $accessToken $functionAppName $functionName $_.Name $_.FullName

Write-Host -f Green ” [Done]”

}

Change SharePoint Browser Tab Icon – FAVICON using jQuery

Within SharePoint, you can set the “FAVICON” to a specific url within the MASTER PAGE, by updating the HTML markup.

<link rel=”shortcut icon” href=”/_layouts/15/images/favicon.ico?rev=23” type=”image/vnd.microsoft.icon” id=”favicon” />

BUT – what if you don’t want to change the master page ?   

(which, you SHOULDN’T do, for Office 365)

A simple jQuery update will do it :

$(document).ready(function () {
     //change the FAVICON
     $(‘#favicon’).attr(‘href’, ‘/sites/GLOBAL/SiteAssets/IMG/favicon.ico’);
});

Create SPWeb in Office 365, using Custom Site Template (PowerShell)

When you need to create a LOT of SharePoint subsites, you can do a script with PowerShell – using the Microsoft.SharePoint.Client.WebCreationInformation class/object.

The steps are basically :

  • Connect to O365
  • Define the settings for the new WebSite
  • Add to WEBS
  • Context.ExecuteQuery

Here’s the PowerShell I’m using (see below to copy+paste) :

image

The tricky part – for a CUSTOM WEB TEMPLATE is knowing what “ID” to use.

Ordinarily, the STS#0 will create a team site – but how to get the ID for my custom site template ??

There’s a quick tip – via the UI – when you go to create a new SUB SITE – using the F12 developer tools.    See that <option> tag ??

<option value=”{24ECC832-383F-4C5E-B658-9A640EA73509}#Client Site Template”>Client Site Template</option>

image

*THAT* is the value you need to include – in the PowerShell as above…

And then you just call the “CreateSubSite” function – and stamp ‘em out.

Smile

======================================

$urlAdmin = “https://AVENGERS-admin.sharepoint.com

$user = “TONY.STARK@AVENGERS.com”

$password = “PepperPottsIsAwesome!”

$urlSite = “https://AVENGERS.sharepoint.com/sites/clients”

$passwordSecureString = ConvertTo-SecureString -string $password -AsPlainText -Force

$credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $user, $passwordSecureString

Connect-SPOService -Url $urlAdmin -Credential $credential

$spoCredentials = New-Object -TypeName Microsoft.SharePoint.Client.SharePointOnlineCredentials -argumentlist $user, $passwordSecureString

$spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($urlSite)

$spoCtx.Credentials = $spoCredentials

$spoCtx.RequestTimeout = “500000”

function CreateSubSite($title)

{

$WCI = New-Object Microsoft.SharePoint.Client.WebCreationInformation

$WCI.WebTemplate = “{24ECC832-383F-4C5E-B658-9A640EA73509}#Client Site Template”

$WCI.Description = $title

$WCI.Title = $title

$WCI.Url = $title

$WCI.Language = “1033”

$spoCtx.Web.Webs.Add($WCI)

$spoCtx.ExecuteQuery()

}

CreateSubSite “Ragnarok”

CreateSubSite “Anotherrok”

Breadcrumb for Office 365 (SharePoint Online)

One of the user-friendly + familiar navigation elements within SharePoint is the ‘breadcrumb’.   This has been removed from the standard SP2013 and O365 display – but is fairly easy to add back.

The simple tips, from some Googling, is to update the MasterPage – and remove the ‘display:none’ settings.

BUT – I don’t want to have make changes to my MASTER PAGE.

The other consideration is that people (users) don’t really need to jump back up the chain of breadcrumbs, but only need to “go up”.

ParentWeb via REST

My solution was to use some jQuery – and call the REST endpoint to get the parent web – and then poke in some HTML for this HREF.

image

Once you have jQuery in place (via JS Injection), then just refer to a JS file with the following code.    

Lastly, find a nice UP icon from an images search, or icon library, or use the one below – scroll to the bottom – and add a comment, while you’re there…    Smile

image

This handles the TOP site also – and doesn’t add the UP icon – as it’s already the top site.    And there is a hover text showing “back up to > xxxxxx” from the parent web title.

Thanks to this blogpost from Shantha Kumar T, for the REST + Parent Web idea…

Here’s the code – if you’d like to copy/paste – let me know if you find this useful !

$.ajax(

{

    url: _spPageContextInfo.webAbsoluteUrl + “/_api/web/parentweb”,

    method: “GET”,

    headers: {“Accept”: “application/json; odata=verbose”},

    success: function(data)

    {

if (data.d.ServerRelativeUrl)

        {

            console.log(‘Parent site title: ‘ + data.d.Title)

var upSiteUrl = “”;

            upSiteUrl += “<span class=’upLink’>”

            upSiteUrl += “<a href='” + data.d.ServerRelativeUrl + “‘ title=’Back up to > ” + data.d.Title + “‘>”

            upSiteUrl += “<img src=’/sites/global/SiteAssets/IMG/up16.png’>”

            upSiteUrl += “</a>”

            upSiteUrl += “</span>”;

            $(‘#zz11_RootAspMenu’).before(upSiteUrl);

        }

    }

});

Icons – originally as a 128×128 – I resized to 16×16 – and changed the colour using PAINT.NET.

up16up

Problems with 4K UHD and HyperV VM

As part of my new ‘kachirho’ company setup, I’ve purchased a new laptop – DELL XPS15 9550…    It’s a beast with new SkyLake i7 6700 processor – and 16GB RAM – and 512 SSD – see here for a YouTube review.   And it looks super-sexy with carbon finish…

It’s got the new (almost 4K) UHD resolution – 3840×2160 – and touch screen.   The visuals on this resolution are amazing – BUT – the clincher is that you need to ‘up’ the font size scaling.

By default, it was set to 200% – if setting to 100% – it’s hard to read !

The next dilemma – and discussion with a colleague – was the scenario for a HYPER-V VM.    I have one for some local development and working with K2.

Yes, I could use an Azure VM – but I have a local VM – so there…

While I can run a VM at decent speed, and with 10GB RAM, it’s not something that I can run on ‘multiple monitors’.  

The next consideration, was to drop my screen resolution to 1920×1080 – to match the second external monitor.    This WORKED – to a degree.

The VM would now pick up the base screen resolution (3840×1920) – within the VM – regardless of the desktop resolution I’d just changed to.

It turns out that HyperV must grab the base screen resolution – at BOOT time.

So – the answer was :

  • Change down from scale at 200% to 100% (I use 175% a lot of the time)
  • Drop the laptop screen resolution to 1920×1080
  • Reboot
  • Start up the VM
  • Connect – and tick the box for ‘span multiple monitors’

I can now run my VM across both screens – and both at 1920×1080.

It’s a fiddly way to do it – but luckily it’s so quick to re-boot, it doesn’t matter !

Yes – as Scott Hanselman mentioned, living a High-DPI desktop lifestyle can be painful….

#FirstWorldProblems

But – it’s a problem I’m happy to live with.    Viva la 4K !!

Smile

JavaScript Date Format

One of my main bugbears with JavaScript is the way it handles DATE variables.   Or, more specifically, date FORMAT.

There are some great jQuery plug-ins – like MOMENT.JS – but if you have the need for a quick formatter – I just use a simple function, like this :

function formatDate(dateObject) {
    var d = new Date(dateObject);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    if (day < 10) {
        day = “0” + day;
    }
    if (month < 10) {
        month = “0” + month;
    }
    var date = day + “/” + month + “/” + year;
    return date;
}

This does a format of “dd/mm/yyyy” – which is the only one you need, right ??

To use the above function, you just need to do this :

var nowDateTime = new Date();
var formattedDateTime = formatDate(nowDateTime);

Feel free to edit/use as you need – can change to dd-mm-yyyy, for example.

But never mm/dd/yyyy – that’s just crazy talk !   

😛