Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Sunday, December 30, 2018

Launch PowerShell ISE with another Credential

In a situation, where you are login in your laptop, when you launch the PowerShell it will be your current login credential

image

I need to login with another credential which has admin rights to perform certain tasks


SNAGHTML64b5603

When a box appears, key in your password

A new PowerShelll ISE is launch

image

And now I can carry out the tasks in this window with admin rights

In summary the command is

Start-Process powershell_ise.exe -Credential "yourdomain\adminID"  

Make changes to the syntax in yellow.  The command must have the quotes as shown.

keywords : launch powershell ise with another credential, launch powershell  ISE with administrator rights, power shell

Monday, February 27, 2017

How to remove “Unsupported Cluster Configuration” in SCVMM 2012

Recently I had a incident in one of the end user’s environment. 

The scenario is as follow :
The storage LUNs where the Virtual Machines resides had several Hard Disks failed.  There were not enough hotspare disks assigned to it.  The only way is to replace the faulty Hard Disks in the storage and then reconfigure it again.

Once it was done, the LUN was presented back to the Hosts and Failover Cluster recognize the LUN and then VMs were configured.

However, in the System Center Virtual Machine Manager (SCVMM 2012) has an issue.  It contained two identical records.  One is displayed as Running and another as Unsupported Cluster Configuration

image

Steps Taken

  • Ensure the VM is running in the Cluster
  • Launch the Virtual Machine Manager Command Shell in the Server that is running the SCVMM 2012
    (right-click run as administrator)
    image
  • Key in the command as follow in the VMM Command Shell that was launched :

    Get-SCVirtualMachine | where { $_.Name -EQ "Duplicate-ComputerName"} | fl name, status


    Note : Replace the Pink with your computer name that you want to remove from the SCVMM.   Remember the rest of the commands stay, including the quotes.
  •  It will display something like the screen below :

    SNAGHTMLb479c8
  • Next is to execute the command to  remove from the SCVMM database
    Get-SCVirtualMachine | where { $_.Name -EQ "Duplicate-ComputerName"} | Remove-SCVirtualMachine –Force

    Note : Replace the Pink with the computer name that you want to remove from the SCVMM.  The rest of the commands stays inclusive the quotes.  This is going to remove from the SCVMM DB but not removing the VM.  Remember the VM needs to be up and running.
  • In the SCVMM, the record will be removed and you need to do a refresh to once again get the information from the Cluster. 
    Right click on the Cluster in the VMM and click refresh

    image

After the SCVMM has completed the job (getting the information from the Cluster), the Unsupported Cluster Configuration is no longer in the record.  The one that is healthy is displayed in the cluster information.

A thank you to Aidan Finn and Law.

keywords : error 2604, unsupported cluster configuration, system center virtual machine manager, scvmm hyper-v, duplicate computer name in scvmm 2012, how to remove computer from scvmm 

Saturday, September 3, 2016

Azure–Powershell (Updated)

Recently the PowerShell for Azure, there’s an update that you can download from the GitHub

The Link is located in here.

You need to have the Azure SDK installed first.  The installation file can be download from this link.

image

Hope this helps.

keywords : Azure, powershell, azure command-line,

Tuesday, June 28, 2016

PowerShell–Get-VM command is not recognize or missing

Currently I’m supporting one of the customer, found out that the PowerShell is in version 1.0 in the SCVMM.  Therefore, I tried to execute a script using the get-vm but it says as not recognize.

The message was :

PS C:\Users\Administrator\Desktop> Get-VM
The term 'Get-VM' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
As a workaround, I’ve execute the command as below :

Import-Module virtualmachinemanager

Then the get-vm command works.

keywords : SCVMM, get-vm missing, get-vm command not recognize, powershell command not recognize.

PowerShell–Listing of Folder Permission, export to CSV

Today would like to share with you about a way to list down all the Folder and subfolder permission into a CSV format.  This is good especially for internal or external audits.

There are two options that you can run.

  • Run in the File Server (provided you have PowerShell installed)
  • Run from your Computer (Map the File Server Drive, and also provided you have PowerShell installed in your computer)

