MSSQLTips.com - your daily source for SQL Server tips

Google
 
Web mssqltips.com

ESSENTIALS: Home | Tips | Search | Categories | Top 10 | Products | Authors | Blogs | Forums | Webcasts | Advertise | About
Invoke-Nz - Powershell script similar to Nz VBA function - Chad Boyd

MSSQLTips

MSSQLTips.com - your daily source for SQL Server tips
Welcome to MSSQLTips Sign in | Join | Help
in Search

Chad Boyd

MSSQLTips - SQL Server Blog

Invoke-Nz - Powershell script similar to Nz VBA function

I got a few pings about the Restore-SqlDb script requiring the Invoke-Nz script to execute - here it is. Similar functionality to that of the Nz function in VBA - basically pass along 2 values and the function will return the first value if it is present (i.e. non-null), otherwise the second (could also say it's similar to the isnull() tsql function, or a coalesce with only 2 parameters). Sorry I missed this with the original Restore-SqlDb posting.

Invoke-Nz.ps1

Thanks to everyone who reminded me,

Chad Boyd ~~~ This posting is provided "AS IS" with no warranties, and confers no rights. Use of any included script samples are subject to the terms specified at http://www.mssqltips.com/disclaimer.asp and http://www.mssqltips.com/copyright.asp.

-------------------------------- CODE ONLY BELOW --------------------------------

# See the Get-Usage function contents in the begin{} section for usage/comment details
param
(
 $value,
 $nullValue
)
begin {
 function Get-Usage {
@"
 NAME
  Invoke-Nz
 
 SYNOPSIS
  You can use the Nz function to return a specified value when an input value is null/empty/unspecified.
 
 SYNTAX
  Nz <value> <nullValue>
 
 DETAILED DESCRIPTION
  You can use this function to convert a null/empty value to another value and prevent it from propagating
  through an expression. If the value parameter is not present/null, the nullValue value is returned.

  If the value of variant isn't Null, then the Nz function returns the value of variant.

  You can often use the Nz function as an alternative to the IIf function. For example, in the following code,
  two expressions including the IIf function are necessary to return the desired result. The first expression
  including the IIf function is used to check the value of a variable and convert it to zero if it is Null.
 
 PARAMETERS
  -value <any>
   Value to check for null/empty/etc. - if not present, the -nullValue is returned
 
   Required?   True
   Position?   1
   Default value  <required>
   Accept pipeline? True
   Accept wildcards? False
 
  -nullValue <any>
   A Variant that supplies a value to be returned if the variant value argument is not present.
 
   Required?   False
   Position?   2
   Default value  <required>
   Accept pipeline? False
   Accept wildcards? False
 
 INPUT TYPE
  Any,Any
 
 RETURN TYPE
  Either `$value or `$nullValue, depending on if the `$value is present.
 
 NOTES
  Alias created called "Nz"
 
  -------------------------- EXAMPLE 1 --------------------------
   Nz $testObj "this is null"
   
  -------------------------- EXAMPLE 2 --------------------------
   dir *.ps1 | Nz -n "NOFILE"

"@
 } # Get-Usage
 if (($MyInvocation.InvocationName -ne '.' -and $MyInvocation.InvocationName -ne '&') -and
  ($Args[0] -eq "-?" -or $Args[0] -eq "/?" -or $Args[0] -eq "-help" -or $Args[0] -eq "/help")) {
   $showUsage = $true;
   &Get-Usage;
   return;
 }
 if ($MyInvocation.InvocationName -ne '.') { Write-Debug "Invoke-Nz::BEGIN"; }
 $InPipeline = $false;
 
 function Invoke-Nz {
  param
  (
   $value,
   $nullValue
  )
  begin {} # Invoke-Nz::begin
  process {
   # Store meta-data depending on pipeline vs. invoked processing...
   if (($_) -or ($_ -eq 0)) { $InPipeline = $true; }
   
   # If we don't have a $value value, figure it out now
   if (-not $value) {
    if ($_) {
     $value = $_;
    } else {
     # No pipeline input - so, if we are invoked throw an error, otherwise the $Try will be nothing...
     if ($MyInvocation.InvocationName -eq '&') {
      # Invoked, throw an exception
      Throw "The parameter -value is required. [$($MyInvocation.InvocationName)] [$($MyInvocation.MyCommand.Name)] [$_]";
     }    
    }
   }
   # If we have a value, show it if debugging, otherwise show a warning
   if ($value) {
    Write-Debug "Invoke-Nz::Have `$value value of [$value] [$_]";
   } else {
    # Not invoked, show a warning - don't throw an error, as that will stop pipeline processing if we're in the pipe...
    # Write-Warning "Invoke-Nz::No value could be determined for the `$value parameter"
    # NOTE: Traditionally I'd throw this warning, but since the entire purpose for this particular command is to return
    #   a value when a particular value isn't present, kind of makes sense not to do so here...
   }
   
   # Process the test
   if (($value) -or ($value -eq 0)) { $value; } else { $nullValue; }
  } # Invoke-Nz::process
  end {} # Invoke-Nz::end
 }
 if (-not (Get-Alias -Name nz -ErrorAction SilentlyContinue)) {
  Set-Alias -Name nz -Value Invoke-Nz -Description 'Nz function in VBA - if value parameter is not present, nullValue is returned.';
 }
} # Invoke-Nz::begin
process {
 # No processing if we are dot-sourced or if we were just asked for a little help...
 if ($showUsage -or $MyInvocation.InvocationName -eq '.') {
  return;
 }

 # pass processing to the function via pipelining or invoke...
 if (($_) -or ($_ -eq 0)) {
  $InPipeline = $true;
  $_ | Invoke-Nz $value $nullValue;
 } else { # if ($_)
  Invoke-Nz $value $nullValue
 } # if (($_) -or ($_ -eq 0))

} # Invoke-Nz::process
end {
 if ((-not $showUsage) -and ($MyInvocation.InvocationName -ne '.')) { Write-Debug "Invoke-Nz::END"; }
} # Invoke-Nz::end

 

