There are 171,476 or so words in the English language. This doesn’t include names or other items. Datamuse is a very powerful database of English words. It contains rhyming, like, anonymous, Synonyms and much more. What I like about this site is it has a simple API that can be stacked. You can find the API here.
What do I mean by stacked. Some APIs use the URL and gathers all the information from that. While others uses the custom header and body of requests. Datamuse uses the URL. It returns a nice json to work with as well inside its content area. Basically, it’s my kind of API. The below API is an example of a url API. After words? each XX= has the word to query with. Each item means something different. The ML means, means like and the sp is spelled like. So we are looking for words that means like black and starts with the letter b.
https://api.datamuse.com/words?ml=Black&sp=b*
URL API’s are super easy to work within PowerShell. The key is to make a string of what you are looking for. If you have a flag of $meansLike = Black. Then it will add the &ml=black to the string. Same as $Spelling=”B*”. It will add the &ml=Black&sp=B*. Then we just remove the first character of the string and we have our string. We do that with substring. Let’s take a look at the full script.
The Script
function Get-SHDWords {
[cmdletbinding()]
param (
[string]$MeansLike,
[string]$SoundsLike,
[string]$SpelledLike,
[string]$LeftContext,
[string]$RightContext,
[string]$Topic,
[string]$NounModifiedByAdjective,
[string]$AdjectiveModifiedbyNoun,
[string]$Synonym,
[string]$Trigger,
[string]$Antonym,
[string]$KindOf,
[string]$MoreGeneralThan,
[string]$Comprises,
[string]$Meronym,
[string]$FrequentFollowers,
[string]$FrequentPredecessors,
[string]$Rhymes,
[string]$NearRhymes,
[string]$Homophones,
[string]$Consonant,
[switch]$Random
)
$actionstring = ""
if ($PSBoundParameters.ContainsKey('MeansLike')) { $actionstring = "$($actionstring)&ml=$MeansLike" }
if ($PSBoundParameters.ContainsKey('SoundsLike')) { $actionstring = "$($actionstring)&sl=$SoundsLike" }
if ($PSBoundParameters.ContainsKey('SpelledLike')) { $actionstring = "$($actionstring)&sp=$SpelledLike" }
if ($PSBoundParameters.ContainsKey('LeftContext')) { $actionstring = "$($actionstring)&lc=$LeftContext" }
if ($PSBoundParameters.ContainsKey('RightContext')) { $actionstring = "$($actionstring)&rc=$RightContext" }
if ($PSBoundParameters.ContainsKey('Topic')) { $actionstring = "$($actionstring)&topics=$Topic" }
if ($PSBoundParameters.ContainsKey('NounModifiedByAdjective')) { $actionstring = "$($actionstring)&rel_jja=$NounModifiedByAdjective" }
if ($PSBoundParameters.ContainsKey('AdjectiveModifiedbyNoun')) { $actionstring = "$($actionstring)&rel_jjb=$AdjectiveModifiedbyNoun" }
if ($PSBoundParameters.ContainsKey('Synonym')) { $actionstring = "$($actionstring)&rel_syn=$Synonym" }
if ($PSBoundParameters.ContainsKey('Trigger')) { $actionstring = "$($actionstring)&rel_trg=$Trigger" }
if ($PSBoundParameters.ContainsKey('Antonym')) { $actionstring = "$($actionstring)&rel_ant=$Antonym" }
if ($PSBoundParameters.ContainsKey('KindOf')) { $actionstring = "$($actionstring)&rel_spc=$KindOf" }
if ($PSBoundParameters.ContainsKey('MoreGeneralThan')) { $actionstring = "$($actionstring)&rel_gen=$MoreGeneralThan" }
if ($PSBoundParameters.ContainsKey('Comprises')) { $actionstring = "$($actionstring)&rel_com=$Comprises" }
if ($PSBoundParameters.ContainsKey('Meronym')) { $actionstring = "$($actionstring)&rel_par=$Meronym" }
if ($PSBoundParameters.ContainsKey('FrequentFollowers')) { $actionstring = "$($actionstring)&rel_bag=$FrequentFollowers" }
if ($PSBoundParameters.ContainsKey('FrequentPredecessors')) { $actionstring = "$($actionstring)&rel_bgb=$FrequentPredecessors" }
if ($PSBoundParameters.ContainsKey('Rhymes')) { $actionstring = "$($actionstring)&rel_rhy=$Rhymes" }
if ($PSBoundParameters.ContainsKey('NearRhymes')) { $actionstring = "$($actionstring)&rel_nry=$NearRhymes" }
if ($PSBoundParameters.ContainsKey('Homophones')) { $actionstring = "$($actionstring)&rel_hom=$Homophones" }
if ($PSBoundParameters.ContainsKey('Consonant')) { $actionstring = "$($actionstring)&rel_cns=$Consonant" }
if ($Random) {
$Character = [char](Get-Random -Minimum 65 -Maximum 90)
$actionstring = "$($actionstring)&sp=$Character*"
}
$actionstring = $actionstring.Substring(1)
(Invoke-WebRequest -Uri "https://api.datamuse.com/words?$actionstring").content | convertfrom-json
}
The Breakdown
Ok, first notice that we have each of the items from the datamuse site as string values that can take input. None of them are mandatory. The first thing after the parameters is our blank action string.
Next, we start questioning the input like a youtube conspiracy theorist. We do that by asking if the bound parameters contains a key. If it does we add to the action string.
if ($PSBoundParameters.ContainsKey('MeansLike')) { $actionstring = "$($actionstring)&ml=$MeansLike" }
Here we are recreating the string by taking the value of the string and adding the &ml=$MeansLike. We do this for each parameter we use except for random. Random we just grab a random english word character and ask for a word that starts with that word. After we have created our action string we use our substring command to remove the first & from the string.
$actionstring = $actionstring.Substring(1)
Once we have the action string formatted right, we are ready to go. We use the invoke-webrequest command and we will grab the data. We will select only the content, which is in a nice json format. Then we will pipe that information into convertfrom-json to create a Powershell object.
Here we are looking for all the words that start with the letter L and that Rhyme with Pink.
Example 2 – Lash
Get-SHDWords -MeansLike anger -SoundsLike love | Where-Object {$_.tags -contains "v"}
Here are the results:
word score tags
---- ----- ----
lash 14742 {v}
In this example, we are looking for words that mean anger but sound like love. Some of the results will have tags. Items like means like and sounds like have tags that you can filter through. With this example, we are looking for verbs. So we look with the where-object command.
In this example, we get a random list of words that start with a random letter. Then we select from that list a random item. We do that with the get-random with a minimum of 0 and the maximum of the test count. Then we select the word. All that produced the word ominous.
Taking a step farther – Passwords
Let’s take this one step further and make a two-word password. The first thing we want is a word. So we use the command Get-SHDwords again. We are going to use the word trust.
Here we generate 3 random characters. We then select our word, trust by putting it into the $One. We can replace our word by replacing the $One input. Then we get the second word with two. Get-SHDWords -Rhymes $One Then we grab just one of those words like before. This time we replace all the vowels with the character we generated at the beginning. Then we combine it all together. The first word, $One, the middle character, $characterMiddle, the second word $two, and finally the ending Character $CharacterEnd. Now we have an easy-to-remember password.
Datamuse offers even more options than what this script offers. Check them out and see what amazing things you can create.
I’m going to leave off here with a challenge this week. Can you write a poem using datamuse based off the word:
Do you have a zip file or an msi file that you need to embed into a powershell script for deployment. This is a quick and simple way to do this. The method is pretty sound and works most of the time. The larger the file, the more troubles the system has converting and converting back, so small files works wonders for this method.
The first thing we are going to do is convert a file into a base 64 string. This is done through the command Get-Content and the system convert method. Powershell 7 recently changed the command for this method and we will cover that first.
Powershell 7 Command
The get content changed the encoding flag to asbytestream flag.
This command will read the data as raw byte data which is needed for the System convert method. The Powershell 5 method users Encoding and then you select your type which is byte.
Powershell 5
$Content = Get-Content -Path $Path -Encoding Byte
These commands reads the data as raw information that will be used for the system.convert to base 64 string method.
Now we have an object of random-looking data like before. We need to write those bytes to a file we do that with the System.IO.File write all bytes method. We will need the outfile location. and the object we created earlier to complete this task.
[system.io.file]::WriteAllBytes($OutFile,$object)
This will create the file you embedded into your powershell script.
Use Case
Encrypted Passwords
Let’s secure a password file and key file inside our embedded script. First, we are going to create the key for out password file.
Now we build the script with these two pieces of information. We recreate the files from the script and then pull them in like before. Here is the key code:
Now we have both files needed to receive our password, let’s convert that password using the key from before. We get the content of the .key file with get-content. Then we use it when we convert to secure string the password file. Pushing all that information into a new credential object for later use in something like a nextcloud download. Then we remove the files as we don’t want that password getting out there.
Let’s say we need to embed an MSI file. For example, we have a custom Open DNS MSI that will auto setup the Umbrella client on an end user’s computer. The first thing we want to do is convert that msi file to the base 64 string like above.
Here we are using the powershell 5 code to convert the msi into a string and pushing it out to our clipboard. Now we need to place that information into the script. This is what the script would look like:
As you can see by the size of the base64 string, that seems like a large file. Surprisingly that’s only 11kb in size. The larger the file the more code will be present and the chances of buffer overload increases.
Scripts
What kind of person would I be without giving you a function or two to make life easier on you. Here are two functions. The first converts the item to base64 string and copies it to your clipboard. The second converts a base64 string to an object.
This little script logs public IP address changes. The original design was to email out. I’ll make sure to point out when and where to put that code. So the idea is simple. It checks to see if it’s public IP address has changed using an invoke-webrequest. If it has changed, it checks to see if a log has been made. If it has been made, it updates the log, if it hasn’t been made, it creates the log. Then when the IP address changes back, it backs up the logs and stops. Lets take a look at the script.
The Script
Param (
[string]$IPAddress = "Your IP Address"
)
$IP = (invoke-webrequest -Uri "http://ifconfig.me/ip" -UseBasicParsing).content
If (!(Test-Path C:\temp)) { New-Item -Path "c:\temp" -ItemType Directory }
if (!($IP -like "$IPAddress")) {
if (!(Test-Path c:\temp\IPTrigger.log )) {
#Email Code Goes Here
$Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
"Datetime,IP" > c:\temp\IPTrigger.log
"$datetime,$IP" >> c:\temp\IPTrigger.log
}
else {
$Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
"$datetime,$IP" >> c:\temp\IPTrigger.log
}
}
else {
if (Test-Path c:\temp\IPTrigger.log) {
$Datetime = (Get-Date).ToString("yyyy-MM-dd_HH-mm")
Copy-Item -Path c:\temp\IPTrigger.log -Destination "c:\temp\IPTrigger_$($datetime).log.bak"
Remove-Item -Path c:\temp\IPTrigger.log
#Email Code goes here with attachment of the log bak.
}
}
The Breakdown
We grab the IP address from the Paramters. This way you can have the script called Public-IPChecker -IPAddress Something from your task scheduler. After we get what the IP Address should be we get what It is with the Invoke-webrequest command.
There are a hand full of sites that grabs the IP address for you. I personally like Ifconfig.me because it places the IP address as the content. Thus no sorting through the HTML to get the IP address.
Next we ask if it’s the IP address. Then we ask if the log has been made.
if (!($IP -like "$IPAddress")) {
if (!(Test-Path c:\temp\IPTrigger.log )) {}
}
If it doesn’t exist, we create it by getting the DateTime into a file friendly format. and Piping that information into the log file along with the current IP address.
If the IP addresses do match then we test to see if the log file is there. If it is there we create a bak of the log file and remove the old one. This is when you can send an email saying it’s back up. If it doesn’t exist, we do nothing.
I have been using Quser for years and I was wondering how to parse the data out to Powershell. The best way to do this is to convert the output into a csv and then convert it from the csv to a psobject. Let us get started. First we output the quser to a variable.
In this example, we are going to grab the local computer’s logged-in information. Here is what the output looks like:
PS C:\Users\david> Quser /server:"$($env:COMPUTERNAME)" 2> $null
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
david console 11 Active 1:05 9/5/2021 9:29 PM
susan 12 Disc 1:05 9/6/2021 11:14 AM
Next, we replace the first (^) > with nothing. It doesn’t look like much but it adds the spacing needed.
$Users = $Users -Replace '^>',''
Here is the output.
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
david console 11 Active 1:08 9/5/2021 9:29 PM
susan 12 Disc 1:08 9/6/2021 11:14 AM
Now we will replace the tabs with commas.
$Users = $Users -Replace '\s{2,}',','
USERNAME,SESSIONNAME,ID,STATE,IDLE TIME,LOGON TIME
david,console,11,Active,1:08,9/5/2021 9:29 PM
susan,12,Disc,1:08,9/6/2021 11:14 AM
From here we want to go through each line and remove the last item if it has too many spaces. This happens when you run this command on a server. You will need to go through each line by line with a foreach loop.
Splitting the user by the comma, we need only 4 not 5. So we remove the first of the last object. If it is 4, we do nothing special and just reintroduce the original $user.
USERNAME,SESSIONNAME,ID,STATE,IDLE TIME,LOGON TIME
david,console,11,Active,1:08,9/5/2021 9:29 PM
susan,,12,Disc,1:08,9/6/2021 11:14 AM
Now we take that $user csv and convert it to a psobject using convertfrom-csv.
$users = $users | ConvertFrom-Csv
USERNAME : david
SESSIONNAME : console
ID : 11
STATE : Active
IDLE TIME : 1:08
LOGON TIME : 9/5/2021 9:29 PM
USERNAME : susan
SESSIONNAME :
ID : 12
STATE : Disc
IDLE TIME : .
LOGON TIME : 9/6/2021 11:14 AM
Next, we need to do some house cleaning. Sometimes the Idle time will show up as a dot. We don’t want that. We want it to show up as null. We do this by finding all the dot Idle times and setting that idle time to null with a foreach-object.
USERNAME : david
SESSIONNAME : console
ID : 11
STATE : Active
IDLE TIME : 1:08
LOGON TIME : 9/5/2021 9:29 PM
USERNAME : susan
SESSIONNAME :
ID : 12
STATE : Disc
IDLE TIME :
LOGON TIME : 9/6/2021 11:14 AM
Finally, we output the information by just putting the $users. That’s it yall. Lets put it together.
Another way to do this is to grab a process from the machine that everyone logged in would be using. Something like explorer. We do this with the get-ciminstance and the wmi object win32_process.
Recently the send-mailmessage was put to rest with good reason. It failed to do its job by securing the emails. It sent items via plain text and not SSL encrypted. Great for internal nothing fancy, but bad if you wanted to send data outside the world. So, I built an alternative that I use the mail message system inside windows. Let’s Send Mail With Powershell.
The Script
function Send-SHDMailMessage {
<#
.SYNOPSIS
Sends an email using custom SMTP settings.
.DESCRIPTION
Sends an email using custom SMTP settings.
.PARAMETER From
As string. Name of the Email address from which it will come from.
Example: "David Bolding <admin@example.com>"
.PARAMETER To
As string. The email address too.
Example: "Admin@example.com"
.PARAMETER SMTPUsername
As string. The Username for the SMTP service you will be using.
.PARAMETER SMTPPassword
As string. The Password in plain text for the smtp service you will be using.
.PARAMETER SMTPServer
As string. The server name of the SMTP service you will be using.
.PARAMETER SMTPPort
As string. The Server Port for the smtp serivce you will be using.
.PARAMETER Subject
As string. The subject line of the email.
.PARAMETER Body
As string. The body of the email as a string. Body takes default over BodyAsHtml
.PARAMETER BodyAsHTML
As string. The body of the email in html format.
.PARAMETER PlainText
Sends the email in plain text and not ssl.
.PARAMETER Attachment
As array of strings. A list of full file names for attachments. Example: "c:\temp\log.log"
.PARAMETER CC
Email address for a carbon copy to this email.
.PARAMETER BCC
Email address for a blind carbon copy of this email.
.PARAMETER Priority
A validate set for High, Normal, Low. By default it will send emails out with Normal.
.EXAMPLE
$Message = @{
from = "HR <HumanResources@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "Test"
Attachment = "C:\temp\JobOffer1.pdf","C:\temp\JobOffer2.pdf"
BodyAsHtml = @"
<html>
<body>
<center><h1>Congradulation</h1></center>
<hr>
<p>Attached is the job offers we discussed on the phone.</p>
<br>
Thank you,<br><br>
Human Resources
</body>
</html>
"@
}
Send-SHDMail @Message
Sends an email using the required information with two attachments.
.EXAMPLE
$Message = @{
from = "HR <HumanResources@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "Test"
BodyAsHtml = @"
<html>
<body>
<center><h1>Sorry, Not Sorry</h1></center>
<hr>
<p>Sorry you didn't get the job. Maybe next time show up with clothing on.</p>
<br>
Thank you,<br><br>
Human Resources
</body>
</html>
"@
}
Send-SHDMail @Message
This will send out an email without any attachments.
.EXAMPLE
$Message = @{
from = "HR <HumanResources@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "Test"
Body = "Your Hired"
}
Send-SHDMail @Message
Sends out a message using just a simple text in the body.
.EXAMPLE
$Message = @{
from = "HR <HumanResources@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "Test"
Attachment = "C:\temp\JobOffer1.pdf","C:\temp\JobOffer2.pdf"
}
Send-SHDMail @Message
This will send out an email that is blank with attached items.
.EXAMPLE
$Message = @{
from = "Notify <Notify@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "$SomethingWrong"
PlainText = $true
}
Send-SHDMail @Message
This will send out an unsecured email in plain text.
.EXAMPLE
$Message = @{
from = "Notifiy <Notify@example.com>"
To = "IT@example.com"
SMTPUsername = "SMTPUser"
SMTPPassword = "SMTPPassword"
SMTPServer = "mail.example.com"
SMTPPort = "2525"
Subject = "Server Down"
CC = "ITManagers@Example.com"
BCC = "CFO@Example.com"
PlainText = $True
Priority = "High"
BodyAsHTML = @"
<html>
<body>
<center><h1>SERVER DOWN!</h1></center>
</body>
</html>
"@
}
Send-SHDMailMessage @Message
.OUTPUTS
no Output.
.NOTES
Author: David Bolding
Date: 09/8/2021
.LINK
#>
[cmdletbinding()]
param (
[parameter(Mandatory = $true)][String]$From,
[parameter(Mandatory = $true)][String]$To,
[parameter(Mandatory = $true)][String]$SMTPUsername,
[parameter(Mandatory = $true)][String]$SMTPPassword,
[parameter(Mandatory = $true)][String]$SMTPServer,
[parameter(Mandatory = $true)][String]$SMTPPort,
[parameter(Mandatory = $true)][String]$Subject,
[Switch]$PlainText,
[string]$Body,
[String]$BodyAsHTML,
[String[]]$Attachment,
[string]$CC,
[string]$BCC,
[Validateset("High","Low","Normal")][String]$Priority
)
# Server Info
$SmtpServer = $SmtpServer
$SmtpPort = $SmtpPort
# Creates the message object
$Message = New-Object System.Net.Mail.MailMessage $From, $To
If ($PSBoundParameters.ContainsKey("CC")) {
$Message.CC.Add($CC)
}
If ($PSBoundParameters.ContainsKey("BCC")) {
$Message.Bcc.Add($BCC)
}
If ($PSBoundParameters.ContainsKey("Priority")) {
$Message.Priority = $Priority
} else {
$Message.Priority = "Normal"
}
# Builds the message parts
$Message.Subject = $Subject
if ($PSBoundParameters.ContainsKey("Body")) {
$Message.IsBodyHTML = $false
$Message.Body = $Body
}
elseif ($PSBoundParameters.ContainsKey("BodyAsHTML")) {
$Message.IsBodyHTML = $true
$Message.Body = $BodyAsHTML
}
else {
$Message.IsBodyHTML = $false
$Message.Body = ""
}
if ($PSBoundParameters.ContainsKey('Attachment')) {
foreach ($attach in $Attachment) {
$message.Attachments.Add("$Attach")
}
}
# Construct the SMTP client object, credentials, and send
$Smtp = New-Object Net.Mail.SmtpClient($SmtpServer, $SmtpPort)
if ($PlainText) {
$Smtp.EnableSsl = $true
}
else {
$Smtp.EnableSsl = $true
}
$Smtp.Credentials = New-Object System.Net.NetworkCredential($SMTPUsername, $SMTPPassword)
$Smtp.Send($Message)
#Closes the message object and the smtp object.
$message.Dispose()
$Smtp.Dispose()
}
Examples
$Message = @{
from = "HR <HumanResources@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "Job Offers"
Attachment = "C:\temp\JobOffer1.pdf","C:\temp\JobOffer2.pdf"
BodyAsHtml = @"
<html>
<body>
<center><h1>Congradulation</h1></center>
<hr>
<p>Attached is the job offers we discussed on the phone.</p>
<br>
Thank you,<br><br>
Human Resources
</body>
</html>
"@
}
Send-SHDMail @Message
In this example, I am using the SMTP2go service to send a job offer letter to a new employee. It contains the attachment flag with two offers. Each attachment is separated with a comma as this is a list of strings. The Body is an HTML using the BodyAsHTML flag. The BodyAsHTML has some custom formatting to make it look somewhat nice.
$Message = @{
from = "HR <HumanResources@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "Thank you"
BodyAsHtml = @"
<html>
<body>
<center><h1>Sorry, Not Sorry</h1></center>
<hr>
<p>Sorry you didn't get the job. Maybe next time show up with clothing on.</p>
<br>
Thank you,<br><br>
Human Resources
</body>
</html>
"@
}
Send-SHDMail @Message
In this example, we are once again using the SMTP2Go to send a rejection letter. No attachments are present on this email. The bodyashtml string is set with a nice custom HTML page.
$Message = @{
from = "Notify <Notify@Example.com>"
To = "Somebody@Example.com"
SMTPUsername = "SMTP2GoUsername"
SMTPPassword = "SMTP2GoPassword"
SMTPServer = "mail.smtp2go.com"
SMTPPort = "2525"
Subject = "Server Down"
Body = "XYZ Server Is Down"
}
Send-SHDMail @Message
In this example, we are sending out a notification email using a different user than before. We are using the same smtp2go, but you can use any server with the username and password you like. The body is a basic string with no HTML formating.
In this example, we are sending a notification email without a body. We are using a custom variable for the subject line. We are also sending this without the SSL encryption as some legacy systems don’t understand SSL encryption.
In this example, we are Sending a Carbon copy to the IT manager and a blind carbon copy of the email to the CFO with a high priority.
Notes
The Body and BodyAsHTML can conflict with each other. If you do both the Body and BodyAsHTML, by default, the body will be selected. If you do not put in a body or bodyashtml, it will send the email with a body of “”.
This script requires you to have an SMTP service like SMTP2Go.
Conclusion
That my friends is how you Send Mail With Powershell.
In the last blog, I talked about how to upload to your next cloud’s file drop, aka upload only, password-protected folder. This time we will go over how to download from a password-protected folder. Let’s go over how to share out a file with a secure password.
Password-Locked Single File
Navigate to the file you wish to share out.
Click on the file in question.
Click the share link + symbol.
Checkbox the “Password Protect”
Enter a new secure password.
Document the password!
Click the Arrow to set the password
click the Clipboard to copy the link.
In another browser, navigate to the link to make sure it works.
Now we have the File shared, it’s time to download it.
The share ID
The Share Password
The URL of the nextcloud site.
The file name/location of where you will save the file.
Now you have those pieces of information, you can start the process of creating the header. Let’s look at the Variables first.
The Authorization type is going to be basic. We are going to convert the shareid and the sharepassword into the UTF8 so our nextcloud can understand it. We want all that as a base 64. So we create the string with “$($ShareID):$($SharePassword)” and push that into our System.Text.Encoding UTF8. Using the method GetByes. All that is then put into the System.Convert base of 64 string, aka password.
Next, we tell the site what we are requesting, we are requesting the XML HTTP request. Next, we will create the URL that will be used by the rest method.
$URL = "$($NextCloudURL)public.php/webdav"
Now we create the invoke-restmethod to download the file in question.
Now that we covered password locked, it’s time to look at the non-password locked. This is a single line item. Like above, just don’t create a password. Copy the URL.
Navigate to the file that you wish to share
clickt he share icon
Click the share link +
Copy the Link
This is a single-line command. The copied item will be the URL/shareID. If you place a /download at the end, it will download accordingly. Nice right. Its even nicer with PowerShell.
That’s it! A simple invoke-webrequest. Now, let’s take it to a different level.
Download a single file from a shared Folder
If you share out a single folder, you can download the files directly from that folder if you know those file names, even if the file isn’t shared itself. Standard information is required. First, let’s make the shared folder.
Navigate to the folder you wish to share out.
Click the share icon.
Click the Share Link +
Click the 3 Dots.
Click the Password Protect
Enter a new password
Document the new password
Click the Arrow beside the password
Click the clip board to copy the link
Here are the items you are going to need to setup this command.
The URL of the next cloud
The Share ID
The Share Password
The File name you are going to download.
The filename/location where you will be downloading too.
The share this time is the folder. So we are authing to that folder. This is great because if you forget the password later, it’s in the script. Next, we grab the file using the invoke-restmethod.
Invoke-RestMethod -Method GET -Header $Header -uri "$($NextCloudURL)public.php/webdav/$($Filename)" -OutFile $Outfilepath
Notice at the end of the URL, the $($filename). This is the filename inside the share. So we are looking for that file to download. That’s all, take a look at the script.