31 May 2024

PowerShell Interview Questions for SQL Server DBAs

 

Problem

With PowerShell playing a more important role in administration of various types of servers, more SQL Server DBA candidates should have PowerShell knowledge and skills. But I still do not see many good PowerShell interview questions targeting DBA candidates, can you provide some questions?

Solution

PowerShell (PS) is rich and deep in content itself, and it is almost impossible to come up with a comprehensive question list to check a candidate's knowledge on every aspect of PS. But in the context of DBA work, we may come up with some good questions to test a DBA's PowerShell knowledge.

I personally do not like to ask questions where the answer can be memorized, such as "what is a PowerShell cmdlet?", "What is an advanced PowerShell function?", etc. Instead, I'd prefer to ask "hands-on" questions such as "Write me a function to display disk size and its free space", "write me a script to read the SQL Server error log and report any entries with words like 'Error xxx occurred'"?, etc.

The questions listed below are designed with two simple rules:

  • Questions should be related to common SQL Server DBA tasks and are simple to complete in a few lines of PS code
  • No Books Online (BOL) is needed as you are expected to find the necessary information via PS self-exploring capability, i.e. get-member

There is one requirement though, the answers should not use T-SQL, such as in this way, invoke-sqlcmd -query "t-sql-code".

Assume SQLPS module (in SQL Server 2012+) is installed and also assume all operations are on a local server. This way, we can prepare a stand-alone test environment on a laptop for the candidate. No network, internet or Googling needed.

  1. Determine if the SQL Server service or SQL Server Agent service is running
  2. Start / stop a SQL Server service
  3. Find the SQL Server version / edition including the service pack level
  4. Find the SQL Server operating system information such as the OS version, processor number, physical memory, etc.
  5. Find the largest SQL Server database by size
  6. Find any SQL Server databases in full recovery without a transaction log backup in the past 3 hours
  7. Find the largest (by size or rows) 3 tables in the AdventureWorks2012 database
  8. Delete the SQL Server backup files in the D:\Backup folder if the file is older than 7 days
  9. Find any orphaned SQL Server database users (i.e. db users without logins)
  10. Script out a SQL Server Agent Job, based on a specific category
  11. Find all SQL Server Agent Jobs that failed during the last execution
  12. Kill all sessions connected to a SQL Server database

Answers to PowerShell Interview Questions for SQL Server DBA

Note: each answer is just one of many possible ways to address the question, and you may come up with better answers than the provided ones.

We need to load PowerShell 3.0 with the SQLPS module.  Here is the code:

#require -version 3.0
#we first need to import SQLPS module
Push-Location
import-module SQLPS -DisableNameChecking;
Pop-Location
$svr=get-item SQLServer:\SQL\<your server>\default # <your server>\default means the default sql instance on <your server>, 
                                              # replace <default> with <instance name> if you are interested in a named instance.

 

  1. Determine if the SQL Server service or SQL Server Agent service is running
get-wmiobject -class win32_service -filter "displayname like 'sql server%'" | select name, displayname, state
# or
get-service -name "*sql*" | select name, displayname, status
  1. Start / stop a SQL Server service
Stop-Service -Name MSSQLSERVER -Force; #note -name parameter value is case-sensitive.
Start-Service -name MSSQLSERVER;
  1. Find the SQL Server version / edition including the service pack level
$svr | select version, edition, productlevel;
  1. Find the SQL Server operating system information such as the OS version, processor number, physical memory, etc.
$svr | select OSVersion, Processors, PhysicalMemory;
  1. Find the largest SQL Server database by size
$svr.databases | select name, size | Sort-Object -Property size -Descending | Select-Object -First 1;
  1. Find any SQL Server databases in full recovery without a transaction log backup in the past 3 hours
$svr.databases | ?{ $_.RecoveryModel -eq 'Full' -and $_.lastlogbackupdate -lt (get-date).AddHours(-2)} | select name, lastbackupdate, lastlogbackupdate
  1. Find the largest (by rows or size) 3 tables in the AdventureWorks2012 database