Published Oct 14 2008, 07:33 AM by Chad Boyd
Filed under:
Attachment: Invoke-Nz.ps1

Comments

 

Restore-SqlDb - Automate a Database Restore (improved with Powershell) - Chad Boyd said:

Pingback from  Restore-SqlDb - Automate a Database Restore (improved with Powershell) - Chad Boyd

October 14, 2008 7:42 AM

About Chad Boyd

Chad is an Architect, Administrator, and Developer with technologies such as Sql Server (and all related technologies), Windows Server, and Windows Clustering. He currently works as an independent consultant and also spends a significant amount of time writing, talking, presenting and blogging about Sql Server in person and online at http://mssqltips.com. In the past, Chad has worked with companies and organizations such as Microsoft Corporation and The American Red Cross, and provided consulting/support services at companies such as Bank of America, HP, Citigroup, Qualcomm, Scottrade, TJX, SunTrust, and Zurich Financial Services. For over 3 years with Microsoft Corporation Chad was responsible for providing onsite and remote support, guidance, and advice with SQL Server products to some of Microsoft’s foremost enterprise customers running the largest, most complex SQL Server installations and configurations in the world. This included all SQL Server products and versions, including SQL Server 7.0, 2000, 2005, and recently 2008, the SQL Server database engine, Reporting Services, SSIS/DTS, Notification Services, and Analysis Services on both 32 and 64 bit systems. Chad's primary responsibilities today include troubleshooting critical server situations, performance tuning and monitoring, disaster recovery planning and execution, architectural guidance for new Sql Server related deployments, and delivering deep technical workshops/presentations/proof-of-concept sessions covering a variety of technologies and functionality. Chad regularly posts Sql Server related content, tools, and advice with the mssqltips team at http://blogs.mssqltips.com/blogs and http://mssqltips.com. Chad can be contacted via his blog or email at chad dot boyd dot tips at gmail dot com.

This Blog

Syndication