Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Saturday, 19 September 2020

Quick Script: DC Audit Policy

Quick Script: DC Audit Policy

Quick Script: Check all Domain Controllers for Audit Policy Settings

Introduction

Here’s a quick script to gather the detailed audit policy for all Domain Controllers in the domain. This is useful if you have domain controllers in different OUs with different policies applied. It will give a quick overview of each audit policy on each machine and since it’s in a GridView it’s easy to filter and sort the list so you can check a single policy against all your DCs.

The Script

Written with StackEdit.

Friday, 26 May 2017

Automating VNX Snapshots with EMC Storage Integrator Powershell

I've been working on automating snapshot creation for a bunch of datastores for one of our applications. In the past I would have written a PowerShell wrapper for the old Navisphere CLI, but I thought I would check to see if the PowerShell module for EMC VNX had gotten any better.

It has! Very much better!

Some of the nice features I have noticed while working on this script:
  • You can connect to multiple storage arrays and search for LUNs across arrays.
  • Once you have the LUN objects you can work on them and not need to care which SAN they are on.
I have published the script here on my GitHub.

The script is intended to be scheduled to run on a daily basis and will automatically clear any snapshots older than the 'expireDays' parameter.

The script will detect which type of LUN is passed in and will create a pool based snapshot for pool LUNs and a SnapView snapshot for RAID based LUNs.

Comments and improvements always welcome.

An example for running the script follows:

Tuesday, 7 February 2017

HP Data Protector Backups using Compellent PowerShell snapshots

There are three main steps in this setup:
  1. Setup snapshot / scripting host server (in my case this is a virtual machine with iSCSI network connections) 
  2. PowerShell Scripts 
  3. HP DP configuration
Prerequisites: 
  • Snapshot Host machine which is connected to the iSCSI network. 
  • Compellent Enterprise Manager Server setup and configured. 

Step 1 – Configure the Snapshot Server for storage access to the Compellent Array 

Configure the Compellent Enterprise Manager Server 
Add the snapshot / scripting server in Compellent enterprise manager using the “Create Server” wizard. 




Get the IQN of the snapshot server: 




Enter Server Name, Windows 2012 MPIO for multi path and the IQN of the server from the iSCSI control panel applet into the Create Server wizard 




On the snapshot server: 
  • Install the Windows MPIO feature: 
           Add-WindowsFeature Multipath-IO 
  • Click Start, Type MPIO and click the MPIO icon 
  • Click “Discover Multi-Paths”  
  • Tick add support for iSCSI and click Add 
  • Reboot the machine if required 

  • Open the iSCSI Control Panel Applet (iscsicpl) on the snapshot / scripting server and enter the target addresses of the SAN. 
  • Click connect on each of the discovered targets that appear, ensure enable MPIO is ticked for each. 
  • Click volumes and devices and “Auto Configure” 
  • There should be a single device showing in the volume list which is the Compellent 



The server should now show as connected in the Compellent Enterprise Manager: 





Step 2 – Configure the PowerShell Scripts on the Scripting / Snapshot Server 

To download the Dell Compellent PowerShell Cmdlets you need to get a Dell Co-Pilot account configured here: 
Once I my account was approved, I was able to login, navigate to the Knowledge Centre, then software. From here I downloaded Dell Storage PowerShell SDK v2.2.1. I have provided the link but it will need registration to download. 

Download and unzip the PowerShell modules to an appropriate location. I use: 
C:\ Scripts\DellStoragePowerShellSDK_v2_2_1_362 

You will need to get a serial number from your controller, this can be found in Enterprise Manager under the hardware tab, then click a controller and the “Index” is the serial required. 





My scripts are available for download on GitHub and can be used with the following syntax: 