# Size by row count
$svr.databases['AdventureWorks2012'].tables | select name, rowcount | Sort-Object -Property RowCount -desc | select -First 3



# Size by table storage
$svr.databases['AdventureWorks2012'].tables | select schema, name, @{name='size'; e={$_.dataspaceused+$_.indexspaceused }} | 
Sort-Object -Property size -desc | select -First 3;
  1. Delete the SQL Server backup files in the D:\Backup folder if the file is older than 7 days
dir d:\backup\*.bak -Recurse | where creationtime -lt (get-date).AddDays(-7) | Remove-Item -Force;
  1. Find any orphaned SQL Server database users (i.e. db users without logins)
$svr.databases | % {$_.users | ? {$_.issystemObject -eq $false -and $_.login -eq ''} | select parent, name, login }
  1. Script out a SQL Server Agent Job, based on a specific category
$svr.JobServer.jobs | where Category -eq 'DBA Admin' | % {$_.script()} | Out-File -path c:\temp\DBA_Admin_Jobs.sql -force;
  1. Find all SQL Server Agent Jobs that failed during the last execution
$svr.JobServer.jobs | where lastRunOutcome -eq 'failed' | select name, lastrundate, lastrunoutcome
  1. Kill all sessions connected to a SQL Server database
$svr.EnumProcesses() | ? { $_.IsSystem -eq $false -and $_.database -eq 'AdventureWorks2012'} | % {$svr.KillProcess($_.spid)}

Summary

In this tip, I listed some common SQL Server DBA tasks that may be completed easier with PS than T-SQL. Most answers rely on SMO. Using these questions as an example, you can come up with your own PS+SMO questions, such as doing backup/restore processes, checking user/object permissions, index fragmentation or more complex ones like Replication, High Availability management, etc.

One thing we need to bear in mind based on my experience is that in an unprepared "hands-on" test, the majority of candidates will perform probably only at 70% (or lower) of their normal capacity. So it is unfair to design some complex questions (like you need to solve with 50+ lines of code) and expect a sound solution within a short time.

I consider PS as an administration automation tool/platform, and I believe in the near future, with PS, we DBAs will be able to create a software-defined database administration framework, in which we will customize our administration according to business requirements, but with our personal styles and flavors. With Microsoft starting to switch their product management from GUI based to a Unix-like command line interface (CLI), the line between traditional DBAs and developers will be blurred, and programming skills will be more important to SQL Server DBAs.

SQL Server Career Planning

 

Problem

I am looking for career advice.  I would like to know how to get started with my career and plan for changes over time.  Do you have any suggestions for building my career?  Check out this tip for some valuable career advice for new and experienced SQL Server Professionals.

In many respects starting and growing your SQL Server career have a number of the same considerations.  At any point in your career, you need to know the following:
  • What are you looking for in your SQL Server Career?
  • Starting Your SQL Server Career
  • Growing Your SQL Server Career
  • SQL Server Interview Recommendations

What are you looking for in your SQL Server Career?

Knowing what you want in your career is just as important as what you do not want.  Often times, many professionals really do not know what they do and do not want.  In my opinion, it is important to take some time for a self assessment and ask yourself what you want and do not want in your job. As a point of reference, here is a basic list of items I have heard from SQL Server Professionals:

  • Challenging technical problems to resolve
  • Listened to by management and the recommendations provided are respected and acted upon
  • Job security and stable work environment to not have to worry about whether you will have a job next week or not
  • Salary and benefits that are commensurate with the job responsibilities and experience
  • Flexible schedule and the ability to take vacations without having to respond to emails and phone calls
  • Less politics and ability to focus on technology
  • Low stress with reasonable deadlines
  • Educational benefits and paid training
  • Ability to work on the latest and greatest technology
  • New and exciting opportunities rather than a routine schedule

Are these the same items you are looking for in your career?  Are there others?  If so, please share your thoughts as a comment for this tip.


Starting Your SQL Server Career

