Search This Blog and Web

Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Tuesday, September 27, 2016

Try Power Shell commands on a web-page!

There's a #PowerShell container available for which I saw a tweet about. Time to try in my blog :



Go-Ahead. Play it, let connect and load and  then type the commands in "Input" and press enter.

Example : gps, dir env:, whoami

Source : http://www.learnondemandsystems.com/powershell-containers-blogs/ 

Monday, October 12, 2015

What's in my Power Shell profile ?

Ed Wilson aka "The Scripting Guy" from Microsoft ran a series of posts in which he wrote about what different users have in their profiles. I was also one of those who replied to that email and he kindly did mention me in his blog.
http://blogs.technet.com/b/heyscriptingguy/archive/2014/05/21/what-39-s-in-your-powershell-profile-users-39-favorites-part-2.aspx

Today, I want to share what's in my profile. I've customized it a bit more since then.
Here' what it has :
  • Change Error color to Gray from default red. It stresses me to see RED RED on the prompt.
  • Changing the location to my scripts folder to :  Easily call my common scripts, Prevent accidental changes to system32 folder.
  • Checking if I've launched Power Shell as an Admin or not.
  • Customizing in-built PROMPT function to show ADMIN/DBG mode and increment command number after each command run.


Want to know what Power Shell MVP's have ? See here.

If you don't know about profile, in simple terms I'll try to explain.
It's an auto-loading PS1 file which runs each time Power Shell starts. Whatever is written in it is executed and then you can see prompt. the environment variable $Profile tells you the path of the file.

To bypass loading profile, powershell.exe has a parameter called -NoProfile. It's a best practice to use this. If an attacker has control of your system, he can change PROFILE and run arbitrary code. Also, your code may behave differently if someone has changed some functions in it.

Wednesday, August 19, 2015

Backup-SQLDatabase, Restore-SQLDatabase and other SQLPS cmdlets issue after an upgrade of SQL Server

If you are using some cmdlets of SQLPS module and you have done an upgrade from SQL Server 2012 to SQL Server 2014, you're likely to face many unfriendly error messages like this one below :

ERROR
"Cannot bind parameter 'RelocateFile'. Cannot convert the "Microsoft.SqlServer.Management.Smo.RelocateFile" value of type "Microsoft.SqlServer.Management.Smo.RelocateFile" to type "Microsoft.SqlServer.Management.Smo.RelocateFile"."

This one comes in Restore-SQLDatabase cmdlet but there can be issues in other cmdlets also which some in SQLPS module.
You're most likely to reach this question after search.
http://stackoverflow.com/questions/26377356/problems-with-relocatefile-property-in-the-restore-sqldatabase-cmdlet

The useful answer given there is to use correct assembly version.

$RelocateData = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' -ArgumentList "MyDB_Data", "c:\data\MySQLServerMyDB.mdf"
$RelocateLog = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' -ArgumentList "MyDB_Log", "c:\data\MySQLServerMyDB.ldf"

I did do that initially but then thought of a better version which I'm sharing here.

PROBLEM
So, let's understand the problem here first :
* After upgrade there are two versions of SQLPS module present in the system. One to them is of SQL Server 2012(110) and other is of SQL Server 2014(120). Use Get-Module -ListAvailable to check.


* When we run the command "Import-Module SQLPS", it loads both of them. Check using command :

# Get loaded assemblies
([appdomain]::CurrentDomain.GetAssemblies() | where {$_.FullName -like "*smo*"}).Location


So, the cmdlets like Backup-SQLdatabase get bound to SQL 2012 version(110).

* When we create a new object of SMO like one below, it gets bound to SQL Server 2014 version unless we specify Version as given in answer above.
$RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile($LogicalMDFName, "$TargetServerMDFFile")
* After that when we run commands like Restore-SQLdatabase and pass -RelocateData parameter, we get the above error.

SOLUTION

Basically, we need to make sure that only one of the assemblies get used. It can be either of SQL Server 2012 or SQL Server 2014.

The trick lies in changing the environment variable $env:PSModulePath.
We need to remove one version. We can either make these changes in our session or permanently by modifying Profile file.

