Sunday, February 24, 2013

PowerShell: Create contractions or input apostrophes

If you've ever needed to recreate contractions due to aprostrophe's being stripped from values or filenames, then read on:

Download my contractions.csv file (Thank you Enchanted Learning)

The contractions.csv has three columns to suit your needs.  Column one is the root words used to create the contraction.  Column two is the contraction without the apostrophe.  Column three is the resulting contraction.

$contractions = import-csv "c:\powershell\contractions.csv" -header ("Words","NoApostrophe","Contraction")

# I've assigned $file with a file name missing an apostrophe

$file = gci "it s a gas".txt

#Now we read each row of the CSV file searching for the word combination needed 
#to add an apostrophe to the name.  Once found, assign a new filename variable, save the file
#with the new name and break out of the loop


foreach($c in $contractions){if ($file.name -like ("*" + $c.noapostroph
e + "*")){
$newfile = $file.name.replace($c.noapostrophe,$c.contraction);ren $file $newfile;break}}


#to rename a variable string value:



$songtitle = "it s a gas"



foreach($c in $contractions){if ($songtitle -like ("*" + $c.noapostrophe + "*")){$songtitle = $songtitle -replace ($c.noapostrophe,$c.contraction);break}}


No comments: