How to run PowerShell scripts with keyboard shortcuts on Windows 10

PowerShell scripts take a little setting up if you want them to run automatically at a given time. It takes more than using just a scheduled task as the script won’t run in PowerShell as an action. If you’re not looking to automatically run these scripts and instead are looking to run PowerShell scripts with keyboard shortcuts, you can do just that. There are some limitations to this process but nothing that makes the process tedious to use.

PowerShell scripts with keyboard shortcuts

The first thing you need is the PowerShell script. Go ahead and create it. Move it somewhere you know you won’t delete it by accident. Once you’ve done that, go to your desktop and right-click on an empty area. From the context menu, select New>Shortcut.

In the location field, enter the following and make sure you replace “path-to-script” with the complete path to the PowerShell script you want to run with a keyboard shortcut.

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "path-to-script"

Example

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\Users\fatiw\Desktop\toastNotification.ps1"

Click Next, and enter a name for the shortcut. If you want, you can also change the icon that the shortcut uses. By default, it will use the PowerShell icon.

After you’ve created the shortcut, right-click it and select Properties from the context menu. Go to the Shortcut tab, click inside the ‘Shortcut key’ field, and record the keyboard shortcut that you want to use to run the app.

You only need to enter a letter or number. The Ctrl+Alt keys are added by default and will be part of all keyboard shortcuts for running apps/shortcuts to apps.

That should do the trick. You can now run the script with the shortcut that you recorded.

Limitations

I mentioned earlier that this method has limitations, though they’re not very restricting. The limitation is that the shortcut, the one you created, must be placed on the desktop or added to the Start Menu. If you move the shortcut anywhere else, e.g., to a different drive on your PC, or nest it inside a folder, the keyboard shortcut will not be able to run the script.

Keeping the script on your desktop is really the most reliable way to run scripts with a keyboard shortcut. It seems that using the Pin to Start option in the shortcut’s menu doesn’t really do the trick and neither does adding it to the Start Menu folder. It may have to do with the script I tested this out on so go ahead and try it out for yourself. If adding the shortcut to the Start Menu won’t work, you’re going to have to place it on your desktop.

Read How to run PowerShell scripts with keyboard shortcuts on Windows 10 by Fatima Wahab on AddictiveTips – Tech tips to make you smarter

How to fix ‘Unable to find module repositories’ error in PowerShell on Windows 10

PowerShell does a few basic things but there are quite a few modules available for it that you can install and use them to get more out of it. Installing a module in PowerShell is pretty easy however, sometimes when you try to install a module you get the error ‘Unable to find module repositories’ which prevents you from installing it. If you’re getting this error, the fix is pretty easy.

Fix ‘Unable to find module repositories’

Open PowerShell with admin rights and run the following command;

Register-PSRepository -Default

Once the command has run, the problem should be resolved. Run the command to install a module or add a repository and this time, it should work. The command completes within a few seconds.

Other solutions

The ‘Unable to find module repositories’ error appears when PowerShell cannot find the repository that you’re adding, or the module that you’re trying to add since it too comes from a repository. The command re-registers the repository gallery which is why, in most cases, it will fix the problem.

Other reasons this error may appear is if PowerShell is unable to communicate with the repository that you want to add. This could be a problem with your internet. If you’re using a VPN or a Proxy service, disable it and then try installing the module again. It’s worth running the Register command again after disabling the proxy before you attempt to install a module.

If disabling the proxy is not an option, you need to enable the proxy for PowerShell as well. If you’re using a proxy via a desktop app, it is highly likely PowerShell is bypassing it. Once you enable the proxy for PowerShell, run the Register command again and then try installing the module.

You should also make sure that you’re running the latest version of PowerShell. If you’re not running the latest version of Windows 10, your version of PowerShell might not be the latest and that’s why the command might be failing. You should also uninstall older versions of PowerShell.

Lastly, and this really is a last ditch effort, try changing the execution policy and then import or install the module. You should also make sure the module is still available. Try installing a different module to see if it installs and if it does, perhaps the problem is with the other module that you’re trying to install. Some modules might have other, alternate methods for installing them so try those.