The coding is as below :

# This is the file specified for the Output of CSV. Make the necessary change
$OutFile = "C:\Download\Permission.csv"

$Header = "Folder Path,IdentityReference,AccessControlType,IsInherited,InheritanceFlags,PropagationFlags"
Del $OutFile
Add-Content -Value $Header -Path $OutFile


# This is the top path of where want to scan the permission from.  This will include the sub folders
$RootPath = "C:\Download\Driver"

$Folders = dir $RootPath -recurse | where {$_.psiscontainer -eq $true}

foreach ($Folder in $Folders){
    $ACLs = get-acl $Folder.fullname | ForEach-Object { $_.Access  }
    Foreach ($ACL in $ACLs){
    $OutInfo = $Folder.Fullname + "," + $ACL.IdentityReference  + "," + $ACL.AccessControlType + "," + $ACL.IsInherited + "," + $ACL.InheritanceFlags + "," + $ACL.PropagationFlags
    Add-Content -Value $OutInfo -Path $OutFile
    }}

Note : Make changes to the Pink in colour according to your CSV file and which path you want to scan your File Server and export out the permission listing.

The output will be something like below when open with Excel :

image

I’m executing on my PC, that’s the reason I have the output as above.

Thank you and hope this helps.

keywords : ACL, folder permission, powershell, File Server, fileserver, Access list, access control list, permission to CSV

Thursday, June 9, 2016

Azure – Removing / Deleting Resource Group with PowerShell

Since Azure introduced the new portal, the recommendation to create is as below :

  1. Create Resource Group
  2. Create Azure Storage Account
  3. Create Azure VNET

That is the 3 basic items that MUST be created first before creating any VMs.

So now I face the “horror of cleaning up” after conducting some demos. The cleaning up is quite a challenge through the GUI Management Portal.  Therefore I need to clear the entire Resource Group.  Before I can delete that, I need to delete all the contents in the resource group. It’s very tedious.

Now I’ve found a way that I would like to share.

Step 1

Update your local PowerShell with the Azure SDK.   If not download it from here.

[image12.png]

Step 2

Once it’s installed, then you should have the Azure commands added into your PowerShell.

Launch the Run ISE as Administrator

Minimize the PowerShell Window.

Step 3

SNAGHTML5584fe7

  • Expand the left panel
  • Browse to the Resource Group

SNAGHTML5603fb3

  • Take note of the PowerShell command (which is going to help later).

Step 4

  • Maximize the PowerShell that was launch earlier (ISE) in Step 2
  • Login using the command of Login-AzureRMAccount

SNAGHTML562ddbf

  • Take note of the SubscriptionId
  • The command to remove the entire Resource Group is as follow :

Remove-AzureRMResource –ResourceId /subscriptions/SubscriptionId/resourceGroups/resourcegroupname/ –ApiVersion 2014-04-01 –Force

Note : Only make changes to the pink colour syntax.  The first is your subscription ID information that you get from the top when you login to Azure and the second one is the resource group name. 

  • If you’re not so sure of the command, then refer to the command that you noted earlier in Step 3 from the Azure Resource Explorer.
  • As example I would like to delete off the entire Resource Group of RG-CANADA-CENTRAL-01 in my subscription then I type the following :

image

  • Once it’s completed removing the Resource Group, a True word is indicated.

image

So hopefully the above helps you as it has helped me in cleaning up the Resource Group.

keywords : azure, resource explorer, manage azure, azure portal , resource group, housekeeping resource group, new azure portal, manage azure portal

How to Remove Azure Account (Cached) using PowerShell

Recently I’ve done quite a lot of testing using various accounts to Azure.  All the commands are executed in the PowerShell ISE (Run ISE are Administrator).

The PowerShell should have the Azure Commands in it already.  If not, can download from here.

Select the Install from the Command-line tools

image

When I tried to Get-AzureAccount, it displayed more than one account and subscriptions

image

I need to remove the other subscriptions.  Therefore I perform as follow :

image

Execute the command as below :

  • Get-AzureAccount | format-table id