* Close existing session if you already have imported both modules.

$TempArray = @()
$TempArray = $env:PSModulePath -split ';'
# 110 for SQL 2012, 120 for SQL 2014, 130 for SQL 2016
$env:PSModulePath = ($TempArray -notmatch '110') -join ';'  
Now, check again available modules :

Only one should show up.
Now, load SQLPS module and run commands.
They'll run fine. Cheers.

Tuesday, March 17, 2015

My biggest contribution yet (System Inventory using Power Shell)

I wrote this tool a few years back but forgot to share. I took one script from here and optimised it using remoting features of Windows Power Shell.

You can download script from Technet.
https://gallery.technet.microsoft.com/System-Inventory-using-dcdab843

The following information is gathered :
  • Computer Information like RAM, OS, Processor (with Pie-Chart)
  • Top 10 Running Processes
  • List of Shared Folders
  • Disk-Info showing disks having Low Disk space (less than 20%,configurable)
  • List of Services that are Automatic but Stopped.
Please let me know your comments.

Tuesday, November 11, 2014

[Script] RPC Port Allocation using Power Shell

Remote Procedure Call (RPC) dynamic port allocation is used by server applications and remote administration applications such as Dynamic Host Configuration Protocol (DHCP) Manager, Windows Internet Name Service (WINS) Manager, and so on.

Basically, the automation of this article. 
https://support.microsoft.com/kb/154596?wa=wsignin1.0

I've added this at Script Center.
Please download at https://gallery.technet.microsoft.com/scriptcenter/RPC-Port-Allocation-using-7f1c52c1.

Tuesday, October 21, 2014

[Script] Get Disk Space using PowerShell

I posted a simple script at Technet which returns the free space of a specific drive on any computer.

Take a look here : https://gallery.technet.microsoft.com/scriptcenter/Get-Disk-Space-using-69c88b59

Basic Code :

Write-Host "Getting Information for Drive : $DriveID for Computer : $CompName" 
 
# Get Info about the disk specified 
$Disk = Get-WMIObject Win32_LogicalDisk -ComputerName $CompName -Filter "DeviceID='$DriveID'"  
 
 
$FreeSpace = [System.Math]::Round((($Disk.FreeSpace) / 1GB)) 
Write-Host "Drive $DriveID has freespace : $FreeSpace GB"

The script can be improved using PS-Remoting for better performance.

Thursday, April 10, 2014

[TOOL] SQL Service Account password change/update (multiple servers)

Today, I'm going to share a tool that I've developed for changing password of SQL service account on (n) servers.

