How to Copy and Paste From a Variable in PowerShell
-
Use the
Set-Clipboard
Cmdlet to Copy From a Variable in PowerShell -
Use the
Get-Clipboard
Cmdlet to Paste From a Variable in PowerShell
This article demonstrates how we can copy and paste from a variable in PowerShell.
We use the Set-Clipboard
on PowerShell to determine the content of our clipboard. We then use the Get-Clipboard
cmdlet to fetch and use the clipboard’s content.
Use the Set-Clipboard
Cmdlet to Copy From a Variable in PowerShell
The Set-Clipboard
cmdlet is a useful PowerShell cmdlet that lets us set the clipboard’s content. It is the same as using the copy action in the PowerShell menu.
We can use this cmdlet in several ways. Here are some examples.
In the example below, we have used the Set-Clipboard
cmdlet to give our clipboard a random string.
Set-Clipboard -Value "This is a random string"
We can also copy the contents of a file using the Set-Clipboard
cmdlet as illustrated below:
Get-Content C:\Users\Trial.txt | Set-Clipboard
Below are some common parameters:
-Append
- This instructs the cmdlet not to clear the clipboard and append the content. It is aSwitchParameter
and does not accept wildcard characters and pipeline input.-Confirm
- ThisSwitchParameter
asks users for confirmation before executing the cmdlet.-Value
- This string parameter signifies the string values to be added to your clipboard. The parameter accepts pipeline input.
Use the Get-Clipboard
Cmdlet to Paste From a Variable in PowerShell
We use the Get-Clipboard
cmdlet to fetch and use the clipboard’s content. It returns multiple lines of text as arrays of strings like the Get-Content
cmdlet.
For example, in our first command, we had set our clipboard to This is a random string
. We can use the Get-Clipboard
command to display the content of our clipboard, as shown below:
Now, we have familiarized ourselves with the two cmdlets. Let’s discuss how we can copy and paste from a variable in PowerShell.
We will use an example to demonstrate the concept.
Let’s assume we are trying to make an API call using today’s date. To do that, we will need to store today’s date in a variable. How do we go about this?
To get the date, we will use the Get-Date
cmdlet. We will then pipe the results to the Set-Clipboard
cmdlet as shown below:
Get-Date $TDay -Format MM-dd-yyyy | Set-Clipboard
We have set the format as the month, day, and year. Next, we will store the content of our clipboard as a variable, as shown below:
$variable = Get-Clipboard
With that out of our way, we can now use the variable in our API call.
The Set-Clipboard
and Get-Clipboard
cmdlets are useful PowerShell utilities for copying and pasting.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn