Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Monday, 9 April 2018

Azure–iterate resources in all tenants for GDPR

GDPR means that we now have a policy for all data to be in UK or Europe.

So – to find where all our azure resources are

1. Install the azure PowerShell toolkik (https://docs.microsoft.com/en-gb/azure/azure-resource-manager/powershell-azure-resource-manager)

2. Run the script below to check the location of your resources are in the list of allowed locations.

# login to azure this should request secure credentials
Login-AzureRmAccount
# get a list of tenants / subscriptions
$allowedlocations = 'northeurope', 'westeurope' , 'francecentral' , 'francesouth', 'ukwest' , 'uksouth', 'germanycentral' , 'germanynortheast'
$subscriptions = Get-AzureRmSubscription
foreach($sub in $subscriptions) {
     Select-AzureRmSubscription -Subscription $sub.Id
     $resources = Get-AzureRmResource
     $resources.where({ $_.Location  -notin $allowedlocations }) 
}

Tuesday, 4 July 2017

Import and bind a cert is IIS.

param (
[Parameter(Mandatory=$true)][String]$certpath,
[Parameter(Mandatory=$true)][String]$certpass,
[Parameter(Mandatory=$true)][String]$ip,
[Parameter(Mandatory=$false)][String]$website = "Default Web Site"
)

$mypwd = ConvertTo-SecureString -String $certpass -Force –AsPlainText
$cert  = Import-PfxCertificate -FilePath $certpath Cert:\LocalMachine\My -Password $mypwd -Exportable
$bind = Get-WebBinding -Protocol https -IPAddress $ip  -port 443
if($bind -ne $null) {
    Remove-WebBinding  -Protocol https -IPAddress $ip  -port 443
}

# -Name $website -IPAddress $ip -Protocol HTTPS -Port 443 -HostHeader '' -Binding $ip':433:'
new-WebBinding -Name $website -IPAddress $ip -Protocol https -Port 443 
$bind = Get-WebBinding -Protocol https -IPAddress $ip  -port 443
$bind.AddSslCertificate($cert.GetCertHashString(), "my")
This is for a cert to IP without host header.

Thursday, 29 June 2017

Stop, start disable services on multiple machines

$Machines = Get-Content -Path ".\Machines.txt"
$service="Microsoft Deployment Agent"
$credential = Get-Credential
foreach($computer in $Machines) {
    #$result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).stopservice() 
    #$result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).ChangeStartMode("Disabled") 
    $result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).startservice()     
    $result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $credential).ChangeStartMode("Automatic") 
}
# $result = (gwmi win32_service -computername $computer -filter "name='$service'" -Credential $cred).startservice() 
#Get-Service -Name $Services -ComputerName $Machines -Credential $credential | Set-Service -Status Started -StartupType Automatic 


As usual not really my code but plagiarised. Massive apologies to whoever/wherever I got it as I can’t find it again.  As usual – this is really for me!

The Get-Service /  Set-Service script was the obvious candidate to use but wont take a credential.

Put a list of machines in Machines.txt.

Original that I’ve lost also took a list of services!

Thursday, 8 June 2017

Grep for PowerShell

Get-Childitem -Path ".\" web.config -Recurse | Select-String -pattern 'dardaudit' –SimpleMatch

Works for me!

Tuesday, 14 February 2017

Powershell endpoints

For old school .svc and .asmx

foreach($dir in ("dir1",”dir2”)) {
    $files = Get-ChildItem -Path  D:\AppWebSites\$dir -Recurse -Include ('*.asmx','*.svc')
    $files
}

Monday, 30 January 2017

ODBC Settings multuple servers

You need to have some wdac sdk on the server and each machine that you connect to.
$credential = Get-Credential
foreach ($server in @("ESS027521","ESS026412","ESS026488","ESS026191")) {
    $session = New-CimSession -ComputerName $server -Credential $credential
    $odbc = Get-OdbcDsn  -CimSession $session
    $server + ":"
    $odbc        
}

Tuesday, 13 December 2016

Moveing classic resources (within subscription)

Well – according to the documentation then you can use the portal to move classic resource items around your groups.

