Powershell for Learners – Page 23

Author: Ves Cain

Date math is one of the more basic, and useful things you can do in PowerShell. By passing two dates to the New-TimeSpan function
we can quickly get differences from days down to milliseconds difference.

An example would be

### NOTE: Code samples will execute as is on Windows platforms. Learners
### on Mac’s should download the latest version of PowerShell Core from Microsoft.
### It is recommended to use the PowerShell.ise to execute the code

$Today = Get-Date
[datetime]$EndOfTerm = ‘2023-12-05’
New-TimeSpan -Start $Today -End $EndOfTerm

Sample results:

Sample output:
Days              : 11
Hours             : 6
Minutes           : 49
Seconds           : 45
Milliseconds      : 807
Ticks             : 9749858073940
TotalDays         : 11.2845579559491
TotalHours        : 270.829390942778
TotalMinutes      : 16249.7634565667
TotalSeconds      : 974985.807394
TotalMilliseconds : 974985807.394

In the prior example, we used basic variables. The next, more advanced, example
uses variables, while and for loops, and joins to do some writing for us.


—————— CODE BELOW —————–

#Is this for college or for nanowrimo?
$Use = ‘College’

#If we’re doing a nanowrimo thing then we need to do 1667 words a day to win
if ($Use -eq ‘Nanowrimo’) { 
    $NumberOfWords = 1667
    }
else {
    #If it’s not nano, give me something between 250 and 500 words
    $NumberOfWords = Get-Random -Minimum 100 -Maximum 500
    };

# Find a dictionary on the internet
# Project Gutenberg has lots – and they have “vulgar” dictionaries too
$dictionaryUrl = ‘https://www.gutenberg.org/cache/epub/29765/pg29765.txt’

# Where to place the downloaded dictionary
$dictionarySaveFile = “$($env:TEMP)\Dictionary.txt”

# Perform the dictionary download, putting it in the file we specififed
Invoke-WebRequest -Uri $dictionaryUrl -OutFile $dictionarySaveFile

# Put the contents of the dictionary into a variable
$dictionary = Get-Content $dictionarySaveFile 

# We can’t work with the entire set and so need to pull out the individual words
$dictionaryWords = $dictionary -split ‘\s+’

# This dictionary has the word in capital letters. 
# Everything else is either a defition or reference
# We only want the actual words
# To do this, we only grab words where the string = the capital version of the string
$capitalWords = $dictionaryWords | Where-Object { $_ -ceq $_.ToUpper() }

# Get rid of anything that’s not actual letters (as uppper case hypen is a hypen)
$RemainingWords = $capitalWords | Where-Object { $_ -match ‘^[a-zA-Z]+$’ }

# Eliminate duplicate words – not strictly required but “A” shows up a lot otherwise
# This does not fully eliminate duplicates – could be a code page problem
# Something for the learner to figure out
$UniqueWords = $RemainingWords | Get-Unique

# Grab however many words needed to satisfy the word count for today.
$PaperWordList = Get-Random -InputObject $UniqueWords -Count $NumberOfWords

# Create an empty array – this will store our sentences
$sentences = @()

# Iterate through the words we have and put them into sentences
# Loop through the words and create sentences
$WordCount = 0
while ($WordCount -lt $PaperWordList.Count) {
    # Get a random length for each sentence
    $wordsPerSentence = Get-Random -Minimum 5 -Maximum 24

    # Iterate through and create a sentence for from the list of random words
    # Each sentence will be random in length depending on changing value

    # of WordsPerSentence in the loop
    for ($i = 0; $i -lt $wordsPerSentence – 1; $i += $wordsPerSentence) {
        # Turns the array of words into a long string with a space between each word
        $sentence = $PaperWordList[$i..($i + $wordsPerSentence – 1)] -join ‘ ‘
        # As the words are all upper case, change them to lower case
        $lowerSentence = $sentence.ToLower()
        # Change the first letter in the string to upper case,

        # so it’s proper sentence structure
        $sentences += $lowerSentence.Substring(0,1).ToUpper() +

                $lowerSentence.Substring(1)
        # Add this sentence to the array of sentences
        $wordCount += $wordsPerSentence
    }
}

# Return the sentences, using join to put a period and space between them
$sentences -join ‘. ‘

—————— END CODE —————–

Please note, the sample output contains no grammar or word checking. Punctuation is strictly limited to periods between sentences.

Sample results:

Only one more semester after this one and the degrees are done. The thought of an master in fine arts english program is attractive but the worthiness of it is not. Not to mention the lack of low residency programs that handle genre fiction. Many places want to be snobs about writing and claim it a pure artform and that somehow genre based work is not literary. Sure but what about a master of arts in counselling psychology. That is the whole reason for starting down this scholastic path after the age of forty. The idea of helping people as a therapist was a driving force for not giving up even when things got tough. The english thing only came along because of the desire to make life more difficult and do a double minor. The desire to write a book one day is still there but no masters degree is required for that to be a thing. Then the choice is to keep going with something or give it all up. The question will come in the night whether that means the last decade of work has been for nothing. While the conscious will say that it was not due to the high number and high value of things learned the subconscious will judge harshly for the thousands of hours spent for a piece of paper that means little more than to show the capability of spending hundreds of hours doing something. Learning is never wasted time but video games can be more fun and they do not have a schedule requiring certain levels are completed by Thursday and Sunday each week. A book is full of unlimited joy unless a report is required of the content. The future is something to understand and the next steps forward are those that must be taken. The only judgement that exists is in the self and the self should probably go auric a aboon catcall disfancy workfellow.