Once displayed, I execute to remove the account using

  • Remove-AzureAccount account-name

Note : Just replace the account-name with the account that needs to be deleted.

Another way is to remove all the accounts then re-add it back. 

To do this execute it as below to remove all the accounts :

  • Get-AzureAccount | ForEach-Object {Remove-AzureAccount $_.ID -Force}

To add the account that I’m working on, use :

  • Add-AzureAccount

 

keys : add azure account, remove azure account in cache, Azure powershell command line, command-line, azure subscription, AzureSubscription, get-azureaccount, remove-azureaccount, Azure SDK

Monday, April 4, 2016

Killing a Hung VM in Task Manager (Another PowerShell command)

This is another command of how to kill a Hung VM by identify the Process ID using PowerShell command :

image

For Windows 2012

Get-WmiObject -Namespace root\virtualization -class msvm_computersystem | select elementname, operationalstatus, processid, name| ft –auto

For Window 2012 R2

Get-WmiObject -Namespace root\virtualization\v2 -class msvm_computersystem | select elementname, operationalstatus, processid, name| ft –auto

Once the Process ID is obtain, launch the Task Manager and kill the VMWP.exe process with the correspondence Process  ID to that particular VM.

image

Hope this helps.

keywords : hang VM, hung VM, stuck VM, Hyper-V virtualization stuck Server 2012 R2, vmwp.exe, killing vwmp.exe

Killing a Hung VM in Task Manager

Sometimes the VM we tried to stop hangs.  So in order to kill the process using the Task Manager, we can end process of VMWP.exe.  But the next question is which one.  Each VM has a unique Process ID.

image

Therefore, I launch the elevated Powershell by executing the following command below

Get-WmiObject win32_process -Filter "Name like '%vmwp%'" | Select-Object ProcessID, @{Label="VMName";expression={(Get-VM -Id $_.commandline.split("")[1]|Select-Object VMName).VMName}}|ft –AutoSize

image

So I go back to the Task Manager and Right-Click on it and end task,base on the Process ID of that particular VM.

image

Hope this command helps you as it helped me.

keywords : hang VM, hung VM, stuck VM, Hyper-V virtualization stuck Server 2012 R2, vmwp.exe, killing vwmp.exe

Tuesday, November 3, 2015

How to Remove Azure Account (Cached) using PowerShell

Recently I’ve done quite a lot of testing using various accounts to Azure.  All the commands are executed in the PowerShell ISE (Run ISE are Administrator).

The PowerShell should have the Azure Commands in it already.  If not, can download from here.

Select the Install from the Command-line tools

image

When I tried to Get-AzureAccount, it displayed more than one account and subscriptions

image

I need to remove the other subscriptions.  Therefore I perform as follow :

image

Execute the command as below :

  • Get-AzureAccount | format-table id

Once displayed, I execute to remove the account using

  • Remove-AzureAccount account-name

Note : Just replace the account-name with the account that needs to be deleted.

Another way is to remove all the accounts then re-add it back. 

To do this execute it as below to remove all the accounts :

  • Get-AzureAccount | ForEach-Object {Remove-AzureAccount $_.ID -Force}

To add the account that I’m working on, use :

  • Add-AzureAccount

 

keys : add azure account, remove azure account in cache, Azure powershell command line, command-line, azure subscription, AzureSubscription, get-azureaccount, remove-azureaccount

Friday, July 31, 2015

Class 20409B - Server Virtualization with Windows Server Hyper-V and System Center

 

Just finished conducting a 5-days class on Server Virtualization using Hyper-V and System Center.  During class, I shared real life scenarios on how it was implemented, what are the obstacles they will face if planning were not done properly in the first place before rolling out.

Feeling happy that the students went back with knowledge.

keywords : 20409, Hyper-V, virtualization, backup, protection, VMM, virtual machine manager, dpm, azure, cloud, vmmlibrary,

Monday, January 19, 2015

PowerShell to Retrieve OS Image family from Azure

Azure is an ever changing.  At times I have PowerShell that provision certain image from the Azure Library, but the naming of the image keeps changing.