“

  • Virtual machines (classic) must be moved with the cloud service.
  • Cloud service can only be moved when the move includes all its virtual machines.”

…

“To move classic resources to a new resource group within the same subscription, use the standard move operations through the portal, Azure PowerShell, Azure CLI, or REST API. You use the same operations as you use for moving Resource Manager resources.”

It even has a nice little picture showing it being done

I had a group with two resources – a VM and its cloud service – but the portal would not allow them to be moved.

So this nice little script does it

# prompt for credentials etc.
Login-AzureRmAccount
# select the correct subscription
Get-AzureRmSubscription -SubscriptionName "Stiona Software General" | Select-AzureRmSubscription
# get the ResourceID property of the two resources - luckily they have the same name in my case
$resources = Get-AzureRmResource -ResourceName fusionreports -ResourceGroupName fusionreports | Select -ExpandProperty ResourceId
# issue a move to the new group
Move-AzureRmResource -DestinationResourceGroupName fusionazure -ResourceId $resources

The $resources this -

/subscriptions/b9fee249-e903-4c4a-ade7-42982be9a20f/resourceGroups/fusionreports/providers/Microsoft.ClassicCompute/domainNa
mes/fusionreports
/subscriptions/b9fee249-e903-4c4a-ade7-42982be9a20f/resourceGroups/fusionreports/providers/Microsoft.ClassicCompute/virtualM
achines/fusionreports

After promt to move the old resource group was empty and the new one contained the vm and cloud service.

Nice hint from stack overflow on the use of  ExpandProperty parameter of Select-Object for getting an array of values from an array of objects.

Man – working with Azure classic sure is tough.

Monday, 5 December 2016

Finding dependencies

Looking to find service references and database connections in web.config files on a server or a set of servers.

I started with this guys script - http://www.markrainey.me/2013/03/finding-urls-in-text-files.html but he was just interested in unique url’s so I hacked it around a bit and also added in another regex for the connection strings.

This is not perfect by any means but is a start for anyone else (or me in the future)

########################################################### 
# AUTHOR  : Mark Rainey  
# Ammended - Stuart McLean 2016-05-12
# DATE    : 2013-03-13  
# COMMENT : Reads in a list of servers and searches
# the E:\Live folder for config files.  When it finds
# them it searches for anything starting with 3 or more
# letters (tcp or http) followed by a colon and \\
# now also outputs connection string data and 
# looks for </value in urls
###########################################################

#ERROR REPORTING ALL
Set-StrictMode -Version latest

$scriptpath = Split-Path -parent $MyInvocation.MyCommand.Definition
# A friend at work helped me get this to output to Excel
$outputFile = $scriptpath + "\urls.csv"
$connectionFile = $scriptpath + "\connections.csv"
# This is a file with a FQDN of each server on a new line
$serverList = $scriptpath + "\serverlist.txt"
# Load server list
$servers = Get-Content $serverList


$URLS = New-Object System.Collections.ArrayList
$ConnectionStrings = New-Object System.Collections.ArrayList

$credential = Get-Credential

