Archivi tag: script

Powershell: script autenticazione su Azure CSP con scelta customer e subscription

Lo script sotto esegue l’autenticazioni su sottoscrizioni Azure di tipo CSP e la selezione della sottoscrizione da utilizzare tramite due menù di scelta.

<#
Requirement:
Powershell 5.1
Module: 
- Partner Center
- Az
#>

Import-Module PartnerCenter

Connect-PartnerCenter  
# Select customer
$customer = Get-PartnerCustomer | Out-GridView -Title "Select the partner and click OK" -PassThru

Login-Azaccount -TenantId $customer.CustomerId

# Select subscription
$Subscription = Get-AzSubscription | Out-GridView -Title "Select the Subscription and click OK" -PassThru
Select-AzSubscription -SubscriptionId $Subscription.Id -TenantId $Subscription.TenantId

Volendo, è possibile memorizzare le credenziali per evitare che vengano richieste due volte tramite il cmdlet “get-credential”. Nel momento in cui sto scrivendo, parrebbe che il comando “connect-partnercenter” generi un errore nel passaggio delle variabili (nonostante il fatto che l’autenticazione si concluda comunque con successo).

Disclaimer: nessuna garanzia è fornita con questo script. Lo scrivente non è responsabile di qualunque danno possa eventualmente derivarne – lo utilizzate a vostro rischio.

Enterprise Vault: could not load file or assembly kvs.enterprisevault.interop.evpstapi

Scenario.
Server con installata la console di Enterprise Vault.
Script per l’esportazione degli archivi in PST (requisito: da avviare in Poweshell 23 bit)
Verifica se il modulo è di Etnerprise Vault è installato
if (!(Get-Module "enterprisevault")) {import-module enterprisevault}
$exportTOpst = import-csv "C:\temp\test.csv" -Delimiter ";"
foreach ($archive in $exportTOpst){
Write-Host -ForegroundColor Magenta "Dearchiviazione dell'archivio "$archive.ArchiveName
Export-EVArchive -ArchiveId $archive.archiveID -Format PST -OutputDirectory D:\Temp -MaxPSTSizeMB 51200
}

Problema
Durante l’esecuzione dello script, viene generato l’errore “could not load file or assembly kvs.enterprisevault.interop.evpstapi”

Soluzione
Copiare nella directory di installazione di Enterprice Valut (p.e. C:\Program Files (x86)\Enterprise Vault) il file KVS.EnterpriseVault.Interop.EVPstApi.dll (presente nel server EV) e riavviare i servizi di EV

Powershell: script per configurare la scheda di rete in DHCP o con IP statico

Script per configurare la scheda di rete in DHCP o con IP statico. Permette di scegliere quale scheda di rete configurare.

function show-menu-DHCP-or-static
{
    cls
    Write-Host "Press '1' DHCP"
    Write-Host "Press '2' Static"
}

function DHCP {
    $IPtype = "IPv4"
    $interface = $adapter | Get-NetIPInterface -AddressFamily $IPtype

    If ($interface.Dhcp -eq "Disabled") {
        # Remove existing gateway
        Write-Host "Removing existing gateway"
        If (($interface | Get-NetIPConfiguration).Ipv4DefaultGateway) {
            $interface | Remove-NetRoute -Confirm:$false
        }

        # Enable DHCP
        Write-Host "Enabling DHCP on interface"
        $interface | Set-NetIPInterface -DHCP Enabled

        # Configure the  DNS Servers automatically
        Write-Host "Enabling automatic DNS"
        $interface | Set-DnsClientServerAddress -ResetServerAddresses
    }
}