Read How to fix ‘Unable to find module repositories’ error in PowerShell on Windows 10 by Fatima Wahab on AddictiveTips – Tech tips to make you smarter

How to save command output to file from Command Prompt and PowerShell on Windows 10

The commands that you execute in PowerShell and Command Prompt can output information. Sometimes, it’s just a few lines e.g., when you check the ping, or it might be a lot of lines e.g. when your local IP address or your external IP. Regardless of how long the output is, sometimes you just need to save it to a file so that you don’t have to fetch the information again and again. Both Command Prompt and PowerShell support copy and paste but you can also save command output to a file when the command is run. Here’s how you can do that in both Command Prompt and PowerShell.

Command output to file – Command Prompt

Open Command Prompt and enter the command that you want to run. Before you tap Enter though, add the following at the end;

> name-of-file.txt

You don’t have to create the text file first. Command Prompt will do that for you. If you enter just the name of the file, it will be created in the same directory that the Command Prompt is currently in. You can save the output to a different location by adding the path to the folder you want to save the output to.

> path-to-folder\name-of-file.txt

If you want to save the output to a file but also view it in Command Prompt, you can do that with this command;

> path-to-folder\name-of-file.txt | type

Command output to file – PowerShell

In PowerShell, you can send command output to a file the same way you can in Command Prompt. Enter the command you want to run and before you tap Enter, add the following at the end. Again, you won’t have to create the text file. PowerShell will do that for you.

> name-of-file.txt

This will save the output file to same directory that PowerShell is currently in. To save the output to a file in a different location, you can specify the path to the folder where you want to save it.

If you want to view the output, you can’t do that at the same time that the file is being created. Once it has been created, run this command and you will be able to view its contents.

Get-Content -Path "path-to-file\file-name.txt"

If you’re wondering whether the output can be saved to a different type of file, the answer is no. Both Command Prompt and PowerShell can only natively write to/create text files and there’s no way to format the output so that when it’s saved to a file, it looks a certain way.

Read How to save command output to file from Command Prompt and PowerShell on Windows 10 by Fatima Wahab on AddictiveTips – Tech tips to make you smarter

How To Get The PowerShell Command History On Windows 10

PowerShell on Windows 10 can give you a history of every command you’ve executed in the current session however, for many users this isn’t enough. They need a history of commands executed across sessions. If you need to get the PowerShell command history, and history for the current session alone doesn’t do the trick, there’s a script and a log file that can help you.

Command History Current Session

If you’re running PowerShell 5, you can get the command history for the current session by running the following command;

Get-History

By default, PowerShell can save up to 50 commands but you can change it to save more. Open PowerShell and right-click the title bar. From the context menu, go to Properties. On the Properties window, go to the Options tab. You will see a Command History section where the default is set to 50. Change it to a higher value.

PowerShell History Log

In order to view the history log, you need to first install the PSReadLine module with the following command;

Install-Module PSReadLine

Next, run the following command and it will return a file location. The file at this location will give you a complete history of every command you’ve run in PowerShell.

(Get-PSReadlineOption).HistorySavePath

Cross-Session PowerShell Command History

This is a bit of a long process but it’s worth it. This solution comes from Intel. First open the following location and check if there is a file named Microsoft.PowerShell_profile.ps1 at this location.

C:\Users\<username>\Documents\WindowsPowerShell

If there’s no file there, open PowerShell and run the following command. It will open your Profile file in Notepad but that file doesn’t exist and PowerShell will tell you as much, and ask if you want to create it. Allow it to create the file.

notepad $Profile

Close the notepad file that opens. In PowerShell, run this command to make sure you’re running PowerShell 5.

$PSVersionTable.PSVersion

Next, set your execution policy to RemoteSigned with the following command.

set-executionpolicy remotesigned

Next, you need to install the PsUrl and PSReadline modules. You can install them with the following command though if you get an error, just install them manually by the process outlined on the linked pages, or try adding the repository as a trusted repository and then running the command again.

install-module PsUrl
install-module PSReadline

Now that those modules have been installed, open this file;