Once the Azure account is established to the local server PowerShell, I would use the script below to retrieve example all Windows 2012 family in Azure.

$osimage = (Get-AzureVMImage | where {$_.ImageFamily -like "Windows Server 2012 *"} | sort PublishedDate -Descending)[0].ImageName

Once that’s done, I’ll just display by key in

$osimage

End result looks like this :

image

Thank you and hopes this helps.

keynote : OS Deployment from Azure, OS Image, osimage from Azure, Azure, Windows 2012 from Azure, Image from Azure

Wednesday, December 17, 2014

How to Write into Event Viewer (using PowerShell)

I’m into a situation that I want to write the activity that was carried out into the Event Viewer (say the Application).

I’ve a PowerShell script but has incorporated the following in the beginning and the end of the script.

First I need to register the event into the server’s event viewer.  I call it as “InFront Maintenance”

In the PowerShell, I only execute once to record it down.

New-EventLog –LogName Application –Source “InFront Maintenance

Once it’s registered, then I incorporated the following into my beginning of my script the activity that I need to carry out. 

Note : If you do not register, the next line you execute to write to event viewer, you’ll definitely hit the error.  This is because the “SOURCE” is not registered.

Write-EventLog –LogName Application –Source “InFront Maintenance” –EntryType Information –EventID 1 –Message “Maintenance Spoke A.

So in the event viewer you’ll be able to see something like this

image

At the end of my script I indicate as follow :

Write-EventLog –LogName Application –Source “InFront Maintenance” –EntryType Information –EventID 1 –Message “End Maintenance Spoke A

In the event viewer you’ll see like this :

image

So to summary it :

To register for the first time the event (just once)

  • New-EventLog –LogName Application –Source “InFront Maintenance

Insert beginning on my PowerShell Script

  • Write-EventLog –LogName Application –Source “InFront Maintenance” –EntryType Information –EventID 1 –Message “Maintenance Spoke A.

Insert at the end of my PowerShell Script

  • Write-EventLog –LogName Application –Source “InFront Maintenance” –EntryType Information –EventID 1 –Message “End Maintenance Spoke A

Just change the Pink for your event, and the Yellow for the General Descriptions.

Thanks to the Scripting Guy Site , Ed Wilson!!

keynote : How to write to Event Viewer with powershell, using powershell to write event,event log, application log event viewer, eventviewer with PowerShell, record activity into event viewer

Monday, April 7, 2014

How to check Disk Space Usage and Free Space Remotely using PowerShell

Scenario :

Two hyper-V Host (clustered) with multiple VMs in it.  I need to check on the disk allocation, disk space usage & disk free space.  With the script below I’m going to share how I did it using PowerShell.  I just run it in one of the Hyper-V Hosts PowerShell.

[Special credit to StackOverflow and BinaryNature.  I’ve made changes to ease the entry of variables]

The credential used in the script must be part of the local administrators group

# ----- Beginning of Script -----

#Define ServerName (Physical/VM) Here

# Change the Variables in PINK and remark out with # if the server or VM is not needed

$PHY1="SVR1"
$PHY2="SVR2"
$AD1="ADVM1"
$APP1="APPVM1"
# $APP2="APPVM2"
$DB1="DBVM1"
$DP1="DPVM1"
$DPM1="DPMVM1"
$DomainUser = "domain\user1"

# Diskfree Module