function Static-IP {
    #Variable
    $IP = Read-Host "IP Address"
    $CIDR = Read-Host "CIDR"
    $GW = Read-Host "Gateway"
    $DNS = Read-Host "DNS"
    $IPtype = "IPv4"

        # Remove any existing IP, gateway from our ipv4 adapter
    If (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) {
        Write-Host "Removing existing IP"
        $adapter | Remove-NetIPAddress -AddressFamily $IPType -Confirm:$false
    }

    If (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) {
        Write-Host "Removing existing gateway"
        $adapter | Remove-NetRoute -AddressFamily $IPType -Confirm:$false
    }

    # Configure the IP address and default gateway
    Write-Host "Configuring new IP"

    $adapter | New-NetIPAddress -AddressFamily $IPType -IPAddress $IP -PrefixLength $CIDR -DefaultGateway $GW

    # Configure the DNS client server IP addresses
    Write-Host "Configuring new gateway"
    $adapter | Set-DnsClientServerAddress -ServerAddresses $DNS
}

#Selection NIC
$nic = Get-NetAdapter | select name

For ($i = 0; $i -lt $nic.Length; $i++){
    $str = ($i + 1).ToString();
    $str = $str + " - ";
    $str = $str + $nic[$i].name;
    Write-Host($str);
}

$response = Read-Host "Type the network number";

$SelectedNic = $nic[$response-1].name;

$adapter = Get-NetAdapter | Where-Object {$_.Name -eq $SelectedNic}
###

#DHCP or Static
show-menu-DHCP-or-static
$Input = Read-Host "Please make a selection"
switch ($input) {
    '1' {
        $Type = 'DHCP'
        DHCP
    }
    '2' {
        $Type = 'Static'
        Static-IP
    }
}

Disclaimer: nessuna garanzia è fornita con questo script. Lo scrivente non è responsabile di qualunque danno possa eventualmente derivarne – lo utilizzate a vostro rischio.

Powershell: importare record DNS da file CSV

Script per importare record A e Cname nel DNS da un file CSV

Esempio di file CSV:
HostName,RecordType,IPAddress
server01,a,192.168.1.1
Service01,cname,server4.mydomain.com

Script

<# CSV example
HostName,RecordType,IPAddress
server01,a,192.168.1.1
Service01,cname,server4.mydomain.com
#>

$CSV = Read-Host "CSV to import:"
$Zone = Read-Host "Zone Name:"
Import-CSV $CSV |
%{
if ($_.RecordType -eq "a") {Add-DnsServerResourceRecordA -Name $_.HostName -ZoneName $zone -IPv4Address $_.IPAddress} 
elseif ($_.RecordType -eq "cname")  {Add-DnsServerResourceRecordCName -Name $_.HostName -ZoneName $zone -HostNameAlias $_.IPAddress}
}

 

Powershell Export And Import Relying Party Trust Claim Rules

Script per esportare, esportare ed importare o importare soltanto le claim AD FS.

 

Add-PSSnapin "Microsoft.ADFS.PowerShell" -ErrorAction SilentlyContinue
$select = Write-Host "Select operation:  (1)Export; (2) Export and Import; (3) Import "
$XMLFilePath = "RPTClaim.xml"

function show-menu 
{
    cls
    Write-Host "==========Export Import AD FS Claim=========="
    Write-Host "Press '1' for Export"
    Write-Host "Press '2' for Export and Import"
    Write-Host "Press '3' for Import"
}

function export
{
    $SourceRelyingPartyTrust = Read-Host "Source Relying Party Trust" #Display Name of Source Relying Party Trust
    Get-ADFSRelyingPartyTrust -Name $SourceRelyingPartyTrust | Export-Clixml $XMLFilePath
    Write-Host "Relying Party Trust Claim Rules Exported"
}

function import{
    $TargetRelyingPartyTrust = Read-Host "Target Relying Party Trust" #Display Name of Target Relying Party Trust
    Import-Clixml $XMLFilePath | foreach-object {Set-ADFSRelyingPartyTrust -TargetName $TargetRelyingPartyTrust -IssuanceTransformRules $_.IssuanceTransformRules}
    Write-Host "Relying Party Trust Claim Rules Imported"
}

function export-import
{
export
import
}