C:\Scripts\CompellentSnapAttach.ps1 -scSn "00000" ` 
    -serverName "scriptserver.lan" -Credential $Credentials ` 
    -port 3033 -TargetVolume "My Volume" ` 
    -managementHostName "managementserver.lan 


The port shown is the default data collection port for the Compellent management server. 

Credentials can be saved using the PowerShell and SecureString method as in the blog post here. 



Step 3 – Configure HP Data Protector to execute PowerShell scripts pre and post backup 

On the Scripting server 
Create .bat files containing the required pre and post code in C:\Program Files\Omniback\Bin 
My scripts are as follows 

AttachGoldImages.bat 
powershell.exe -File "C:\Scripts\AttachGoldImages.PS1" 

DetachGoldImages.bat 
powershell.exe -File "C:\Scripts\DetachGoldImages.PS1" 

In Data Protector Manager 
Open the backup specification and go to the Options tab 
Click the Advanced button in ‘Backup Specification Options’ 
Enter the filenames of the .bat files created earlier. The “On Client” box should be the scripting server that the .bat files are located on. 



Once all of these steps are complete, the scripting server can now mount an iSCSI replay, perform the backup and then remove the replay from both the scripting server and the Compellent array. 

Wednesday, 23 November 2016

What is 'Double Hop Authentication' in Windows and why should I care?

If you've tried to use Invoke-Command to run commands with credentials on a remote machine and received unexpected Access Denied messages then you may have run across Double Hop Authentication issues.

If the command you tried to run needs to pass credentials to a second machine in order to execute, then you will likely receive an Access Denied message like the following.

You do not have permission to perform the operation. Contact your administrator if you believe you should have
permission to perform this operation.
    + CategoryInfo          : PermissionDenied: (:) [Get-VM], VirtualizationOperationFailedException
    + FullyQualifiedErrorId : AccessDenied,Microsoft.HyperV.PowerShell.Commands.GetVMCommand
    + PSComputerName        : HYPERV1

The most recent example I've seen is when attempting to run System Center Configuration Manager PowerShell commands on a remote machine using Jenkins. The error message above isn't much help, but since I'm running Invoke-Command with the -Credentials and -Computer parameters - and then trying to authenticate to a further machine - 'Double Hop' is probably the issue.

Another example is trying to run something like the following:

Invoke-Command -Computer hyperv1 -Credential $Cred -ScriptBlock { Get-VM -ComputerName hyperv2 }

The server hyperv1 will attempt to authenticate to hyperv2, but it is not authorised to cache and forward the credentials.



How can I fix it?

In order to be able to pass credentials via a remote machine to another machine, you need to configure CredSSP (Credential Security Service Provider.) This does have security issues, since you are trusting the remote machine to cache and re-send your credentials to the second machine. You should only configure this for machines you fully trust.

To configure your machine to use CredSSP perform the following steps in an administratively elevated PowerShell console.

Client Steps:

Run the get command to view the current allowed list. If it is empty then you can run the enable command with a single machine. If it contains other machines you'll need to combine your machine with the existing list and run the enable command. The list is comma delimited. This setting is also available in Group Policy: Computer Configuration -> Administrative Templates -> Credentials Delegation -> Allow delegating fresh credentials.

    Get-WSManCredSSP

    Enable-WSManCredSSP -Role "Client" -DelegateComputer "server.domain.com"



Server Steps:

    Enable-WSManCredSSP -Role "Server"

If you haven't already configured an HTTPS listener on the server you can do so with this command.

    winrm quickconfig -transport:https

There are pre-requesites to this such as having a valid not self-signed certificate for the FQDN of the server machine.

Once completed you should now be able to re-run your command specifying -Authentication CredSSP

An example of the Hyper-V command that didn't work before is:

Invoke-Command -Computer hyperv1 -Credential $Cred -ScriptBlock { Get-VM -ComputerName hyperv2 } -Authentication CredSSP

Further reading on the PowerShell command for configuring this here.

The classic way to configure this is detailed on MSDN here.

Thursday, 22 September 2016

Store a credential to a file in Powershell

Store a credential to a file in Powershell

In Powershell you can use SecureString to store a password for a user account. Once saved, the encrypted password can be decrypted by the same Windows user for later use.

This is handy if you need to supply a PSCredential object to a cmdlet in a scheduled script.

To store the credential, enter the username and password into a PSCredential object while logged into the user account which will be used to execute the script.

$credential = Get-Credential

Once you have the object, convert the password from a secure string and output to a file

$credential.Password | ConvertFrom-SecureString | Out-File .\credentialpw.bin -enc ASCII

Once the password is in the file, you can re-import the password to a credential object as follows.

$userName = "myuser"
$secPassword = Get-Content .\credentialpw.bin | ConvertTo-SecureString
$newCredential = New-Object System.Management.Automation.PsCredential($userName,$secPassword)

The $newCredential object can now be used to pass to a cmdlet.

If you try to use the password file as a different Windows user, the password file cannot be converted to a SecureString:


Keep in mind that the password as a securestring object can be reversed back to plain text, so this should not be used to keep the password safe from the user account it is stored by.

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secPassword)
$PlainText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

The above commands will allow you to recover the plain text password - but only as the user that originally saved the credential.


Tuesday, 20 September 2016

Convert Classic Azure VM to Azure Resource Manager with Powershell

Problem


I have a classic VM which I want to move into an Azure Resource Manager machine. The only way this is currently possible is to recreate a new machine using an existing VHD. Unfortunately this doesn’t work if you just try to create an RM machine using the existing classic storage VHD.

You can get the VHD location for the powershell code from Azure Portal, click on the stroage account and in through blobs, vhds etc.

Powershell Code

Login-AzureRMAccount

#New VM Information
$rgName="ServersUS"
$netrgName="ServersUS"
$vnetName="NetworkUS"
$subnetIndex=0

$locName="Central US"
$vmName="newvm"
$vmSize="Basic_A2"

#Old VM Information
$osDiskUri="https://classicalstorageaccount.blob.core.windows.net/vhds/classic.vhd"
$diskName=$osDiskUri.Split("/")[-1] #This should just be the filename of the vhd

$vnet=Get-AzureRmVirtualNetwork -Name $vnetName -ResourceGroupName $netrgname
$nicName="$($vmName)-nic"
$nic=New-AzureRmNetworkInterface -Name $nicName -ResourceGroupName $netrgName `
    -Location $locName -SubnetId $vnet.Subnets[$subnetIndex].Id
