How to copy and paste from a variable in PowerShell? - powershell

I'm trying to look up a value in PowerShell and paste it as a string into a line of text on another application.
In this instance I need to put the date into a line for an API call. I've found the date and can access the line where I need to input the date. I'm having trouble highlighting the date output, or using the variable where I have stored the date to paste that date into the line of code I'm using.
PowerShell code
$TDay = (Get-date).AddDays(-14)
Get-Date $TDay -Format MM-dd-yyyy
--API call
https:\\companyteam.teamwork.com/desk/v1/tickets/search.json?lastUpdated=07/26/2019
I'm able to delete the previous date but now I need to paste the value of the result from the PowerShell Script into where the date is displayed on the API call.
To solve my problem I think I'll need to manually highlight the results from the API call using the PowerShell mouse commands or if I could potentially just tell PowerShell to paste the result of Get-Date $TDay -Format MM-dd-yyyy

You can use Set-Clipboard to set the clipboard contents, which is the equivalent to a copy. You can use Get-Clipboard to paste copied contents to the console or as a variable value. You can also just paste from any copy-paste menu that has access to your clipboard.
Get-Date $TDay -Format MM-dd-yyyy | Set-Clipboard
$variable = Get-Clipboard
Since I am not sure how you are making the API call, simplistically speaking let's assume the URI is just a string. You can still use the Get-Clipboard command or variable within the sub-expression operator $(). Variables don't technically need the sub-expression unless you are accessing properties of that variable.
"https:\\companyteam.teamwork.com/desk/v1/tickets/search.json?lastUpdated=$(Get-Clipboard)"
# OR
"https:\\companyteam.teamwork.com/desk/v1/tickets/search.json?lastUpdated=$variable"

Related

How to converse Markdown file to HTML in PowerShell without any error and in a clean way?