function Get-DiskFree
{
    [CmdletBinding()]
    param
    (
        [Parameter(Position=0,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [Alias('hostname')]
        [Alias('cn')]
        [string[]]$ComputerName = $env:COMPUTERNAME,
     
        [Parameter(Position=1,
                   Mandatory=$false)]
        [Alias('runas')]
        [System.Management.Automation.Credential()]$Credential =
        [System.Management.Automation.PSCredential]::Empty,
     
        [Parameter(Position=2)]
        [switch]$Format
    )
 
    BEGIN
    {
        function Format-HumanReadable
        {
            param ($size)
            switch ($size)
            {
                {$_ -ge 1PB}{"{0:#.#'P'}" -f ($size / 1PB); break}
                {$_ -ge 1TB}{"{0:#.#'T'}" -f ($size / 1TB); break}
                {$_ -ge 1GB}{"{0:#.#'G'}" -f ($size / 1GB); break}
                {$_ -ge 1MB}{"{0:#.#'M'}" -f ($size / 1MB); break}
                {$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break}
                default {"{0}" -f ($size) + "B"}
            }
        }
     
        $wmiq = 'SELECT * FROM Win32_LogicalDisk WHERE Size != Null AND DriveType >= 2'
    }
 
    PROCESS
    {
        foreach ($computer in $ComputerName)
        {
            try
            {
                if ($computer -eq $env:COMPUTERNAME)
                {
                    $disks = Get-WmiObject -Query $wmiq `
                             -ComputerName $computer -ErrorAction Stop
                }
                else
                {
                    $disks = Get-WmiObject -Query $wmiq `
                             -ComputerName $computer -Credential $Credential `
                             -ErrorAction Stop
                }
             
                if ($Format)
                {
                    # Create array for $disk objects and then populate
                    $diskarray = @()
                    $disks | ForEach-Object { $diskarray += $_ }
                 
                    $diskarray | Select-Object @{n='Name';e={$_.SystemName}},
                        @{n='Vol';e={$_.DeviceID}},
                        @{n='Size';e={Format-HumanReadable $_.Size}},
                        @{n='Used';e={Format-HumanReadable `
                        (($_.Size)-($_.FreeSpace))}},
                        @{n='Avail';e={Format-HumanReadable $_.FreeSpace}},
                        @{n='Use%';e={[int](((($_.Size)-($_.FreeSpace))`
                        /($_.Size) * 100))}},
                        @{n='FS';e={$_.FileSystem}},
                        @{n='Type';e={$_.Description}}
                }
                else
                {
                    foreach ($disk in $disks)
                    {
                        $diskprops = @{'Volume'=$disk.DeviceID;
                                   'Size'=$disk.Size;
                                   'Used'=($disk.Size - $disk.FreeSpace);
                                   'Available'=$disk.FreeSpace;
                                   'FileSystem'=$disk.FileSystem;
                                   'Type'=$disk.Description
                                   'Computer'=$disk.SystemName;}
                 
                        # Create custom PS object and apply type
                        $diskobj = New-Object -TypeName PSObject `
                                   -Property $diskprops
                        $diskobj.PSObject.TypeNames.Insert(0,'BinaryNature.DiskFree')
                 
                        Write-Output $diskobj
                    }
                }
            }
            catch
            {
                # Check for common DCOM errors and display "friendly" output
                switch ($_)
                {
                    { $_.Exception.ErrorCode -eq 0x800706ba } `
                        { $err = 'Unavailable (Host Offline or Firewall)';
                            break; }
                    { $_.CategoryInfo.Reason -eq 'UnauthorizedAccessException' } `
                        { $err = 'Access denied (Check User Permissions)';
                            break; }
                    default { $err = $_.Exception.Message }
                }
                Write-Warning "$computer - $err"
            }
        }
    }
 
    END {}
}


$cred = Get-Credential -Credential $DomainUser
$PHY1, PHY2, $AD, $APP1, $APP2, $DB1, $DP1, $DPM1 | Get-DiskFree -Credential $cred -Format | Format-Table -GroupBy Name -AutoSize


# ----- End of Script -----

Steps

My method was copy the script above (from Beginning to End of the Script)  into a notepad and make changes only to the PINK.  Please include the “ “ quotes as in the scripts. 

(You can also save it as powershell script with ext of PS1 and run. Since this is a one time, I don’t intend to save it as PS1 file)

After making the necessary changes, I copied the text and launch the PowerShell (need to run as Administrator) from one of the Hosts

image

…then I paste into the PowerShell screen and press [Enter]

image

It will display the credential, key in the password :

image

It will display something like below with the (servername or VM name as I’ve hide) :

image

Happy trying  and hope the script helps as it helps me.

keywords : checking free space with powershell, powershell scripts, power shell script, checking space usage remotely, windows 2012 check disk space in VM