show-menu
$input = Read-Host "Please make a selection "
switch ($input)
{
    '1' 
    {
        cls
        export
    }
    '2'
    {
        cls
        export-import
    }
    '3'
    {
        cls
        import
    }
}

 

Disclaimer: nessuna garanzia è fornita con questo script. Lo scrivente non è responsabile di qualunque danno possa eventualmente derivarne – lo utilizzate a vostro rischio.

Eseguire le Microsoft Management Console (MMC) con Runas

Si ha l’esigenza, molte volte, di dover aprire le MMC (ad esempio i tools per la gestione di Active Directory) con credenziali differenti rispetto al dominio di appartenenza. Occorre quindi utilizzare il comando Runas con lo switch netonly.

Il comando, per esempio, per eseguire la MMC di Active Directory Users and Computers è:

runas.exe /netonly /user:user@domain.local "mmc %SystemRoot%\system32\dsa.msc /domain=domain.local /server:server"

Ho configurato uno script in Powershell con le MMC di Active Directory Management Tools:

function Show-Menu
{
     param (
           [string]$Title = 'Runas_MMC.ps1'
     )
     cls
     Write-Host "================ $Title ================"
     
     Write-Host "1: Press '1' for Active Directory Users and Computers."
     Write-Host "2: Press '2' for Active Directory Sites and Services."
     Write-Host "3: Press '3' for Active Directory Domain and Trusts."
     Write-Host "4: Press '4' for ADSI Edit."
     Write-Host "Q: Press 'Q' to quit."
}

do
{
     Show-Menu
     $input = Read-Host "Please make a selection"
     $server = Read-Host "Server"
     $user = Read-Host "Domain\User"
     switch ($input)
     {
           '1' {
                cls
                runas.exe /netonly /user:"$user" "mmc c:\windows\system32\dsa.msc /server=$server"
           } 
           '2' {
                cls
                runas.exe /netonly /user:"$user" "mmc c:\windows\system32\dssite.msc /server=$server"
           } 
           '3' {
                cls
                runas.exe /netonly /user:"$user" "mmc c:\windows\system32\domain.msc /server=$server"
           } 
           '4' {
                cls
                runas.exe /netonly /user:"$user" "mmc c:\windows\system32\adsiedit.msc /server=$server"
           }
           'Q' {
                return
           }
     }
     pause
}
until ($input -eq 'q')

Esecuzione dello script

E’ possibile modificare lo script aggiungendo o eliminando le varie console.

Disclaimer: Nessuna garanzia è fornita con questo script. Lo scrivente non è responsabile di qualunque danno possa eventualmente derivarne – lo utilizzate a vostro rischio.

Creare lista delle VM configurate in Azure Resource Manager con Powershell

Il seguente script esporta in un file CSV la lista e le configurazioni delle VM configurate in Azure Resource Manager.

Configurazioni esportate:

  • Nome macchina
  • Resource Group
  • Utenza amministratrice locale
  • Indirizzo IP
  • Informazioni dischi
$vms = get-azurermvm
$nics = get-azurermnetworkinterface | where VirtualMachine -NE $null 
$VMArray = @()