# Find the string and save it to a file
Function getStringMatch
{
 Try { 
  # Loop through all servers
  Foreach ($server In $servers) {
      # Set UNC Path to files for this server
   $drive = "\\" + $server + "\d$"
   New-PSDrive -Root $drive  -PSProvider FileSystem -Name z -Credential $credential
   #The path can be anywhere on your servers you want to search
   $path     = "z:\AppWebSites"
   #Get list of files
   $files    =  Get-Childitem $path web.config -Recurse | Where-Object { !($_.psiscontainer) } 
   # Loop through the server and search all config files under E:\Live
    #$matches = New-Object System.Collections.ArrayList
   #$matches.clear()
   Foreach ($file In $files)
      {
    $fullFileName = $file.FullName 
    # regular expression for a URL format
    #$regex = '([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?'
    # find any urls
    $regex = '([a-zA-Z]{3,})(:\/\/.*)(?=<)'
                # Find all matches in current file and add the Value for each one to an array
    select-string -Path $fullFileName -Pattern $regex -AllMatches | % { $_.Matches } | % {
        $found = New-Object psobject -Property  @{       
        server = $server;
        urlRef = $_.Value;
        file = $file.FullName
        }
        
     $URLS.add($found)
    }

    $connectionStringRegex = '(?<=connectionString=")(.*)(?=")'
    select-string -Path $fullFileName -Pattern $connectionStringRegex -AllMatches | % { $_.Matches } | % {
    try{
        $connectionString = $_.Value;

        $source =   ($connectionString | select-string -Pattern '(?<=data source=)(.*?)(?=;)').Matches[0].Value 
        $catalog =  ($connectionString | select-string -Pattern '(?<=Initial Catalog=)(.*?)(?=;)').Matches[0].Value 
        $sqlUser =  ($connectionString | select-string -Pattern '(?<=User ID=|uid=)(.*?)(?=;)').Matches[0].Value 
        $found = New-Object psobject -Property  @{       
        server = $server;
        source = $source;
        catalog = $catalog;
        sqluser = $sqlUser;
        file = $file.FullName
        }
        
     $connectionStrings.add($found)
     }
     Catch {
  Write-host "could not parse connection string $_" + $connectionString
 }
      } 
   }
            
   Remove-PSDrive z
  
  }
  
 }
 Catch {
  Write-host "Something failed $_"
 }
 Finally {
  "Finished"
 }
 
}
  getStringMatch
  $URLS.ToArray() | Export-Csv -Path $outputFile -NoTypeInformation
  $connectionStrings.ToArray() | Export-Csv -Path $connectionFile -NoTypeInformation

Wednesday, 30 November 2016

Powershell file compare.

Simple script for comparing files in two directories.

param (
       [Parameter(Mandatory=$true)][string]$originalDir,
        [Parameter(Mandatory=$true)][string]$newDir
)

$fso = Get-ChildItem -Recurse -path $originalDir
foreach($file in $fso.Name) {
echo comparing $originalDir\$file to $newDir\$file
Compare-Object -ReferenceObject $(Get-Content $originalDir\$file)  -DifferenceObject $(Get-Content $newDir\$file) -IncludeEqual
}

Will compare line by line the files in the originalDir with those in newDir with the same name. 

  • Probably breaks if the file isn’t in newDir
  • Doesn’t check for extra files in newDir.

Friday, 18 November 2016

Sprints 2 and 3 retrospective–an hour really isn’t long.

So – sprint 2 took about an hour and a half of coding – so a lot closer than the first.

I then noticed that I still had some inline nasty SQL in my powershell – so I cracked out another hour and got another proc and changes in.

Main lesson so far – an hour is a really short time – keep pebbleising the tasks.

Outcome

Ok – so the work got done and hopefully I’ll have a list of riders on production soon.

 

I’ve thought hard about it and its definitely a useful task towards the end goal as the first “Minimum” viable product is for riders to sign up.  I’m going to allow google authentication/Oath which will strongly (enough for this) validate the users email which I can then use to look up there details in the data I have.

 

 

A good start.

 

Some feedback on the tasks here – really putting this code here for anyone to look @ until I work out if/what to open source.  Unless you particularly want to critique my sql or look at how I use powerhell to call stored procs then not much excitement.

 

“Work out how to deploy database project to local database and how to connect to it. “

this was pretty easy – just set the PowerShell script to depend on the database project and then it deploys all your changes as it builds – pretty nifty stuff

 

“Create stored procs for crud operations required by script – include find rider.”

CREATE PROCEDURE [dbo].[ups_RiderInsert]
    @vcrFirstName    NVARCHAR (100) ,
    @vcrSurname      NVARCHAR (100) ,
    @vcrAddressLine1 NVARCHAR (100) ,
    @vcrAddressLine2 NVARCHAR (100) ,
    @vcrTown         VARCHAR (100)  ,
    @vcrCountryCode  VARCHAR (2)    ,
    @vcrCountry      VARCHAR (100)  ,
    @vcrPhoneNumber  VARCHAR (20)   ,
    @vcrClub         VARCHAR (50)   ,
    @vcrClubNumber   VARCHAR (20)   ,
    @vcrECName       VARCHAR (100)  ,
    @vcrECTelephone  VARCHAR (100) 
AS
SET XACT_ABORT ON