C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Paste the following inside this file, and save it.

$HistoryFilePath = Join-Path ([Environment]::GetFolderPath('UserProfile')) .ps_history
Register-EngineEvent PowerShell.Exiting -Action { Get-History | Export-Clixml $HistoryFilePath } | out-null
if (Test-path $HistoryFilePath) { Import-Clixml $HistoryFilePath | Add-History }
# if you don't already have this configured...
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward

In order to view command history in PowerShell, you need to run the Get-History command however there is one very crucial step to making sure your history is saved. You CANNOT close PowerShell by clicking the close button. Instead you must always close it with the exit command.

You can use the Up and Down arrow keys to cycle through the previous commands.

Read How To Get The PowerShell Command History On Windows 10 by Fatima Wahab on AddictiveTips – Tech tips to make you smarter

How To Automatically Mute Sound When Headphones Are Unplugged On Windows 10

Windows 10 can keep separate audio profiles for different audio devices. For each audio device that you connect, you can set a different volume level and when the device is connected, the volume will adjust automatically. Of course, no one keeps an audio device muted all the time. They will increase or decrease the volume but no one habitually mutes an audio device. If you use a pair of headphones with your desktop, and often have to disconnect them, you can use a little PowerShell script that will automatically mute sound when you unplug your headphones.

This is something that mobile phones do i.e., when you unplug your headphones, the music stops automatically. The logic behind this is that you’re either done listening to music or you’ve accidentally removed your headphones and you need a quick way to turn it off. The script was basically written on that same principle by Prateek Singh of GEEKEEFY.

Automatically Mute Sound

Open Notepad and paste the following;

[cmdletbinding()]
Param()

#Adding definitions for accessing the Audio API
Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume {
// f(), g(), ... are unused COM method slots. Define these if you care
int f(); int g(); int h(); int i();
int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
int j();
int GetMasterVolumeLevelScalar(out float pfLevel);
int k(); int l(); int m(); int n();
int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice {
int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator {
int f(); // Unused
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio {
static IAudioEndpointVolume Vol() {
var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
IMMDevice dev = null;
Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
IAudioEndpointVolume epv = null;
var epvid = typeof(IAudioEndpointVolume).GUID;
Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
return epv;
}
public static float Volume {
get {float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v;}
set {Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty));}
}
public static bool Mute {
get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
}
}
'@ -Verbose


While($true)
{
#Clean all events in the current session since its in a infinite loop, to make a fresh start when loop begins
Get-Event | Remove-Event -ErrorAction SilentlyContinue

#Registering the Event and Waiting for event to be triggered
Register-WmiEvent -Class Win32_DeviceChangeEvent
Wait-Event -OutVariable Event |Out-Null

$EventType = $Event.sourceargs.newevent | `
Sort-Object TIME_CREATED -Descending | `
Select-Object EventType -ExpandProperty EventType -First 1

#Conditional logic to handle, When to Mute/unMute the machine using Audio API
If($EventType -eq 3) 
{
[Audio]::Mute = $true
Write-Verbose "Muted [$((Get-Date).tostring())]"
}
elseif($EventType -eq 2 -and [Audio]::Mute -eq $true)
{
[Audio]::Mute = $false
Write-Verbose "UnMuted [$((Get-Date).tostring())]"
}
}

Save it with the PS1 file extension. Make sure you select ‘All Files’ from the file type dropdown. Give the file a name that will tell you at a glance what it does. Save it some place you’re unlikely to delete it by accident but also where you can find it easily if you need to.

Running The Script

PowerShell can’t just autorun a script. There is a built-in security measure the prevents it from doing so but there’s a way around it. We have a detailed article on how you can do just that. Follow the instructions to auto-run the PowerShell script you just created, and use a scheduled task to start the script every time you boot your PC.

Alternatively, you can manually run the script when you boot your system. I’ve been using it for less than 30 minutes and I don’t know how I was living without it before.

Read How To Automatically Mute Sound When Headphones Are Unplugged On Windows 10 by Fatima Wahab on AddictiveTips – Tech tips to make you smarter