When you are starting your career you need to make the decision to work in the technology field and figure out a few different jobs you would like to try.  Talk with everyone you know to get an understanding of what they do, how they do it, what they like, what they dislike, how to get started, etc.  They might even be able to point you in the right direction to get your first job.  Starting off you need to get your first opportunity and use it as a stepping stone for trying a few different types of jobs.  Most people with years of experience do not know what they want to do, so figuring out exactly what you want to do when you start off is challenging.

As you start your career you need to set some goals for yourself.  Be sure to record your goals and revisit them on a quarterly, semi-annual or annual basis.  As best as possible, try to quantify your goals and setup a time frame i.e. 1, 3, 5, etc. years.  Items to consider as you build your goals:

  • Education
    • Are you learning something new every day?
    • Do you have a test environment setup for you to learn and test items you have learned?
    • Is your employer encouraging you to work towards certifications, degrees, etc.?
  • Career
    • Do you have the opportunity to grow? 
    • Has your manager established a path for you at the company?
    • Are you working with the latest and greatest technologies?
    • Do you enjoy what you are doing?
    • Can you see yourself growing in your career and advancing in future years?
    • Do you want to try other technologies?
  • Family
    • What are the implications on your family?
    • Is there a separation between work and family?
  • Financial
    • Are you being paid a competitive salary and offered valuable benefits?

Growing Your SQL Server Career

As you progress in your career, some of the items you worked through when you started your career are still applicable, but you also need to include additional items such as:

  • Self Assessment
    • Determine your "comfort zone".
      • Whether this is development, operations, BI, etc., you need to know what you do well and why that is the case.  You also need to think about items such as your comfort in working with one portion of SQL Server or the entire stack.  Also think about your comfort level working on a team versus independently.  Do you have experience working in both scenarios?  Do you have a preference?
    • Determine areas of improvement.
    • Determine professional interests.
  • Educational Plan
    • Determine your opportunities to learn from your employer and your personal resources.
    • Grow your test environment to be able to test and learn.
    • Review online options to learn as well as local events such as user groups, SQL Saturdays, Code Camps, etc.
    • Build a plan to learn each new edition of SQL Server.
  • Network
    • Be sure to make a concerted effort to build your online and offline network.  If you run into an issue, make sure they will be your life line.
  • Goals
    • Review your goals to determine the items you have accomplished, what has changed and what you still need to accomplish.
    • Revise goals that have changed, remove goals that are no longer applicable and create new goals that align with your current interests.
    • Be sure to look forward in order to stay on top of technology changes.

SQL Server Interview Recommendations

As you begin your interview process, be sure you understand the process.  Ask questions to understand how the recruiter, manager, etc. works through the interview process at the company.  Traditionally speaking, the interview process is something like:

  • Find job that you are interested in and you meet the qualifications
  • Based on the needs, update your resume to best match the requirements
  • Contact the company\recruiter\hiring manager and send them your resume
  • If selected for the initial round of interviews, prepare for the phone interview which could be with the recruiter or hiring manager
    • This could be one or more rounds of interviews depending on the organization
  • If selected for the next round of interviews, prepare for an onsite interview with the team
    • This could include a peer interview to determine if you would be a good fit for the team
    • This could include a technical interview to determine your technical skills
  • Depending on the organization, a decision may be reached or there may be multiple onsite interviews\meetings with the team
  • Generally, the last step in the process if the employer is interested in your skills is to issue a background check and/or check your references

Over the years, I have seen this process change dramatically.  I have seen a much less rigid process in some organizations with entire interviews held over lunch while others are administering technical and aptitude tests.  I have also seen a much heavier reliance on learning about companies and potential employers based on information found online and networking web sites.  In some circumstances, Google performs your background checks for you.  These are just short term and long term considerations as you prepare for an interview.

As you prepare for the your interview be sure you know the following:

  • Understand the employer's needs.
  • Who will be involved in the interview and their role.
  • Where the interview will be held.
  • Everything about the company that you can find out.
  • Your commute time.
  • Travel requirements.
  • Work schedule including off hours work.
  • Your "sales pitch" to let the employer know why you can uniquely benefit them.

Union Budget 2024-25 – All You Need to Know

  Union Budget 2024-25 – All You Need to Know The Union Budget is a yearly financial plan presented by the Finance Minister of India for the...