<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>powershell &#8211; blog.boro2g .co.uk</title>
	<atom:link href="https://blog.boro2g.co.uk/category/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.boro2g.co.uk</link>
	<description>Some ideas about coding, dev and all things online.</description>
	<lastBuildDate>Thu, 11 Feb 2016 11:55:02 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.5.8</generator>
	<item>
		<title>Octopus deploy &#8211; Script Steps sourced from a package</title>
		<link>https://blog.boro2g.co.uk/octopus-deploy-script-steps-sourced-from-a-package/</link>
					<comments>https://blog.boro2g.co.uk/octopus-deploy-script-steps-sourced-from-a-package/#respond</comments>
		
		<dc:creator><![CDATA[boro]]></dc:creator>
		<pubDate>Thu, 11 Feb 2016 11:49:41 +0000</pubDate>
				<category><![CDATA[Octopus]]></category>
		<category><![CDATA[powershell]]></category>
		<guid isPermaLink="false">http://blog.boro2g.co.uk/?p=736</guid>

					<description><![CDATA[<p>In the latest version of Octopus deploy you can now choose to run script steps where the files exist in a package. This might sound like a minor change but opens up some very neat options. You can read more on the details of the change in https://octopus.com/blog/octopus-deploy-3.3#ScriptsInPackages. Note at the time of writing this is [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/octopus-deploy-script-steps-sourced-from-a-package/">Octopus deploy &#8211; Script Steps sourced from a package</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In the latest version of Octopus deploy you can now choose to run script steps where the files exist in a package. This might sound like a minor change but opens up some very neat options. You can read more on the details of the change in <a href="https://octopus.com/blog/octopus-deploy-3.3#ScriptsInPackages" target="_blank">https://octopus.com/blog/octopus-deploy-3.3#ScriptsInPackages</a>. <em>Note at the time of writing this is only available in the beta of 3.3 (<a href="https://octopus.com/downloads/3.3.0-beta0001" target="_blank">https://octopus.com/downloads/3.3.0-beta0001</a>)</em></p>
<p><strong>Ok, so why is this such a good thing?</strong><br />
Step templates are great &#8211; there is even a large library of pre-existing templates to download (<a href="https://library.octopusdeploy.com/#!/listing" target="_blank">https://library.octopusdeploy.com/#!/listing</a>). If you&#8217;ve not used them before, step templates allow additional scripts to run during your deployment. </p>
<p>Examples could be: post to slack, create certain folders, delete given files etc. Basically anything you can achieve with powershell can be done in step templates.</p>
<p><strong>Lets just stick with step templates then?</strong><br />
If you&#8217;ve gone through the process of setting up several deployments with Octopus and find you want to replicate the same functionality across several projects or installs then you need to re-create all the step template configurations each time. It&#8217;s not the slowest process but the idea below helps streamline things.</p>
<p>Now that you can run scripts from a package, why not source control the steps you want to run? One key advantage is that you can then see things like history of all the deployment steps.</p>
<p><strong>What needs setting up?</strong><br />
You need to be running version 3.3 or higher of Octopus &#8211; see above for the link.</p>
<p>I&#8217;ve been using a simple test deployment of an out the box MVC project along with a new project specifically for the scripts.:<br />
<a href="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/solution-setup.png" rel="attachment wp-att-738"><img decoding="async" class="alignnone size-full wp-image-738" src="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/solution-setup.png" alt="solution setup" width="262" height="170" /></a></p>
<p>In Octopus this has 2 steps:<br />
<a href="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/steps.png" rel="attachment wp-att-739"><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-739" src="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/steps.png" alt="steps" width="672" height="285" srcset="https://blog.boro2g.co.uk/wp-content/uploads/2016/02/steps.png 672w, https://blog.boro2g.co.uk/wp-content/uploads/2016/02/steps-300x127.png 300w" sizes="(max-width: 672px) 100vw, 672px" /></a></p>
<p>The first is a vanilla website deployment of &#8216;WebApplication1&#8217;. The second the startup scripts:<br />
<a href="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/script-step.png" rel="attachment wp-att-737"><img decoding="async" class="alignnone size-full wp-image-737" src="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/script-step.png" alt="script step" width="780" height="789" srcset="https://blog.boro2g.co.uk/wp-content/uploads/2016/02/script-step.png 780w, https://blog.boro2g.co.uk/wp-content/uploads/2016/02/script-step-297x300.png 297w, https://blog.boro2g.co.uk/wp-content/uploads/2016/02/script-step-768x777.png 768w" sizes="(max-width: 780px) 100vw, 780px" /></a></p>
<p><strong>Note the package id.</strong> The idea behind using a separate projects is that the powershell scripts never need to exist in the website project.</p>
<p><strong>The startup script project</strong><br />
<a href="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/solution-setup.png" rel="attachment wp-att-738"><img decoding="async" class="alignnone size-full wp-image-738" src="http://blog.boro2g.co.uk/wp-content/uploads/2016/02/solution-setup.png" alt="solution setup" width="262" height="170" /></a></p>
<p>I chose to use a class library for the simple reason that I could include a reference to Octopack and hence building the output nuget file was trivial.</p>
<p>The nuspec file is important as it tells the packaging to include all powershell files:</p><pre class="crayon-plain-tag">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;package xmlns=&quot;http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd&quot;&gt;
  &lt;metadata&gt;
    &lt;id&gt;WebApplication1.Startup&lt;/id&gt;
    &lt;title&gt;TODO Your Web Application&lt;/title&gt;
    &lt;version&gt;1.0.0&lt;/version&gt;
    &lt;authors&gt;TODO Your name&lt;/authors&gt;
    &lt;owners&gt;TODO Your name&lt;/owners&gt;
    &lt;licenseUrl&gt;http://TODO.com&lt;/licenseUrl&gt;
    &lt;projectUrl&gt;http://TODO.com&lt;/projectUrl&gt;
    &lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt;
    &lt;description&gt;TODO A sample project&lt;/description&gt;
    &lt;releaseNotes&gt;TODO This release contains the following changes...&lt;/releaseNotes&gt;	
  &lt;/metadata&gt;
  &lt;files&gt;
	  &lt;file src=&quot;**\*.ps1&quot; target=&quot;\&quot; /&gt;
  &lt;/files&gt;
&lt;/package&gt;</pre><p></p>
<p>Packages simply contains a reference to Octopack:</p><pre class="crayon-plain-tag">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;packages&gt;
  &lt;package id=&quot;OctoPack&quot; version=&quot;3.0.53&quot; targetFramework=&quot;net46&quot; developmentDependency=&quot;true&quot; /&gt;
&lt;/packages&gt;</pre><p></p>
<p>And finally the scripts:<br />
<strong>Helloworld.ps1</strong></p><pre class="crayon-plain-tag">Write-Host &quot;Hello World PS script example&quot;

if ($OctopusParameters) {
	##enable the next line to show all Octopus variables
	#$OctopusParameters.GetEnumerator() | Sort-Object Name | % { &quot;$($_.Key)=$($_.Value)&quot; }
}

#use this approach to pull in additional script files
. .\Startup.ps1</pre><p></p>
<p>And the more important one, <strong>Startup.ps1</strong></p><pre class="crayon-plain-tag">function createFolderIfNotExists{
	param([string]$folder)
	if (!(Test-Path $folder)) {
		Write-Host &quot;Creating $folder&quot;
		New-Item -Path $folder -ItemType Directory
	} else {
		Write-Host &quot;Directory already exists!&quot;
	}
}

function assignReadPermissionsTo {
    param([string] $item, [string] $readPermissionsTo)
    if(!(Test-Path $item)) {
        throw &quot;$item does not exist&quot;
    }
    $users = $readPermissionsTo.Split(&quot;,&quot;)
    foreach($user in $users) {
        Write-Host &quot;Adding read permissions for $user&quot;
        $acl = Get-Acl $item
        $acl.SetAccessRuleProtection($False, $False)
        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, &quot;Read&quot;, &quot;ContainerInherit, ObjectInherit&quot;, &quot;None&quot;, &quot;Allow&quot;)
        $acl.AddAccessRule($rule)
        Set-Acl $item $acl
    }
}

function assignWritePermissionsTo {
    param([string] $item, [string] $writePermissionsTo)
    if(!(Test-Path $item)) {
        throw &quot;$item does not exist&quot;
    }
    $users = $writePermissionsTo.Split(&quot;,&quot;)
    foreach($user in $users) {
        Write-Host &quot;Adding write permissions for $user&quot;
        $acl = Get-Acl $item
        $acl.SetAccessRuleProtection($False, $False)
        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($user, &quot;Write&quot;, &quot;ContainerInherit, ObjectInherit&quot;, &quot;None&quot;, &quot;Allow&quot;)
        $acl.AddAccessRule($rule)
        Set-Acl $item $acl
    }
}

$foldersToCreate = @(&quot;_logs&quot;,&quot;test\deep&quot;)
$usersToGiveAccess = &quot;IIS_IUSRS&quot;

if ($OctopusParameters) {
	$installFolder = $OctopusParameters['Octopus.Action[Deploy website].Output.Package.InstallationDirectoryPath']

	Write-Host &quot;Environment: &quot; $OctopusParameters['Octopus.Environment.Name']
	Write-Host &quot;Deployment folder: &quot; $installFolder
	
    Foreach ($folder in $foldersToCreate) {
        $newFolder = [io.path]::combine($installFolder,$folder)
        createFolderIfNotExists -folder $newFolder
        assignWritePermissionsTo -item $newFolder -writePermissionsTo $usersToGiveAccess
    }	
}
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
Write-Host &quot;Current running folder is: &quot; $PSScriptRoot</pre><p></p>
<p>It&#8217;s worth noting this should be considered a POC of the approach. The next steps would be to split the scripts up into more meaningful units, remove hello world and update the nuspec with more valid information.</p>
<p>If you struggle with accessing the Octopus Parameters you require, the script in helloworld allows you to dump out all parameters and their values. In the startup script the parameter: <em>$OctopusParameters[&#8216;Octopus.Action[Deploy website].Output.Package.InstallationDirectoryPath&#8217;]</em> depends on the name of your deployment in step 1 of your deployment process <em>(Deploy website)</em></p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/octopus-deploy-script-steps-sourced-from-a-package/">Octopus deploy &#8211; Script Steps sourced from a package</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.boro2g.co.uk/octopus-deploy-script-steps-sourced-from-a-package/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to write a basic powershell module that includes multiple scripts</title>
		<link>https://blog.boro2g.co.uk/write-basic-powershell-module-includes-multiple-scripts/</link>
					<comments>https://blog.boro2g.co.uk/write-basic-powershell-module-includes-multiple-scripts/#respond</comments>
		
		<dc:creator><![CDATA[boro]]></dc:creator>
		<pubDate>Fri, 27 Mar 2015 09:39:56 +0000</pubDate>
				<category><![CDATA[powershell]]></category>
		<guid isPermaLink="false">http://blog.boro2g.co.uk/?p=567</guid>

					<description><![CDATA[<p>As part of a recent project I&#8217;ve needed to work closely with some of the Azure api&#8217;s. You can achieve some really cool things pretty quickly once you&#8217;ve learnt a few basics. A good tip I picked up was that if you can implement something in .net/c# chance are you can replicate in PowerShell. If [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/write-basic-powershell-module-includes-multiple-scripts/">How to write a basic powershell module that includes multiple scripts</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As part of a recent project I&#8217;ve needed to work closely with some of the Azure api&#8217;s. You can achieve some really cool things pretty quickly once you&#8217;ve learnt a few basics.</p>
<p>A good tip I picked up was that if you can implement something in .net/c# chance are you can replicate in PowerShell. If there isn&#8217;t a specific PowerShell module/api available you can call into the .net dll. This can be loaded via e.g.:</p>
<p></p><pre class="crayon-plain-tag">function CurrentDirectory
{
    return (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent);
}
[System.Reflection.Assembly]::LoadFrom((CurrentDirectory) + '\Microsoft.WindowsAzure.Storage.dll')
$credentials = New-Object Microsoft.WindowsAzure.Storage.Auth.StorageCredentials($accountName, $accountKey)</pre><p></p>
<p>In order to structure your various functions the recommended approach is to use modules. A quick google will bring up more details. What I couldn&#8217;t find was how to setup a basic module that includes multiple scripts.</p>
<p>When you create new modules they can live in a couple places, <strong>$env:PSModulePath</strong> will show you this.</p>
<p>A module structure is pretty basic, you need a psm1 file (and psd1 &#8211; see <a href="https://www.simple-talk.com/sysadmin/powershell/an-introduction-to-powershell-modules/" target="_blank">https://www.simple-talk.com/sysadmin/powershell/an-introduction-to-powershell-modules/</a>)<br />
<a href="http://blog.boro2g.co.uk/wp-content/uploads/2015/03/ps-structure.png"><img loading="lazy" decoding="async" src="http://blog.boro2g.co.uk/wp-content/uploads/2015/03/ps-structure.png" alt="ps structure" width="143" height="75" class="alignnone size-full wp-image-568" /></a><br />
Script.ps1 is basic, it contains a simple function:</p><pre class="crayon-plain-tag">function HiThere
{
    return &quot;hi there&quot;;
}</pre><p></p>
<p>Custom.psm1 then looks to load all the scripts you have. Note, make sure the folder name matches the psm1 name:</p><pre class="crayon-plain-tag">$functions = Get-ChildItem -Recurse &quot;$PSScriptRoot\Subfolder&quot; -Include *.ps1 

# dot source the individual scripts that make-up this module
foreach ($function in $functions) { . $function.FullName }

Write-Host -ForegroundColor Green &quot;Module $(Split-Path $PSScriptRoot -Leaf) was successfully loaded.&quot;</pre><p></p>
<p>These files need to live in one of your module folders e.g. <strong>%UserProfile%\Documents\WindowsPowerShell\Modules</strong></p>
<p>It&#8217;s then a case of installing your module:<br />
Check what modules are available to install via: <strong>Get-Module -ListAvailable</strong><br />
And install the one you want via: <strong>Import-Module Custom</strong>. Note, Custom is the name of the folders and psm1 file.</p>
<p>Provided it&#8217;s all gone to plan you should now be able to call <strong>HiThere</strong> from a ps prompt</p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/write-basic-powershell-module-includes-multiple-scripts/">How to write a basic powershell module that includes multiple scripts</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.boro2g.co.uk/write-basic-powershell-module-includes-multiple-scripts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Debugging Azure web-role startup tasks</title>
		<link>https://blog.boro2g.co.uk/debugging-azure-web-role-startup-tasks/</link>
					<comments>https://blog.boro2g.co.uk/debugging-azure-web-role-startup-tasks/#respond</comments>
		
		<dc:creator><![CDATA[boro]]></dc:creator>
		<pubDate>Mon, 23 Mar 2015 19:12:30 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[powershell]]></category>
		<guid isPermaLink="false">http://blog.boro2g.co.uk/?p=562</guid>

					<description><![CDATA[<p>One feature Azure offers for getting your  boxes configured is the notion of startup tasks &#8211; I won&#8217;t go into too much detail here as there is lots available online e.g. https://msdn.microsoft.com/en-us/library/azure/hh180155.aspx As part of setting these up I thought I&#8217;d share a few tips / gotchas that caught me out when running powershell from the [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/debugging-azure-web-role-startup-tasks/">Debugging Azure web-role startup tasks</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>One feature Azure offers for getting your  boxes configured is the notion of startup tasks &#8211; I won&#8217;t go into too much detail here as there is lots available online e.g. <a href="https://msdn.microsoft.com/en-us/library/azure/hh180155.aspx">https://msdn.microsoft.com/en-us/library/azure/hh180155.aspx</a></p>
<p>As part of setting these up I thought I&#8217;d share a few tips / gotchas that caught me out when running powershell from the cmd tasks.</p>
<p>My solution setup was:</p>
<ul>
<li>Site root
<ul>
<li>StartupScripts
<ul>
<li>Script.cmd</li>
<li>Script.ps1</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>So then I&#8217;d reference in the task:</p>
<p><em> &lt;Task commandLine=&#8221;StartupScripts\script.cmd&#8221; executionContext=&#8221;elevated&#8221; taskType=&#8221;simple&#8221; /&gt;</em></p>
<p>Nothing rocket science so far! So, why didn&#8217;t the script work? I could jump on the box and run the cmd and it would be fine.</p>
<p><strong>How to debug the process?</strong><br />
I found the most useful way was to add markers from the cmd and the ps1. The cmd file looked like:</p>
<p></p><pre class="crayon-plain-tag">md c:\test
echo &quot;Running&quot; &gt; &quot;c:\test\log.txt&quot;
powershell -command &quot;Set-ExecutionPolicy Unrestricted&quot; 2&gt;&gt; &quot;c:\test\log.txt&quot;
powershell .\startupScripts\script.ps1 %~dp0 2&gt;&gt; &quot;c:\test\log.txt&quot;
EXIT /B 0</pre><p>Note, the <strong>.\startupScripts</strong> part of the ps1 path is v important!</p>
<p>Then the powershell:</p><pre class="crayon-plain-tag">$tempFolder = &quot;c:\test&quot;
$logFile = &quot;ps_log.txt&quot;
$siterootFolder = &quot;\sitesroot\0\&quot;
If (!(Test-Path &quot;e:\&quot;))
{
    $siterootFolder = &quot;f:&quot; + $siterootFolder
}
else
{
    $siterootFolder = &quot;e:&quot; + $siterootFolder
}

function Write-Log
{
    param( [string] $text )
    Write-Host $text;	
    $path = [System.IO.Path]::Combine(&quot;$tempFolder\$logFile&quot;)

    $fs = New-Object IO.FileStream($path, [System.IO.FileMode]::Append, [System.IO.FileAccess]::Write, [IO.FileShare]::Read)
    $sw = New-Object System.IO.StreamWriter($fs)

    $sw.WriteLine($text)
    $sw.Dispose()
    $fs.Dispose()
}

Write-Log &quot;Output folder is $siterootFolder&quot;</pre><p>Note, if you try to write to log.txt you will get process locked exceptions as the cmd holds locks on the file.<br />
There are all sorts of techniques for writing to a file, this example uses a StreamWriter. Hit up google for different examples.</p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/debugging-azure-web-role-startup-tasks/">Debugging Azure web-role startup tasks</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.boro2g.co.uk/debugging-azure-web-role-startup-tasks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Running sql queries from Powershell</title>
		<link>https://blog.boro2g.co.uk/running-sql-queries-powershell/</link>
					<comments>https://blog.boro2g.co.uk/running-sql-queries-powershell/#respond</comments>
		
		<dc:creator><![CDATA[boro]]></dc:creator>
		<pubDate>Wed, 21 Jan 2015 17:55:57 +0000</pubDate>
				<category><![CDATA[powershell]]></category>
		<category><![CDATA[Sitecore]]></category>
		<guid isPermaLink="false">http://blog.boro2g.co.uk/?p=547</guid>

					<description><![CDATA[<p>Have you ever needed to test out the performance of sets of sql queries? Recently we had some performance issues on a live infrastructure which needed diagnosing. Getting code released was slightly tricky so instead we concocted some scripts to allow us to run sql queries from Powershell. The advantage of these, we could run [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/running-sql-queries-powershell/">Running sql queries from Powershell</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Have you ever needed to test out the performance of sets of sql queries?</p>
<p>Recently we had some performance issues on a live infrastructure which needed diagnosing. Getting code released was slightly tricky so instead we concocted some scripts to allow us to run sql queries from Powershell. The advantage of these, we could run from different boxes in the farm to try and isolate where the issues arrived.</p>
<p>The key settings in this setup are:</p><pre class="crayon-plain-tag"># Specify SQL Connection String. 
$master = &quot;Data Source=###;Initial Catalog=Master;Integrated Security=SSPI;&quot; 
$core = &quot;Data Source=###;Initial Catalog=Core;Integrated Security=SSPI;&quot; 
# Specify SQL Connection String. 

$runs = 10</pre><p>The connection strings are much like your standard application connection strings.</p>
<p>To then run in bulk you can use the script shown below. <em>Note, adjust the specific queries you want to execute</em>:</p><pre class="crayon-plain-tag">function ExecNonQuery 
{ 
    param ($conStr, $cmdText) 
   
    # Determine if parameters were correctly populated. 
    if (!$conStr -or !$cmdText) 
    { 
        # One or more parameters didn't contain values. 
        write-Host &quot;ExecNonQuery function called with no connection string and/or command text.&quot; 
    } 
    else 
    { 
        write-Host &quot;Creating SQL Connection...&quot; 
        # Instantiate new SqlConnection object. 
        $Connection = New-Object System.Data.SQLClient.SQLConnection 
         
        # Set the SqlConnection object's connection string to the passed value. 
        $Connection.ConnectionString = $conStr 
         
        # Perform database operations in try-catch-finally block since database operations often fail. 
        try 
        { 
            #write-Host &quot;Opening SQL Connection...&quot; 
            # Open the connection to the database. 
            $Connection.Open() 
             
            #write-Host &quot;Creating SQL Command...&quot; 
            # Instantiate a SqlCommand object. 
            $Command = New-Object System.Data.SQLClient.SQLCommand 
            # Set the SqlCommand's connection to the SqlConnection object above. 
            $Command.Connection = $Connection 
            # Set the SqlCommand's command text to the query value passed in. 
            $Command.CommandText = $cmdText 
             
            #write-Host &quot;Executing SQL Command...&quot;   
            # Note, to see a result back here, ExecuteNonQuery has been changed to ExecuteScalar
            write-host $Command.ExecuteScalar() 
        } 
        catch [System.Data.SqlClient.SqlException] 
        { 
            # A SqlException occurred. According to documentation, this happens when a command is executed against a locked row. 
            #write-Host &quot;One or more of the rows being affected were locked. Please check your query and data then try again.&quot; 
        } 
        catch 
        { 
            # An generic error occurred somewhere in the try area. 
            write-Host &quot;An error occurred while attempting to open the database connection and execute a command.&quot; 
        } 
        finally { 
            # Determine if the connection was opened. 
            if ($Connection.State -eq &quot;Open&quot;) 
            { 
                write-Host &quot;Closing Connection...&quot; 
                # Close the currently open connection. 
                $Connection.Close() 
            } 
        } 
    } 
} 

 
# Specify SQL Connection String. 
$master = &quot;Data Source=###;Initial Catalog=Master;Integrated Security=SSPI;&quot; 
$core = &quot;Data Source=###;Initial Catalog=Core;Integrated Security=SSPI;&quot; 
# Specify SQL Connection String. 

$runs = 10
$stopWatch = [System.Diagnostics.Stopwatch]::StartNew()

for ($i=0; $i -le $runs; $i++)
{
ExecNonQuery -conStr $core -cmdText &quot;SELECT COUNT (*) FROM aspnet_Users&quot; 

ExecNonQuery -conStr $core -cmdText &quot;SELECT COUNT (*) FROM aspnet_UsersInRoles&quot; 

ExecNonQuery -conStr $core -cmdText &quot;exec sp_executesql N'SELECT [ItemId], [Order], [Version], [Language], [Name], [Value], [FieldId], [MasterID], [ParentID]
                     FROM (
                        SELECT [Id] as [ItemId], 0 as [Order], 0 as [Version], '''' as [Language], [Name], '''' as [Value], [TemplateID] as [FieldId], [MasterID], [ParentID]
                        FROM [Items]

                        UNION ALL                          
                        SELECT [ParentId] as [ItemId], 1 as [Order], 0 as [Version], '''' as [Language], NULL as [Name], '''', NULL, NULL, [Id]
                        FROM [Items] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order], 0 AS [Version], '''' as [Language], NULL as [Name], [Value], [FieldId], NULL, NULL
                        FROM [SharedFields] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order], 0 AS [Version],       [Language], NULL as [Name], [Value], [FieldId], NULL, NULL
                        FROM [UnversionedFields] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order],      [Version],       [Language], NULL as [Name], [Value], [FieldId], NULL, NULL 
                        FROM [VersionedFields]
                     ) as temp  WHERE [ItemId] IN (SELECT [ID] FROM [Items] WITH (nolock)  WHERE [TemplateID]=@p0 OR [TemplateID]=@p1 OR [TemplateID]=@p2 OR [TemplateID]=@p3 OR [TemplateID]=@p4 OR [TemplateID]=@p5 OR [TemplateID]=@p6 OR [ID]=@p7 OR [ParentID]=@p8 OR [TemplateID]=@p9 OR [TemplateID]=@p10 OR [ParentID]=@p11) 
                     ORDER BY [ItemId], [Order] ASC, [Language] DESC, [Version] DESC',N'@p0 uniqueidentifier,@p1 uniqueidentifier,@p2 uniqueidentifier,@p3 uniqueidentifier,@p4 uniqueidentifier,@p5 uniqueidentifier,@p6 uniqueidentifier,@p7 uniqueidentifier,@p8 uniqueidentifier,@p9 uniqueidentifier,@p10 uniqueidentifier,@p11 uniqueidentifier',@p0='AB86861A-6030-46C5-B394-E8F99E8B87DB',@p1='E269FBB5-3750-427A-9149-7AA950B49301',@p2='455A3E98-A627-4B40-8035-E683A0331AC7',@p3='239F9CF4-E5A0-44E0-B342-0F32CD4C6D8B',@p4='A87A00B1-E6DB-45AB-8B54-636FEC3B5523',@p5='F68F13A6-3395-426A-B9A1-FA2DC60D94EB',@p6='B6F7EEB4-E8D7-476F-8936-5ACE6A76F20B',@p7='11111111-1111-1111-1111-111111111111',@p8='11111111-1111-1111-1111-111111111111',@p9='EB06CEC0-5E2D-4DC4-875B-01ADCC577D13',@p10='B2A1FF6C-6B1F-41EF-B2E1-AA598CF7335F',@p11='C74AC643-53C8-4F1E-9508-840CDC72AACA'&quot; 
 
ExecNonQuery -conStr $master -cmdText &quot;exec sp_executesql N'SELECT [ItemId], [Order], [Version], [Language], [Name], [Value], [FieldId], [MasterID], [ParentID]
                     FROM (
                        SELECT [Id] as [ItemId], 0 as [Order], 0 as [Version], '''' as [Language], [Name], '''' as [Value], [TemplateID] as [FieldId], [MasterID], [ParentID]
                        FROM [Items]

                        UNION ALL                          
                        SELECT [ParentId] as [ItemId], 1 as [Order], 0 as [Version], '''' as [Language], NULL as [Name], '''', NULL, NULL, [Id]
                        FROM [Items] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order], 0 AS [Version], '''' as [Language], NULL as [Name], [Value], [FieldId], NULL, NULL
                        FROM [SharedFields] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order], 0 AS [Version],       [Language], NULL as [Name], [Value], [FieldId], NULL, NULL
                        FROM [UnversionedFields] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order],      [Version],       [Language], NULL as [Name], [Value], [FieldId], NULL, NULL 
                        FROM [VersionedFields]
                     ) as temp  WHERE [ItemId] IN (SELECT [ID] FROM [Items] WITH (nolock)  WHERE [ParentID] = @itemId) 
                     ORDER BY [ItemId], [Order] ASC, [Language] DESC, [Version] DESC',N'@itemId uniqueidentifier',@itemId='734FB52F-33E3-4BCF-ADA9-27F1A4D8B4E1'&quot; 

ExecNonQuery -conStr $master -cmdText &quot;exec sp_executesql N'SELECT [ItemId], [Order], [Version], [Language], [Name], [Value], [FieldId], [MasterID], [ParentID]
                     FROM (
                        SELECT [Id] as [ItemId], 0 as [Order], 0 as [Version], '''' as [Language], [Name], '''' as [Value], [TemplateID] as [FieldId], [MasterID], [ParentID]
                        FROM [Items]

                        UNION ALL                          
                        SELECT [ParentId] as [ItemId], 1 as [Order], 0 as [Version], '''' as [Language], NULL as [Name], '''', NULL, NULL, [Id]
                        FROM [Items] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order], 0 AS [Version], '''' as [Language], NULL as [Name], [Value], [FieldId], NULL, NULL
                        FROM [SharedFields] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order], 0 AS [Version],       [Language], NULL as [Name], [Value], [FieldId], NULL, NULL
                        FROM [UnversionedFields] 

                        UNION ALL 
                        SELECT [ItemId], 2 as [Order],      [Version],       [Language], NULL as [Name], [Value], [FieldId], NULL, NULL 
                        FROM [VersionedFields]
                     ) as temp  WHERE [ItemId] IN (SELECT [ID] FROM [Items] WITH (nolock)  WHERE [ParentID] = @itemId) 
                     ORDER BY [ItemId], [Order] ASC, [Language] DESC, [Version] DESC',N'@itemId uniqueidentifier',@itemId='11A81FBC-77FB-40D9-A3B3-0078106B07FC'&quot; 
 
write-Host &quot;Query Complete!&quot;
}

$stopWatch.Stop()

Write-Host &quot;total &quot; $stopWatch.ElapsedMilliseconds &quot;ms&quot;
Write-Host &quot;average &quot; ($stopWatch.ElapsedMilliseconds/$runs) &quot;ms&quot;</pre><p></p>
<p>The post <a rel="nofollow" href="https://blog.boro2g.co.uk/running-sql-queries-powershell/">Running sql queries from Powershell</a> appeared first on <a rel="nofollow" href="https://blog.boro2g.co.uk">blog.boro2g .co.uk</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.boro2g.co.uk/running-sql-queries-powershell/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
