it:ad:powershell:howto:snippets:work_with_strings

IT:AD:PowerShell:HowTo:Snippets:work with strings

Strings have .NET Properties

I recommend you use .NET classes to work with filenames, but the following demonstrates the concept that if defined as [string], the object has the .NET properties you know quite well (SubString, LastIndexOf):

function GetFileName([string]$fileFullName, [string]$divider="\"){

    #if it doesn't find it, should come back as -1...therefore work as well:    
    $fileFullName.SubString($fileFullName.LastIndexOf($divider)+1);

}

Escaping

 
#Escaping strings...uses ` instead of /
$path = "This is `"quoted`" text.";

IsNullOrEmpty

 
#test a string as null or not
if ($str) {...}

Or (probably more definite):

 if ([string]:: IsNullOrEmpty($text)){
}

Case

 
# Upper/Lower
$text = $text.ToLower()
$text = $text.ToUpper()
#CamelCase
$text = [Regex]::Replace($text , '\b.', {  $args[0].Value.Tolower() })
#PrettyCase:
$text = $text | % { $_.substring(0,1).ToUpper()+$_.substring(1) }

Split / Join

 
#Split:
"One;Two;Three;".Split(";") | ForEach {
    Write-Host "$_ is a token"
 }

 
#Split & Switch
$env:commitMsg.Split(";") | ForEach {
    $tmp = $_.Split(";");
	$tmp[0] = $tmp[0].ToUpper();
	switch($tmp[0]){
	   "PUBLISH" {$_publishTarget = $tmp[1];}
	   "CONFIG" {$Env:BUILDCONFIGURATION = $tmp[1];}
	   "CONFIGURATION" {$Env:BUILDCONFIGURATION = $tmp[1];}
	}
 }

Trim

Trim is another .NET string property:

var s= "tt  ".trim();

Contains/EndsWith, etc

 
$d = $a.EndsWith("Script")

Regex

So just as a reminder, a straight dump of some methods within Lib/Text.ps1:


# regex function
function FindMatch([string]$text, [string]$pattern,[int]$matchId=0){

    if ($text -match $pattern) {
       #extract match from global...
       [string]$result = $Matches[$matchId];
    }

}

  • /home/skysigal/public_html/data/pages/it/ad/powershell/howto/snippets/work_with_strings.txt
  • Last modified: 2023/11/04 23:20
  • by 127.0.0.1