so I have updated my PowerShell (downloaded new one from MS Store) to version 7.2.4.0.
And the I wantto convert Markdown file to HTML, so I would import the 2 modules based on this description (https://social.technet.microsoft.com/wiki/contents/articles/30591.convert-markdown-to-html-using-powershell.aspx), so I would do something like:
Import-Module C:\Users\user\Documents\WindowsPowerShell\Modules\powershellMarkdown.dll
Import-Module C:\Users\mitus\Documents\WindowsPowerShell\Modules\MarkdownSharp.dll
Now I want to:
$md = ConvertFrom-Markdown C:\test\test.md
It results with:
ConvertFrom-Markdown: The given key 'test.md' was not present in the dictionary.
So I try the following:
$md = ConvertFrom-Markdown -Path .\test.md
And the POwerShell now says:
ConvertFrom-Markdown: A parameter cannot be found that matches parameter name 'Path'.
Either way, Its not working. Why PowerShell does not know parameter -Path? How do I make conversion from Markup to HTML working? Why is this shit not working at all even if imported those two .dll files? What am I doing wrong?
Thank you for your help!
The ConvertFrom-* commands generally don't support file input directly (with exceptions). When there is no related Import-* command, you have to use Get-Content to first read the file and then pass it to the ConvertFrom-* command like so:
$md = Get-Content C:\test\test.md -Raw | ConvertFrom-Markdown
Make sure to use the -Raw parameter so the ConvertFrom-Markdown command receives a single input string instead of an array of lines, which could be parsed incorrectly.
If you want to inspect the content of the .md file first, you may store it in a separate variable:
$text = Get-Content C:\test\test.md -Raw
# Now you may optionally log the content of the .md file
Write-Host $text
$md = $text | ConvertFrom-Markdown

Is there a way to use wildcards when downloading and saving a file using Powershell?

I have a PowerShell script that I am using to download a file from a URL every morning, however it has started putting the date on it every day, therefore making it imppossible to use a scheduled PowerShell everyday to download it.
Is there anyway to use a wildcard to make it pick up all of the dates?
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile("https://test.com/store/scheduled/320%2019.10.22.csv","\\server\shared\Reports\RawData\Cross Selling Data.csv")
The bold bit is what I am looking to Wildcard after '320' as this is the report number but before .csv. I've tried * but that doesn't seem to work. The date obviously changes on each day's report.
When it comes to using wildcard, the answer is no. It's impossible to use wildcard while making web requests as it'd require checking every possible path.
What is possible is to construct the path programmatically if you know the pattern. For example, in your case
# That input
PS> Get-Date -Format 'yy.MM.dd'
# Gives you the following result
19.10.22
which looks similarly to the pattern you included in your code (I assume %20 is space). To use it in string (assuming you use double quotes ") you can use the following:
"https://test.com/store/scheduled/320%20$(Get-Date -Format 'yy.MM.dd').csv"
Last, but not least, as #Tomalak mentioned in comments, Invoke-WebRequest might work for you as well.

Meaning of Powershell statement

I am completely new to Powershell and I am trying to understand what this fragment of code does:
$OwnFunctionsDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Functions"
Write-Host "Loading own PowerShell functions from:" -ForegroundColor Green
Write-Host "$OwnFunctionsDir" -ForegroundColor Yellow
Get-ChildItem "$OwnFunctionsDir\*.ps1" | %{.$_}
Write-Host ''
In particular I cannot interpret what the line Get-Children … does. This code is intended to be added to your Powershell profile to load commonly used functions at Powershell startup.
Short Answer
This command loads the contents of all ".ps1" files in "<yourHomeDirecotry>\Documents\WindowsPowerShell\Functions" into your working session.
Long Answer
First, $env:USERPROFILE is an environment variable that corresponds to your home directory. So in my case it is "c:\users\jboyd"
The first interesting bit of code is:
$OwnFunctionsDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Functions"
This assigns a string to a new variable named OwnFunctionsDir. What's interesting about this string is that it is double quoted and it contains the variable $env:USERPROFILE. PowerShell expands variables in double quoted strings (this is not the case for single quoted strings). So if this were running on my machine the value of $OwnFunctionsDir would be "c:\users\jboyd\Documents\WindowsPowerShell\Functions".
Skipping the Write-host functions (because I think they are pretty self explanatory) takes us to:
Get-ChildItem "$OwnFunctionsDir\*.ps1" | %{.$_}
Get-ChildItem is interesting because its behavior depends on the PowerShell provider (don't worry about what that is) but in this case Get-ChildItem is the equivalent of dir or ls. $OwnFunctionsDir\*.ps1 is the path being enumerated. Using my machine as an example, this is equivalent to listing all files with names matching the wildcard pattern "*.ps1" (essentially all PowerShell files) in the directory "c:\users\jboyd\Documents\WindowsPowerShell\Functions".
The | character pipes the results of the command on the left to the command on the right.
The % character is an alias for the ForEach-Object command. The left and right curly braces are a scriptblock, this is the body of the foreach command. So each item from Get-ChildItem is piped into the scriptblock.
In the scriptblock of the ForEach-Object command the $_ variable represents the current item being processed. In this case $_ will be a PowerShell file with an extension ".ps1". When we invoke a PowerShell file with a period in front of it that is called dot sourcing. Dot sourcing loads the content of a file into your working session. So any variables or functions in the file are loaded.

Create Directory using Get-Date is making Sub Folders?

Just a small issue and i'm likely missing something very simple
I've setup a script just to make a few folders as part of a bigger script
I've tried to set it up so that when the script is ran a new directory is created with the date in as so:
$Date = ((Get-Date).ToShortDateString())
$CompileFolder = "C:\Registry_Export\PostInfection\$Date\Compiled Postinfection"
New-Item -path $CompileFolder -ItemType Directory
The script works as intended (The part above is just a piece from the script)
However when the directories are generated they are creating sub directories instead of just one directory.
For Example 23/03/2017 should make a folder called 23/03/2017
However it is making a folder structure of:
C:\Registry_Export\PostInfection\23\03\2017\Compiled Postinfection
I understand that this is because of the / that is generated because of the date however would like to know if there is an easy way to rectify this
Thank You
/ is an illegal file name character in NTFS (and, by extension, also an illegal directory name character).
I would suggest either using a different separator for your date string, like - or ., or just omitting a separator completely. To use a custom format, you can use either ToString(), the -f string format operator, or Get-Date -Format
# using hyphens (23-07-2017)
$Date = '{0:dd-MM-yyyy}' -f (Get-Date)
# using dots (23.07.2017)
$Date = (Get-Date).ToString('dd.MM.yyyy')
# using no separator (23072017)
$Date = Get-Date -Format ddMMyyyy
To complement Mathias R. Jessen's helpful answer:
Another way of putting it: any \ or / chars. in a name passed to New-Item -ItemType Directory are interpreted as path separators separating multiple directory names.
Generally, consider using a culture-invariant, sortable string format, such as the one provided by the s standard format string, which is based on the ISO 8601 standard:
> (Get-Date -Format s) -replace 'T.*'
2017-03-23
The -replace 'T.*' part simply cuts off the time portion.

How do I properly handle spaces in file names passed as arguments to a PowerShell script via a SendTo shortcut?

I've written a (very) simple script that appends the current date to a given file name in PowerShell, and I've set it up with a SendTo shortcut for easy access.
However, it doesn't handle file names with spaces in them very well. If a file name is "thisFile.txt" it correctly adds the date, making it "thisFile.txt.20121227", but if the file name is "this File.txt" it doesn't work from the SendTo shortcut I've set up.
It does work from the command line for both types of file names, however, and I've been scratching my head trying to figure out why.
This is the snippet of code I've been using:
$enddate = (Get-Date).toString("yyyyMMdd")
$filename = $arg
foreach ($filename in $args) {
Rename-Item $filename $filename"."$enddate
}
This is in the Target field for the shortcut I've set up:
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe " -NonInteractive -WindowStyle Hidden -NoProfile -noexit &"C:\Scripts\adddate.ps1"
Using the -f switch instead of the ampersand (&) in front of the script path should solve your issue.
You might want to do a little debugging.
I would wager that your filename with spaces is getting split into an array.
In your for loop, write the output of the $filename variable to a file. You might find that you need to add a little logic to your script that says "hey, this doesn't have an extension! i need to append more items in the area until this is a filename with an extension!", or perhaps until "test-path $filename" returns true.