foreach($nic in $nics)
    {
        $vm = $vms | where-object -Property Id -EQ $nic.VirtualMachine.id
        $IPprv =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
        $AlMeth =  $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod
        
        $VMArray += New-Object PSObject -Property @{`
        Name = $vm.Name;
        ResourceGroup = $vm.ResourceGroupName;
        AdminUserName = $vm.AdminUsername;
        PrivateIPAddress = $IPprv ;
        IPAllocation = $AlMeth;
        Location = $vm.Location;
        Size = $vm.HardwareProfile.VmSize;
        ImageSKU = $vm.StorageProfile.ImageReference.Sku;
        OSType = $vm.StorageProfile.OsDisk.OsType;
        DataDiskCount = $vm.StorageProfile.DataDisks.Count;
        DataDisks = $vm.StorageProfile.DataDisks;
        }
    

}
$VMArray | export-csv "AzureRMInventory.csv"

Disclaimer: Nessuna garanzia è fornita con questo script. Lo scrivente non è responsabile di qualunque danno possa eventualmente derivarne – lo utilizzate a vostro rischio.

Creare una VM in Azure tramite Powershell e ARM

AzureIl seguente sript crea una Vitual Machine in Azure tramite Powershell e Azure Resource Manager (ARM).

Elementi creati dallo script
  • Resource Group
  • Availability Set
  • Virtual Network e subnet
  • Network interface e Public IP
Caratteristiche VM

Sistema Operativo: Windows Server 2012 R2 DataCenter
Size: Standard A1

Prerequisiti

Powershell v. 5
Modulo Azure 3.0.0 (Installazione e configurazione di Azure Powershell)

#Variable
$rgName = Read-Host -Prompt 'Resource Group name';
$locName = 'West Europe';

#Create Resource Group
New-AzureRmResourceGroup -Name $rgName -Location $locName ;

#Create Availability Set
$asName = Read-Host -Prompt 'Availability Set name'
New-AzureRmAvailabilitySet -ResourceGroupName $rgName -Name $asName -Location $locName -PlatformUpdateDomainCount 2 -PlatformFaultDomainCount 2
$AvID = (Get-AzureRmAvailabilitySet -ResourceGroupName $rgName -Name $AsName).id

#Create subnet
$newSubnetParams = @{
    'Name' = Read-Host -Prompt 'Subnet name'
    'AddressPrefix' = '10.0.0.0/24'
}
$subnet = New-AzureRmVirtualNetworkSubnetConfig @newSubnetParams

#Create VirtualNet
$newVNetParams = @{
    'Name' = Read-Host -Prompt 'Network Name'
    'ResourceGroupName' = $rgName
    'Location' = $locName
    'AddressPrefix' = '10.0.0.0/16'
}
$vNet = New-AzureRmVirtualNetwork @newVNetParams -Subnet $subnet

#Create Storage Account
$newStorageAcctParams = @{
    'Name' = Read-Host -Prompt 'Storage Account name (lowercase)' 
    'ResourceGroupName' = $rgName
    'Type' = 'Standard_LRS'
    'Location' = $locName
}
$storageAccount = New-AzureRmStorageAccount @newStorageAcctParams

#Create Public IP
$newPublicIpParams = @{
    'Name' = Read-Host -Prompt 'Label Public IP'
    'ResourceGroupName' = $rgName
    'AllocationMethod' = 'Dynamic' ## Dynamic or Static
    'DomainNameLabel' = Read-Host -Prompt 'DNS name'
    'Location' = $locName
}
$publicIp = New-AzureRmPublicIpAddress @newPublicIpParams

#Create NIC
$newVNicParams = @{
    'Name' = Read-Host -Prompt 'NIC Name'
    'ResourceGroupName' = $rgName
    'Location' = $locName
}
$vNic = New-AzureRmNetworkInterface @newVNicParams -SubnetId $vNet.Subnets[0].Id -PublicIpAddressId $publicIp.Id

#Config VM - General
$newConfigParams = @{
    'VMName' = Read-Host -Prompt 'VM name'
    'VMSize' = 'Standard_A1'
    'AvailabilitySetId' = $AvID
}
$vmConfig = New-AzureRmVMConfig @newConfigParams

#Config VM - Operating System
$newVmOsParams = @{
    'Windows' = $true
    'ComputerName' = $newConfigParams.VmName
    'Credential' = (Get-Credential -Message 'Type the name and password of the local administrator account.')
    'ProvisionVMAgent' = $true
    'EnableAutoUpdate' = $true
}
$vm = Set-AzureRmVMOperatingSystem @newVmOsParams -VM $vmConfig

#Config VM - Image
$newSourceImageParams = @{
    'PublisherName' = 'MicrosoftWindowsServer'
    'Version' = 'latest'
    'Skus' = '2012-R2-Datacenter'
}
 
$offer = Get-AzureRmVMImageOffer -Location $locName -PublisherName MicrosoftWindowsServer
$vm = Set-AzureRmVMSourceImage @newSourceImageParams -VM $vm -Offer $offer.Offer

#Attach NIC to VM
$vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $vNic.Id

#Config VM - Disk
$Saname = $newStorageAcctParams.name
$VmName = $newConfigParams.VmName
$osDiskName = $vmName+'_os'
$osDiskUri = 'https://'+$saname+'.blob.core.windows.net/vhds/'+$osDiskName+'.vhd'
 
$newOsDiskParams = @{
    'Name' = $osDiskName
    'CreateOption' = 'fromImage'
}
 
$vm = Set-AzureRmVMOSDisk @newOsDiskParams -VM $vm -VhdUri $osDiskUri

#Create Vm
New-AzureRmVM -VM $vm -ResourceGroupName $rgName -Location $locName

Disclaimer: Nessuna garanzia è fornita con questo script. Lo scrivente non è responsabile di qualunque danno possa eventualmente derivarne – lo utilizzate a vostro rischio.

[Script Powershell] Connettersi sugli StorSimple serie 8000

Avendo avuto necessità di connettermi tramite Powershell sugli apparati StorSimple serie 8000 tramite HTTP, ho cercato uno script che mi permettesse di automatizzare la connessione.
Mi sono imbattutto nello script di Sam Boutros ma al momento di settare nei Trusted Host l’indirizzo dello StorSimple mi veniva restituito il seguente errore:
Set-Item : Cannot convert ‘System.Object[]’ to the type ‘System.String’ required by the parameter. Specified method is not supported.

Ho quindi modificato lo script come segue:
$StorSimpleIP = get-content -path .\IPStorSimple.txt

foreach ($address in $StorSimpleIP) {set-item wsman:\localhost\Client\TrustedHosts -Value $address.ToString() -Force}

# Get pwd for SSAdmin, store in encrypted local file for future automation
if (!(Test-Path -Path “.\SSCred.txt”)) {
Read-Host ‘Enter the pwd for your StorSimple administration’ -AsSecureString | ConvertFrom-SecureString | Out-File .\SSCred.txt
}
$Pwd = Get-Content .\SSCred.txt | ConvertTo-SecureString
$SSCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList “$StorSimpleIP\ssadmin”, $Pwd

$StorSimpleSession = Get-PSSession | where { $_.ComputerName -eq $StorSimpleIP }
if (! $StorSimpleSession) { $StorSimpleSession = New-PSSession -ComputerName $StorSimpleIP -Credential $SSCred -ConfigurationName SSAdminConsole }
$StorSimpleSession

Enter-pssession -credential $SSCred -ConfigurationName SSAdminConsole -ComputerName $StorSimpleIP

ScriptConnectStorSimple

Script Powershell – Report farm Hyper-V

HyperV_logoMi occorreva uno script che restituisse lo stato dei volumi configurati in un cluster Hyper-V.

Mi sono imbattuto in questo simpatico script che oltre a fare quello che cercavo, invia tramite e-mail un report dettagliato in HTML sulla farm Hyper-V.
Tra le varie voci del report:

VM Name
Up-Time
Integration Component Version
Clustered or Not
No of vProcessors
StartUp Memory
Minimum Memory
Maximum Memory
Average Memory (If Resource Metering is enabled)
vDisk1-Storage (CSV Volume or Local Drive Letter)
VHDX – Disk 1 – Allocated Size
VHDX – Disk 1 – Actual Usage
Disk Fragmentation
vDisk2-Storage (CSV Volume or Local Drive Letter)
VHDX – Disk 2 – Allocated Size
VHDX – Disk 2 – Actual Usage
Disk Fragmentation
Type of Disk – VHD or VHDX
vNIC – Legacy or Synthetic
Date – First Snapshot created

Screenshot: Storage Report

Reference: http://insidevirtualization.com/hyperv3/hyper-v-dashboard-v-3-3-released/