Showing posts with label script. Show all posts
Showing posts with label script. 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 }) 
}

Sunday, 1 October 2017

Strava open image script

Sometimes I want to download peoples photos from strava.

Click on image to get it full screen

run

$im = $('div[class="photo-slideshow-content"] > image[alt="Photo"]').src
window.open($im)

in console.

Will open the image in a new window so you can download.

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!

Monday, 20 March 2017

KTA permissions for service accounts

Don’t ask – but heres a script to set permissions for KTA service accounts to run as non admins.

They also need lon on as service account permissions.

script to grant folder permission from here - http://techibee.com/powershell/grant-fullcontrol-permission-to-usergroup-on-filefolder-using-powershell/2158

param (

       [Parameter(Mandatory=$true)][string]$serviceAccount

) 



function Grant-userFullRights( [string[]]$Files, [string]$UserName) {           
 $rule=new-object System.Security.AccessControl.FileSystemAccessRule($UserName,"FullControl","Allow")            

 foreach($File in $Files) {            
  if(Test-Path $File) {            
   try {            
    $acl = Get-ACL -Path $File -ErrorAction stop            
    $acl.SetAccessRule($rule)            
    Set-ACL -Path $File -ACLObject $acl -ErrorAction stop            
    Write-Host "Successfully set permissions on $File"            
   } catch {            
    Write-Warning "$File : Failed to set perms. Details : $_"            
    Continue            
   }            
  } else {            
   Write-Warning "$File : No such file found"            
   Continue            
  }            
 }            
}
[string]$UserName = $serviceAccount

$Files = @("C:\ProgramData\Kofax\AppLogging\DB", "C:\ProgramData\Kofax Image Products\Local\Scripts")

Grant-userFullRights $Files $UserName
netsh http add urlacl http://+:80/Agility.Sdk.Services.StreamingService user=$UserName
netsh http add urlacl  http://+:3581/SALMetadata/ user=$UserName
netsh http add urlacl  http://+:3581/SAL/ user=$UserName
net stop "TotalAgility Streaming Service"
net start "TotalAgility Streaming Service"
net stop "KSALicenseService"
net start "KSALicenseService"

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")

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.

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

Monday, 30 November 2015

Getting documents from a database

I’m not proud of this – the cscript below will extract the documents from a blob database matching the query and save to a file.  In this case they are pdf’s.

Each file is given a name – the intDocumentId.pdf in this example.

 

  1. save as file e.g. extract.cs
  2. change query to suit
  3. run dos as user with access to db.
  4. Change db connection string.

 

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open "Provider=SQLNCLI;server=******;database=ddocs;Trusted_Connection=yes"
Set rs = cn.Execute("SELECT * FROM tblDocuments WHERE  dbo.tblDocuments.intDocumentTypeId in (SELECT intDocumentTypeId FROM tblDocumentType WHERE vcrDocumentType = 'myletter')  AND dteDateCreated > 2015-11-20")
Do While Not rs.EOF
    Set mstream = CreateObject("ADODB.Stream")
    mstream.Type = 1
    mstream.Open
    mstream.Write rs.Fields("vbnDocument").Value
    mstream.SaveToFile rs.Fields("intDocumentId").Value & ".pdf", 2
    mstream.close()
    rs.MoveNext()
Loop
rs.Close
cn.Close