BEGIN TRANSACTION
	INSERT INTO tblRider
	VALUES( 
	@vcrFirstName,
	 @vcrSurname      ,
    @vcrAddressLine1 ,
    @vcrAddressLine2 ,
    @vcrTown           ,
    @vcrCountryCode  ,
    @vcrCountry        ,
    @vcrPhoneNumber  ,
    @vcrClub            ,
    @vcrClubNumber      ,
    @vcrECName       ,
    @vcrECTelephone)

	SELECT SCOPE_IDENTITY()  AS INT
COMMIT TRANSACTION



CREATE PROCEDURE [dbo].[usp_EventParticipentInsert]
    @intRiderId       INT  ,
    @intEventId       INT  ,
    @decPaidSTG       MONEY,
    @decPaidEUR       MONEY
AS
SET XACT_ABORT ON
BEGIN TRANSACTION
INSERT INTO tblEventParticipant
VALUES(
   @intRiderId       ,
    @intEventId      ,
    @decPaidSTG      ,
    @decPaidEUR      
)
	SELECT SCOPE_IDENTITY()  AS INT

COMMIT
CREATE PROCEDURE [dbo].[usp_LicenceGetByRiderAndYear]
	@intRiderId int,
	@intYear int
AS
	SELECT * FROM dbo.tblLicense 
	WHERE
	intRiderId = @intRiderId
	AND intYear = @intYear
CREATE PROCEDURE [dbo].[usp_LicenseInsert]
    @intYear          INT,
    @intRiderId       INT,
    @vcrLicenceNumber NVARCHAR(20)

AS
SET XACT_ABORT ON
BEGIN TRANSACTION
INSERT INTO tblLicense 
VALUES(@intYear , @intRiderId, @vcrLicenceNumber)
COMMIT
CREATE PROCEDURE [dbo].[usp_RiderSearchByName]
	@FirstName nvarchar(100) ,
	@SurName nvarchar(100)
AS
	SELECT * FROM tblRider r
	WHERE (r.vcrFirstName like @FirstName + '%' OR @FirstName IS NULL)
	AND (r.vcrSurname like @SurName + '%' OR @SurName IS NULL)
	

 

 

    “Enahance script / tidy up for stored proc use and other comments in script below.”

param (
	   [Parameter(Mandatory=$true)][string]$fileName,
		[Parameter(Mandatory=$true)][string]$connString,
		[Parameter(Mandatory=$true)][int]$intEventId,
	[Parameter(Mandatory=$true)][int]$intYear
)


function ToDBNull($var) {
	if($var -eq $null) {return [System.DBNull]::Value}
	return $var;
}