Background : Typically in an organisation as a best-practice account password is changed every 90 days(to prevent brute-force attack's success). Many Windows services are run using these accounts. Hence, there password needs to be updated.

Manual Way : Take a remote desktop connection to the server, open services.msc, select service and update password in Logon tab.


serviceaccount6
Src : http://www.sqlservercentral.com/blogs/steve_jones/2011/12/15/how-to-change-the-sql-server-service-cccount/
This is fine for 1 or 2 servers but this process does not scale-up in an enterprise where there are many servers and also many services are being run on each server(like sqlserveragent,ssis,ssas,ssrs).

Automation : As always, Power Shell is there to the rescue. There are two methods to achieve that 1. SMO 2. WMI
I first tried using SMO but it broke at crucial point. (Avoid SMO as far as you can.)
So, the second option with me was WMI.
Basically, all SQL services are Windows services and can be managed using Win32_Service class.

Basic Code :$service = gwmi win32_service -computer [computername] -filter "name='whatever'"
$service.change($null,$null,$null,$null,$null,$null,$null,"P@ssw0rd")
Full Code :

# Script should be run on systems having PowerShell V3 installed.
# Run PowerShell as ADMINISTRATOR.
# Remoting must be enabled on destination servers using "Enable-PSRemoting -Force"
# In case of errors, please try running this command on local machine : gwmi win32_bios -comp "server1" where "server1" is the machine for which you get error. This should run fine for utility to proceed.

<#
.SYNOPSIS
    Service Account Password Change
.DESCRIPTION
    Power Shell utility to change password of SQL service account on (n) servers
.PARAMETER Path
    $servers : List of Server(s) separated by comma
    $AccountName : Name of the account through which service is running and whose password needs to be changed
.EXAMPLE
    cd "E:\Utilities\ServiceAccount";
    .\SQLServiceAccount.ps1 -Servers "s1","s2" -accountName "redmond\v-any"
.NOTES
    Author: r1111111r@gmail.com
    Date : 15/01/2014
    Version : 1.0
    You must be having access to the servers.
    This should be run only from systems having PowerShell V3. Destination servers may have V2/V3.
.INPUTS
    List of servers and account name
    Then password when prompted
.OUTPUTS
    On Screen and file-logging.
    It logs into the directory from which it's invoked/called.
#>

param(
    [cmdletBinding()]
    # Seprate list by commas eg. "ser1","ser2"
    [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]
    [string[]] $servers,
    # eg. "domain\account"
    [Parameter(Mandatory=$true)] [ValidatePattern("(\w+)\\(\w+)")]
    [string] $accountName
    )

# Bail-out in case of any error
$ErrorActionPreference = "Stop"

# Generic helper function
function ConvertTo-ScriptBlock
(
    [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
    [string] $ScriptString
)
{
    $ScriptBlock = $ExecutionContext.InvokeCommand.NewScriptBlock($ScriptString)
    Return $ScriptBlock
}

function Get-ScriptDirectory
{
    # Look up this script file's path
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    Split-Path $Invocation.MyCommand.Path
}

# This function writes the input Msg into the console window
function Log
(
    [string] $Msg = $(throw "Msg parameter not specified!")
    # Define the foreground color in which to log; if not specified, default provided
   ,[string] $Fore = "cyan"
)
{
    Write-Host (Get-Date -format "yyyy-MM-dd hh:mm:ss") $Msg `n`r -fore $Fore
}

Log "Account specified is $accountName"
# Get password from the user and store it as  a "Secure String"
# UserName, Message parameters are available only in V3
$pass = (Get-Credential -UserName $accountName -Message "Enter password for account")
If($pass -eq $null) {Log "Password not specified"; throw}

# get alias name from domain\alias e.g. domain\alias will return alias
$account = ($accountName.Split("\")[1])

$path = (Get-ScriptDirectory)
if(!(Test-Path $path)) {Log "Invalid log path $path" -Fore Red ; throw}

# Checks whether Transcript is in progress
function Test-Transcribing {
    $externalHost = $host.gettype().getproperty("ExternalHost",
        [reflection.bindingflags]"NonPublic,Instance").getvalue($host, @())

    try {
        $externalHost.gettype().getproperty("IsTranscribing",
    [reflection.bindingflags]"NonPublic,Instance").getvalue($externalHost, @())
    } catch {
             Write-Warning "This host does not support transcription."
         }
}

# The function that stops services (including dependent services), changes password & starts them again
function Change-ServiceAccount()
{
    # This is the code to fetch the services for SQL server including SSIS, OLAP
    $services = Get-WmiObject -Class win32_service -Filter "DisplayName LIKE '%SQL%'"
    Write-Host "Total SQL services are : " ($services.Count)`n`r
    
    foreach($service in $services)
    {
        Write-Host "Processing service : " $service.Name`n`r

        # Need services that are run by the account specified
        if($service.StartName -match "$account")
        {
        $serviceName = $service.Name
        Write-Host "Service is running under : " $service.StartName`n`r -ForegroundColor Yellow
                
        Log "Stopping service : $serviceName"
        # Stop All services so that "Dependent Services" are not running
        # It's better and simpler than $service.Stop() as the later does not stop dependent services by default

        Get-Service -Name $serviceName | Stop-Service -Force -Verbose

        Log "Changing password for $serviceName"

        # uint32 Change(DisplayName,PathName,ServiceType,ErrorControl,StartMode,DesktopInteract,StartName,StartPassword,LoadOrderGroup,LoadOrderGroupDependencies,ServiceDependencies);
        $RetCode = $service.Change($null,$null,$null,$null,$null,$null,$null,$pass)

        # Get error message from return code
        $msg = RetCodes -Code ($RetCode.ReturnValue)
        if($RetCode.ReturnValue -ne 0) { throw "Error : $msg" }

        Start-Sleep 2
        Log "Starting service : $serviceName"

        $RetCode = $service.StartService()

        $msg = RetCodes -Code ($RetCode.ReturnValue)
        if($RetCode.ReturnValue -ne 0) { throw "Error : $msg" }
       
        }
        else
        {
            Write-Host "Skipping Service : " $service.Name `n`r -ForegroundColor White
        }
   }
}

# These are the list of return codes of Change() function which changes password
function RetCodes ([int] $Code)
{
    switch ($Code)
    {
        0 { "Success" }
        1 { "Not Supported" }
        2 { "Access Denied"}
        3 { "Dependent Services Running"}
        4 { "Invalid Service Control"}
        5 { "Service Cannot Accept Control"}
        6 { "Service Not Active"}
        7 { "Service Request Timeout"}
        8 { "Unknown Failure"}
        9 { "Path Not Found"}
        10 { "Service Already Running"}
        11 { "Service Database Locked"}
        12 { "Service Dependency Deleted"}
        13 { "Service Dependency Failure"}
        14 { "Service Disabled"}
        15 { "Service Logon Failure"}
        16 { "Service Marked For Deletion"}
        17 { "Service No Thread"}
        18 { "Status Circular Dependency"}
        19 { "Status Duplicate Name"}
        20 { "Status Invalid Name"}
        21 { "Status Invalid Parameter"}
        22 { "Status Invalid Service Account"}
        23 { "Status Service Exists"}
        24 { "Service Already Paused"}
        default {"Invalid return code"}
    }
}

# Make function calls from here
try
{
    # Read local function
   $RetFunction = (Get-Content Function:\RetCodes)
   $RetFunction = "Function RetCodes {" + $RetFunction + "}"
   $RetScriptBlock = (ConvertTo-ScriptBlock -ScriptString $RetFunction)

   $LogFunction = (Get-Content Function:\Log)
   $LogFunction = "Function Log {" + $LogFunction + "}"
   $LogScriptBlock = (ConvertTo-ScriptBlock -ScriptString $LogFunction)

    #Create log file to store execution result
    $StartTime = Get-Date -Format "yyyyMMdd_hhmm"
    $logFile = "$path\ServiceAccount_$StartTime.log"
    Start-Transcript $logFile

 foreach( $server in $servers)
   {
   # Check Server is valid and alive
   Log "Testing Connection to $server"

   If(Test-Connection -ComputerName $server -Quiet)
   {
        Log "Creating Connection to $server"
        $session = New-PSSession -ComputerName $server

        If($session.State -eq "Opened") { Log "Successfully connected to : $server"  -Fore "Yellow"}
    
        # Create function RetCodes in remote session
        Invoke-Command -Session $session -ScriptBlock $RetScriptBlock

        # Create function Log in remote session
        Invoke-Command -Session $session -ScriptBlock $LogScriptBlock

        # Pass local variable to remote session
        Invoke-Command -Session $session -ScriptBlock {param($account)} -ArgumentList $account
        Invoke-Command -Session $session -ScriptBlock {param($pass)} -ArgumentList $pass.GetNetworkCredential().Password

        # Call local function in remote session
        Invoke-Command -Session $session -ScriptBlock ${function:Change-ServiceAccount}
    }
    else
    {
        Log "Server : $server is not valid/available, skipping it" -Fore "Red"
    }
   }

}

catch 
    Write-Host "oops! " $Error[0] `n`r -ForegroundColor Red
    Write-Host "Please check `"http://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx`" for error details"
    #Start-Process "http://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx" -ErrorAction SilentlyContinue
}

finally
{
    Log "Clearing Sessions" -Fore "Yellow"
    Get-PSSession | Remove-PSSession
    if(Test-Transcribing) { Stop-Transcript }
}

Important Points : The above script is optimized using remoting and is amazingly fast. If you need a quick short version, only read and use Change-ServiceAccount function.

At the end, thanks to the all the people whose information I've used in creating this utility. Please let me know your comments on this.

Wednesday, October 23, 2013

Timeout problem in Backup-SQLDatabase cmdlet in SQLPS module

Power Shell is for managing all types of technologies be it SQL, EXchange, Lync, Office etc.( just name it)

These technologies usually create there own cmdlets, and then bundle into a "Module" for distribution.
SQL team initially followed different approach by creating mini-shell "sqlps.exe" but it was not well accepted.
Now, they give there cmdlets in  SQLPS module.

"Import-Module SQLPS" command loads this module.

There are multiple cmdlets available for multiple tasks like querying, backup/restore, security management, policy management etc. . Two cmdlets for taking backup/restore are :

  • Backup-SQLDatabase
  • Restore-SQLDatabase
These two use SMO(Server Management Objects) classes underneath and then run T-SQL commands.
Backup-SqlDatabase  is a wrapper over SMO object model (managed code); SMO constructs T-SQL code and executes query using ADO.NET.
SMO classes have been available for a long time, and are widely used in automation.
There are different ways to perform backup/restore operations as specified here.

If we use Power Shell to do automation of this activity ( which we should ), we can use the most simple cmdlets to use aka Backup-SQLDatabase and Restore-SQLDatabase.

However, both these have one serious bug i.e. if a backup or restore takes more than 10 minutes, they time-out and fail.
Usually, backup/restore of large databases take more than 10 minutes to complete (which is why we wanted to automate this).

Here's the error you will see if you run this command :
Backup-SqlDatabase -ServerInstance $Server -Database $DatabaseName -BackupFile $BackUpFile -CompressionOption On -ConnectionTimeout 0 -Initialize -Verbose -ea Stop

Here’s the error exactly after 600 seconds of execution :
VERBOSE: 60 percent processed.
VERBOSE: The backup or restore was aborted.
The wait operation timed out
    + CategoryInfo          : InvalidOperation: (:) [Backup-SqlDatabase], Win3
   2Exception
    + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.P
   owerShell.BackupSqlDatabaseCommand
    + PSComputerName        : localhost 

This is a very weird issue.
You can try re configuring “remote query timeout” to 0 as given here, but the issue persists.
ConnectionTimeout switch is different than StatementTimeout. This switch is not available in these cmdlets.

The workaround lies in setting this property by connecting to SMO server.

$serverConn = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $server
$serverConn.ConnectionContext.StatementTimeout =

So, I have to pass SMO.Server object to this cmdlet.
Backup-SqlDatabase -InputObject $serverConn -Database abc -BackupFile "L:\123\abc.bak" 

This will run fine for command that take longer than 600 seconds.( Default value of StatementTimeout is 600, which caused the issue).

To tell Microsoft about this, I've logged a bug in their "Connect" program.

Please vote-up.

PS: If Power Shell is giving you some issues, don't worry. Invest time in learning and sharing. Overall, your time will be saved.

Tip : I came around this workaround after using the best cmdlets of Power Shell : Get-Help, Get-Member.
These are your base including Get-Command.

Cheers!

Wednesday, October 16, 2013

Why this blog ?

“It is every man's obligation to put back into the world at least the equivalent of what he takes out of it.” - Albert Einstein


There are two purposes of starting this one :
  • Spread Knowledge
  • Personal Diary

Spread Knowledge

Every day in day out, you Google about something that you need and hopefully find what you need. In thanks to them, I'm also sharing my experiences. I want to share what I know so that it may save someone's time. And, the other benefit of sharing is the more you tell the more you get to know.

Personal Diary

I started with PS from Jan 2013 (had some fun admiring it from July 2012), did learn many things, worked and then forgot! Since, I had to work on some other technologies as needed. But, PS lived in my heart. After some gap, I wanted to refresh. I did not have any notes. So, here I am preparing my notes. Maybe later they will prove beneficial to me.

Let's start sharing! 

Featured Post

Timeout problem in Backup-SQLDatabase cmdlet in SQLPS module

Power Shell is for managing all types of technologies be it SQL, EXchange, Lync, Office etc.( just name it ) These technologies usually cr...