PowerShell – executing SQL query – resolving issue – column not returning all characters

Hi All,

Greetings

Today new issue and solution

Background

  • I am working on PowerShell script in which I am querying to SQL server
  • I am getting the result
  • Yet one of the SQL column of type “Text” is not returning all the characters.
  • Return string value is truncated
  • The column includes the big HTML string which I read and create a page in SharePoint
  • I am using “Invoke-Sqlcmd” PowerShell CMDLET to query SQL server from PowerShell


PS C:\> $SiteURL = "https://knowledgejunction1.sharepoint.com/sites/prashamdemo/"
PS C:\> $ClientID = "my client app id"
PS C:\> Connect-PnPOnline -Url $SiteURL -Interactive -WarningAction Ignore -ClientId $ClientID -Force
PS C:\> $sqllink = Invoke-Sqlcmd -Query "SELECT * FROM dbo.mytable" -ServerInstance "myserver" -TrustServerCertificate
PS C:\> $sqllink.body

Value of "$sqllink.body" is returning the string but not complete value. It cut through.

Solution

  • After a bit of research, I found that the Invoke-Sqlcmd cmdlet has a default maximum character length. This length is 4000 for character columns. This limit causes truncation for longer strings.
  • We can override this with the -MaxCharLength parameter
PS C:\> $sqllink = Invoke-Sqlcmd -Query "SELECT * FROM dbo.mytable" -ServerInstance "myserver" -MaxCharLength ([int]::MaxValue) -TrustServerCertificate

  • As we used “-MaxCharLength ([int]::MaxValue)” parameter to our CMDLET, column returned the complete string without truncating

References

Thanks for reading!!! Please feel free to discuss in case any questions / suggestions / thoughts !!!

HAVE A GREAT TIME AHEAD !!! LIFE IS BEAUTIFUL 🙂

Prasham Sabadra

LIFE IS VERY BEAUTIFUL. ENJOY THE WHOLE JOURNEY :) Founder of Microsoft 365 Junction, Speaker, Author, Learner, Developer, Passionate Techie. Certified Professional Workshop Facilitator / Public Speaker. Believe in knowledge sharing. Around 20+ years of total IT experience and 17+ years of experience in SharePoint and Microsoft 365 services Please feel free me to contact for any SharePoint / Microsoft 365 queries. I am also very much interested in behavioral (life changing) sessions like motivational speeches, Success, Goal Setting, About Life, How to live Life etc. My book - Microsoft 365 Power Shell hand book for Administrators and Beginners and 100 Power Shell Interview Questions - https://www.amazon.in/Microsoft-Administrators-Beginners-Interview-Questions/dp/9394901639/ref=tmm_pap_swatch_0?_encoding=UTF8&qid=1679029081&sr=8-11

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.