$vm=New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vm=Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id
$osDiskCaching = 'ReadWrite'
$vm=Set-AzureRmVMOSDisk -VM $vm -VhdUri $osDiskUri -name $DiskName `
    -CreateOption attach -Windows -Caching $osDiskCaching

New-AzureRmVM -ResourceGroupName $rgName -Location $locName -VM $vm

Error while using classic storage

WARNING: Error occurred when getting storage account, classicalstorageaccount, for boot diagnostics: Sequence contains no matching element
WARNING: Since the VM is created using premium storage, existing standard storage account, rmstorageaccount, is used for boot diagnostics.
New-AzureRmVM : Long running operation failed with status 'Failed'.
StartTime: 20/09/2016 14:48:55
EndTime: 20/09/2016 14:48:56
OperationID: f49d21d3-b3e5-44c0-85d7-72bba687b371
Status: Failed
ErrorCode: AcquireDiskLeaseFailed
ErrorMessage: Failed to acquire lease while creating disk 'classic.vhd' using blob with URI https://classicalstorageaccount.blob.core.windows.net/vhds/classic.vhd. Blob is already in use.
At line:29 char:1
+ New-AzureRmVM -ResourceGroupName $rgName -Location $locName -VM $vm
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [New-AzureRmVM], ComputeCloudExcep
   tion
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand

Resolution

Copy the vhd to a new storage account using the Azure Storage Explorer or Powershell. You will need to change the access policy on the vhd to Blob or Container in order to copy using the Storage Explorer. There is a powershell method (linked above) which allows you to copy the file using authentication.


Changing the access policy for the vhd file in Azure Portal

File copy took about 20 mins going from central US classic to Central US Resource Manager. Once completed the powershell code above can be used to create a new virtual machine with an existing VHD

Friday, 16 September 2016

Sysprep already exists when trying to deploy machines with New-QVWComputer

Sysprep already exists when trying to deploy machines with New-QVWComputer

New-QVWComputer : A SysPrep customization with the name [SERVERNAME] already exists.
At C:\Scripts\MyScript.ps1:78 char:12
+ $NewVMs += New-QVWComputer -ComputerGroup $InactiveGroup -Farm $Farms `
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-QVWComputer], ValidationRuleException`1
    + FullyQualifiedErrorId : Quest.vWorkspace.BusinessLayer.Infrastructure.Actions.ValidationRuleException`1[[Quest.vWorkspace.BusinessLayer.Infrastructure.SysPrep.Sys
   PrepRecord, Quest.vWorkspace.BusinessLayer, Version=8.6.308.2000, Culture=neutral, PublicKeyToken=76d0ba9347d138d6]],Quest.vWorkspace.PowerShell.Infrastructure.NewQ 
  vwComputerCommand

      Run SQL Server Management Studio on your database server
      Find the vWorkspace database
      Find the dbo.DmSyspreps table
      Right Click on the table > Edit Top 200 Rows
      Right Click in the right hand pane > Pane > SQL
      Add “WHERE        (SysprepName = 'SERVERNAME')” to the end of the query
      Right click > Execute SQL


Change the sysprep name of the machine which wasn’t fully deleted. I cancelled the provisioning task which meant it wasn’t cleaned up from the DB. It should be safe to delete the line, but I wanted to make sure all was OK when doing it.


SQL datatype conversion error when trying to deploy machines with New-QVWComputer

SQL datatype conversion error when trying to deploy machines with New-QVWComputer

New-QVWComputer : The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
At C:\MyScript.ps1:78 char:12
+ $NewVMs += New-QVWComputer -ComputerGroup $InactiveGroup -Farm $Farms `
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-QVWComputer], SqlException
    + FullyQualifiedErrorId : System.Data.SqlClient.SqlException,Quest.vWorkspace.PowerShell.Infrastructure.NewQvwComputerCommand

The command works when using a different template. Template dates have been screwy in vWorkspace when deploying using the powershell commandlets and I think this is the same root cause.

I’m assuming that the error is because the SQL back end is trying to parse a UK date string as a US datetime object and failing to do so correctly.

Hopefully changing the modified date will allow the SQL back end to parse the date (incorrectly) and will allow the deployment to work. I intend to change to a date which will parse as a US format date ie. Not greater than day 12 of any month.

This Dell link hints at a similar problem https://support.software.dell.com/vworkspace/kb/142232 and suggests a workaround on the broker machines.

$file = get-item TEMPLATENAME.vhdx
$file.LastWriteTime = $newDate.AddDays(-5) #Works out as 10/09/2016
$file.LastWriteTime

Once the date is updated, import the template



 After updating the template the New-QVWComputer command will now deploy from the template.



Nutanix CE 2.0 on ESXi AOS Upgrade Hangs

AOS Upgrade on ESXi from 6.5.2 to 6.5.3.6 hangs. Issue I have tried to upgrade my Nutanix CE 2.0 based on ESXi to a newer AOS version for ...