Wednesday, 1 August 2018

PowerShell: How can I list/document all the items in my azure subscription?

The following script will create an Excel file with each Resource Group as a tab.

First, I created a password file to reference from the script (no passwords in clear text please)
"xxxx" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Temp\Password.txt" 

Here is the function - it will create seperate CSV files per resource group and then merge them intoa a single Excel file at the end.

BTW, you may want to change the hard coded directories, username and filenames as required..... enjoy

# create a function to merge the csv files we have created
Function Merge-CSVFiles 
                Param( 
                                $CSVPath = "C:\csv\", ## Soruce CSV Folder 
                                $XLOutput="c:\Temp\csv\data.xlsx" ## Output file name 
                ) 
  
                $csvFiles = Get-ChildItem ("$CSVPath\*") -Include *.csv 
                $Excel = New-Object -ComObject excel.application 
                $Excel.visible = $false 
                $Excel.sheetsInNewWorkbook = $csvFiles.Count 
                $workbooks = $excel.Workbooks.Add() 
                $CSVSheet = 1 
  
                Foreach ($CSV in $Csvfiles) 
                { 
                                $worksheets = $workbooks.worksheets 
                                $CSVFullPath = $CSV.FullName 
                                $SheetName = ($CSV.name -split "\.")[0] 
                                $worksheet = $worksheets.Item($CSVSheet) 
                                $worksheet.Name = $SheetName 
                                $TxtConnector = ("TEXT;" + $CSVFullPath) 
                                $CellRef = $worksheet.Range("A1") 
                                $Connector = $worksheet.QueryTables.add($TxtConnector,$CellRef) 
                                $worksheet.QueryTables.item($Connector.name).TextFileCommaDelimiter = $True 
                                $worksheet.QueryTables.item($Connector.name).TextFileParseType  = 1 
                                $worksheet.QueryTables.item($Connector.name).Refresh() 
                                $worksheet.QueryTables.item($Connector.name).delete() 
                                $worksheet.UsedRange.EntireColumn.AutoFit() 
                                $CSVSheet++ 
                } 
  
                $workbooks.SaveAs($XLOutput,51) 
                $workbooks.Saved = $true 
                $workbooks.Close() 
                [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbooks) | Out-Null 
                $excel.Quit() 
                [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null 
                [System.GC]::Collect() 
                [System.GC]::WaitForPendingFinalizers() 
  

# define the working folder for the csv files  
$targetDir = "c:\temp\csv" 
  
# Extract the credential using password.txt as the password source 
$user = "richard.leeman@mycustomdomain.com" 

# the location of the password file created above
$file = "C:\Temp\Password.txt" 
$myCred=New-Object -TypeName System.Management.Automation.PSCredential  -ArgumentList $user, (Get-Content $file | ConvertTo-SecureString) 
Connect-AzureRmAccount -Credential $mycred 
  
# get all the assets 
$data = Get-AzureRmResource | Sort-Object ResourceGroupName, ResourceType 
  
# get a distinct list of resource groups 
$distinctRG = $data | Select-Object ResourceGroupName -Unique 
  
# export the data to CSV 
$len = $distinctRG.Length; 
  
$a = New-Object -comobject Excel.Application 
$a.Visible = $False 
  
for ($i=0;$i -lt $len; $i++) { 
                $name = $distinctRG[$i] 
                $filename = "$targetDir\$($name.ResourceGroupName).csv" 
                
                # Export the data to a file - PowerShell is awesome
                $data | Where-Object -FilterScript { $_.ResourceGroupName -eq $name.ResourceGroupName} | Sort-Object ResourceType, Name |  Export-Csv -Path $filename 

# merge all the files into the final document
Merge-CSVFiles -CSVPath $targetDir -XLOutput "$targetDir\MyCloudAssets.xlsx" 

Wednesday, 28 February 2018

Visual Studio: The Windows SDK version 8.1 was not found. Install the required version of Windows SDK or change the SDK version in the project

I encountered this issue when trying to compile some old code.

I tried to download the SDK, but there are no active links.

My resolution was to install Visual C++' support in Visual Studio 2015 by re-running the installer.​ Its like killing a fly with a hand-grenade (3GB install), but as least it resolved the problem.

IE11 - Critical Error: Object doesn't support property or method 'addEventListener'

Add this code within the body tag and all is good.

 <script type="text/javascript">
        /* IE11 Fix */
        if (typeof (UserAgentInfo) != 'undefined' && !window.addEventListener) {
            UserAgentInfo.strBrowser = 1;
        }
    </script>​

Thursday, 7 September 2017

Backup-SPSite : You must specify a filename for the backup file.

I followed the backup instructions from here to backup my site collection but I encountered the following error: You must specify a filename for the backup file

That was strange as I have set the -Path parameter. The resolution is that the path MUST BE VALID. In my case , I was missing an underscore.

Sunday, 3 September 2017

SharePoint 2010: Unable to open Central Administration

I have been trying to install a SharePoint 2010 development environment on my local Windows 10 laptop (dont ask why) and I have finally been able to load Central Admin. Here are the issues I encountered:

1. Ensure you have Windows 10 Pro - you will need to activate Windows Auth before you install
2. Run the following script if Central Admin is

start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ManagementScriptingTools;IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-RequestFiltering;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI;WCF-HTTP-Activation;WCF-NonHTTP-Activation

NOTE: This is not mine and has been borrowed from sensoft2000-sharepoint (thank you very much)

Sunday, 6 August 2017

SharePoint 2010 on Windows 10: Solving COMException / Unknown error (0x80005000)

This is not a problem I expected to solve, but it happened anyway. A client is using SharePoint 2010 and I need a local development farm.

I started with the usual configuration requirements:
Add <Setting Id="AllowWindowsClientInstall" Value="True"/> to the Setup config

Created a script to make a new configuration database so that I dont have to join a domain
$secpasswd = ConvertTo-SecureString "MyVerySecurePassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("mydomain\administrator", $secpasswd)

$guid = [guid]::NewGuid();
$database = "spconfig_$guid"

New-SPConfigurationDatabase -DatabaseName $database -DatabaseServer myservername\SharePoint -FarmCredentials $mycreds -Passphrase (ConvertTo-SecureString "MyVerySecurePassword" -AsPlainText -force)

The PowerShell script was generating the error.

The solution is simple - you need to enable IIS 6.0 Management Compatibility on the machine

The script ran and I now have a very old SharePoint farm to use

Wednesday, 2 August 2017

Azure: Why is my blob 0KB when I move it?

I was archiving documents in Blob Storage and found that the target files were always being rendered as 0 KB.

I was using the following code:

var storageAccount = CloudStorageAccount.Parse("CONNECTIONSTRING");
var blobContainer = storageAccount.CreateCloudBlobClient().GetContainerReference("container");
var blob = blobContainer.GetBlobReference("myfilename")

// Get the source as a stream
Stream stream = new MemoryStream();
blob.DownloadToStream(stream);

var destBlob = blobContainer.GetBlockBlobReference(blob.Name);
destBlob.UploadFromStream(stream);

blob.Delete();

The code should work, except for the fact that the stream needs to be repointed to the start for the download to work.

blob.DownloadToStream(stream); (from above)
stream.Position = 0;

And now the copy/move works