#
# Script.ps1
# TODO - rename the bit above and document this method
function parseExcel([String] $fileName){
	$excel=new-object -com excel.application
	$wb=$excel.workbooks.open($fileName)
	$sh = $wb.Sheets.Item(1)
	# TODO de hard code teh endrow.
	$startrow = 2
	$endrow = 16#Connection and Query Info

# prpbably best to pass the database name etc. through as Parameters

$conn = new-object System.Data.SqlClient.SqlConnection $connString 
	#TODO Should the open be in the try/catch?
$conn.Open()
try{

	# Main for loop for parsing sheet
	# TODO rather than hard coding rows do until no end.

	for($i = $startrow;
		($sh.Cells.Item($i,1).Value2 -ne $null) -and ($sh.Cells.Item($i,1).Value2.Trim() -ne "") ; 
		$i++) {
$Name = $sh.Cells.Item($i,1).Value2
$Surname = $sh.Cells.Item($i,2).Value2
[String]$Address = $sh.Cells.Item($i,3).Value2
$Tel = $sh.Cells.Item($i,4).Value2
$email = $sh.Cells.Item($i,5).Value2
$Club = $sh.Cells.Item($i,6).Value2
$CI = $sh.Cells.Item($i,7).Value2
$ClubNo = $sh.Cells.Item($i,8).Value2();
$EC = $sh.Cells.Item($i,9).Value2
$ECTel = $sh.Cells.Item($i,10).Value2
$PaidE = $sh.Cells.Item($i,11).Value2
$PaidS = $sh.Cells.Item($i,12).Value2 
		# TODO - do we need to close the command - check documentation 
		# to see if it implements IDisposable - and is there a using equivalent in PowerShell
[System.Data.SQLClient.SQLCommand]$Command = New-Object System.Data.SQLClient.SQLCommand

	$Command.Connection = $conn
			$Command.CommandType = [System.Data.CommandType]::StoredProcedure
			# - lookup first - do within proc?.

	$Command.CommandText = "[dbo].[usp_RiderSearchByName]"
	
	$Command.Parameters.aDD("@FirstName",[System.Data.SqlDbType]::NVarChar)
	$Command.Parameters["@FirstName"].Value = $Name
	$Command.Parameters.Add("@SurName",[System.Data.SqlDbType]::NVarChar ).Value = $Surname
	[int]$ID = $null
   [System.Data.SqlClient.SqlDataReader ]$reader = $Command.ExecuteReader()
			try{
				if($reader.Read()){
					$ID = $reader["intRiderID"]
				}
			}
			finally{
				$reader.Close()
			}
			# if we didn'te find a rider then create on
			if($ID -eq 0) {
				[System.Data.SQLClient.SQLCommand]$Command =  $Command = New-Object System.Data.SQLClient.SQLCommand

			$Command.Connection = $conn
			$command.CommandType = [System.Data.CommandType]::StoredProcedure

				$Command.CommandText = "[dbo].[ups_RiderInsert]"
				$Command.Parameters.Add("@vcrFirstName",[System.Data.SqlDbType]::NVarChar ).Value = $Name
				$Command.Parameters.Add("@vcrSurname",[System.Data.SqlDbType]::NVarChar ).Value = $Surname
				$Command.Parameters.Add("@vcrAddressLine1",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($Address.Split(',')[0])
				$Command.Parameters.Add("@vcrAddressLine2",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($Address.Split(',')[1])
				$Command.Parameters.Add("@vcrTown",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($Address.Split(',')[2])
				$Command.Parameters.Add("@vcrCountryCode",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($null)
				$Command.Parameters.Add("@vcrCountry",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($null)
				$Command.Parameters.Add("@vcrPhoneNumber",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($Tel)
				$Command.Parameters.Add("@vcrClub",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($Club)
				$Command.Parameters.Add("@vcrClubNumber",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($ClubNo)
				$Command.Parameters.Add("@vcrECName",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($EC)
				$Command.Parameters.Add("@vcrECTelephone",[System.Data.SqlDbType]::NVarChar ).Value = ToDBNull($ECTel)
		
				[int]$ID = $Command.ExecuteScalar()
				}
	
[System.Data.SQLClient.SQLCommand]$Command =  $Command = New-Object System.Data.SQLClient.SQLCommand

	$Command.Connection = $conn
			$command.CommandType = [System.Data.CommandType]::StoredProcedure
	$Command.CommandText = "[dbo].[usp_EventParticipentInsert]"
				$Command.Parameters.Add("@intRiderId",[System.Data.SqlDbType]::Int).Value = $ID
				$Command.Parameters.Add("@intEventId",[System.Data.SqlDbType]::Int).Value = $intEventId
					$Command.Parameters.Add("@decPaidSTG",[System.Data.SqlDbType]::Money).Value = If($PaidS -ne $null)  {$PaidS} else {0}
					$Command.Parameters.Add("@decPaidEUR",[System.Data.SqlDbType]::Money).Value = If($PaidE -ne $null)  {$PaidE} else {0}


		

	$Command.ExecuteScalar()
			# if got a CI number
			if($CI -ne $null -and $CI.Trim() -ne '') { 
# search for a licence

			[System.Data.SQLClient.SQLCommand]$Command =  $Command = New-Object System.Data.SQLClient.SQLCommand

			$Command.Connection = $conn
			$command.CommandType = [System.Data.CommandType]::StoredProcedure
			$Command.CommandText = "[dbo].[usp_LicenceGetByRiderAndYear]"
			$Command.Parameters.Add("@intRiderId",[System.Data.SqlDbType]::Int).Value = $ID
			$Command.Parameters.Add("@intYear",[System.Data.SqlDbType]::Int).Value = $intYear
	
			[int]$LID = $null
   [System.Data.SqlClient.SqlDataReader ]$reader = $Command.ExecuteReader()
			try{
				if($reader.Read()){
					$LID = $reader["intRiderID"]
				}
			}
			finally{
				$reader.Close()
			}
				# no licence found - create one
	if($LID -eq 0){
	[System.Data.SQLClient.SQLCommand]$Command =  $Command = New-Object System.Data.SQLClient.SQLCommand

			$Command.Connection = $conn
			$command.CommandType = [System.Data.CommandType]::StoredProcedure
			$Command.CommandText = "[dbo].[usp_LicenseInsert]"
			$Command.Parameters.Add("@intRiderId",[System.Data.SqlDbType]::Int).Value = $ID
			$Command.Parameters.Add("@intYear",[System.Data.SqlDbType]::Int).Value = $intYear
	$Command.Parameters.Add("@vcrLicenceNumber",[System.Data.SqlDbType]::NVarChar).Value = $CI
		$Command.ExecuteScalar()
				}
	

	}

	}
}
Finally
{
$conn.Close()
}
$wb.Close()
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)

	}


	parseExcel($fileName)

Monday, 7 November 2016

Sprint 1 Retrospective 1 – one hell of an overrun

Overview

I’ll cover all that happened in subsequent blog entries – but it took three hours to accomplish the one hour goal that I set in Sprint 1.
Event though I’d never used VS DB Projects before, I created the project and schema and got it deployed in about 25 minutes which I thought was fair enough.  DB project was pretty easy – as I expected it to be.  To be honest I just created the tables with the tool and then typed in the columns, constraints etc. in the SQL window!
It seems to create a local database too – I’ll have to work out where that is for future testing as I now have live data.
Then came the PowerShell task.
I decided fairly late on to parse the excel rather than csv as I thought it would get rid of any comma separation issues.  A couple of google searches showed it was relatively easy.
It was – but using .Value instead of .Value2 (why?) cost me some time then building sql by concatenating strings was a stupid idea and I still had to work out how to cope with special characters like the ‘ which is prevalent in O’Tool, O’Connor etc.

Lessons

  1. Really need to break down the user stories to tiny bits!  Not sure how to deliver useable features at the same time though.
  2. Do the right thing – I new I should be creating stored procs
    1. they’d certainly add valiue down the line
    2. Strong typing is always the way to go
  3. Don’t do new stuff in a limited time – I’d never parsed powershell with excel and was caught out by lack of experience.
  4. Check for extra features/gold plating.  I added in the Organiser table because it’s in my schema but had no date for it or defined columns.  I then had to work out how to insert a row into a database with just an identity column!

The Script

Not much to publish – I’ll get the schema out – but here is the powershell that I used.  It’s probably full of holes!
#
# Script.ps1
#
function parseExcel([String] $fileName){
 $excel=new-object -com excel.application
 $wb=$excel.workbooks.open($fileName)
 $sh = $wb.Sheets.Item(1)
 $startrow = 2
 $endrow = 16#Connection and Query Info

$serverName="uj6arxo0jh.database.windows.net" 
$databaseName='AudaxDB' 
$connString = "Server=$serverName;Database=$databaseName;uid=stiona;pwd=2difficult4u2c#" 
$conn = new-object System.Data.SqlClient.SqlConnection $connString 
$conn.Open()
try{



 for($i = $startrow; $i -le $endrow; $i++) {
$Name = $sh.Cells.Item($i,1).Value2
$Surname = $sh.Cells.Item($i,2).Value2
[String]$Address = $sh.Cells.Item($i,3).Value2
$Tel = $sh.Cells.Item($i,4).Value2
$email = $sh.Cells.Item($i,5).Value2
$Club = $sh.Cells.Item($i,6).Value2
$CI = $sh.Cells.Item($i,7).Value2
$ClubNo = $sh.Cells.Item($i,8).Value2();
$EC = $sh.Cells.Item($i,9).Value2
$ECTel = $sh.Cells.Item($i,10).Value2
$PaidE = $sh.Cells.Item($i,11).Value2
$PaidS = $sh.Cells.Item($i,12).Value2 

$Command =  $Command = New-Object System.Data.SQLClient.SQLCommand

    $Command.Connection = $conn

    $Command.CommandText = "INSERT INTO tblRider VALUES( '" + $Name  + "'" +
    ",'" + $Surname.Replace("'","''") + "'" +
    ",'" + $Address.Split(',')[0] + "'" +
    ",'" + $Address.Split(',')[1] + "'" +
    ",'" + $Address.Split(',')[2] + "'" +
    ",NULL" + 
    ",NULL" +
    ",'" + $Tel + "'" +
    ",'" + $Club + "'" +
    ",'" + $ClubNo + "'" +
    ",'" + $EC + "'" +
    ",'" + $ECTEL + "'" +
        ")`n`r" + 
        "SELECT @@IDENTITY `n`r"
        
        
        $Command
        [int]$ID = $Command.ExecuteScalar()
        $ID
$Command =  $Command = New-Object System.Data.SQLClient.SQLCommand

    $Command.Connection = $conn
    $Command.CommandText = 
       "INSERT INTO tblEventParticipant VALUES( " +  $ID  +",1,'" + $PaidS + "','" + $PaidE +"')" 
    $Command
    $Command.ExecuteScalar()


if($CI -ne $null -and $CI.Trim() -ne '') { 
$Command =  $Command = New-Object System.Data.SQLClient.SQLCommand

    $Command.Connection = $conn
    $Command.CommandText = 
       "INSERT INTO tblLicense  VALUES( 2016, " +  $ID  + ",'" + $CI +"')" 
    $Command
        $Command.ExecuteScalar()

    }

 }
}
Finally
{
$conn.Close()
}
$wb.Close()
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)

 }

 parseExcel("C:\Users\stuartm\OneDrive\Documents\Audax\A300_2016\A30002016Entrants.xlsx")

Tuesday, 11 October 2016

Powershell delete all recycle bins

Get-ChildItem "D:\`$Recycle.bin\" -Recurse -Force | Remove-Item -Force -Recurse

Blatantly stolen from http://serverfault.com/questions/330776/clear-the-recycle-bin-for-all-users-in-windows-server-2008-r2

Monday, 10 October 2016

Powershell Azure - when you have multiple "directories"/ tenants.

Documentation didn't really cover this too well but when I tried to use powerhell to move items between subscriptions I kept getting an invalid subscription id.  I eventually deduced it was because I have two directories/tenants and was in the wrong one.

List subscriptions using

Get-AzureRmSubscription

then select one in the right tenant making sure you specify the TenantID too.

Select-AzureRmSubscription -SubscriptionId xxxxx -TenantId yyyyy
Basically it seems if you've multiple "Directories" / tenants you have to specify the tenant id.

Once you've done that, moving subscriptions etc. works for that Tenant.

Wednesday, 27 April 2016

Powershell - create copy in multiple directories

If found - creates a copy ofActiveDirectory.dll to ActiveDirectory.pre in each of the sub directories of the current directory.

get-childitem -recurse -filter "ActiveDirectory.dll" | foreach-object {copy -path $_.FullName -Destination "$($_.Directory)\ActiveDirectory.pre" -Container}

Not sure if the container is needed.

Tuesday, 22 March 2016

Powershell create directory structure

New-Item enables creation of a full directory structure in one - non of that mkdir stuff.

New-Item -ItemType Directory -Force -Path \\web03b\D$\EAP-6.2.0\jboss-eap-6.2\standalone\log

Powershell create directory structure

New-Item enables creation of a full directory structure in one - non of that mkdir stuff.

New-Item -ItemType Directory -Force -Path \\pppweb03b\D$\EAP-6.2.0\jboss-eap-6.2\standalone\log

Monday, 22 February 2016

Installing azure scripltets

I tried the instructions at https://azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/ using Installing Azure PowerShell from the Gallery.
The second command Install-AzureRM failed.
“The 'Install-AzureRM' command was found in the module 'AzureRM', but the module could not be loaded.!
So I ran
Import-Module -Name AzureRM
and then Install-AzureRM and it worked.
(Actually I had to change my policy to allow scripts to run first - Set-ExecutionPolicy RemoteSigned).

Stuart:1 – MS PowerShell: 0