Quick & Dirty way to run PowerShell as a scheduled task

The PowerShell execution policy is there to protect us but not to stop us from doing the ‘not so best practice‘ things.

Best practice would be to sign all your scripts with a code signing certificate, and by using ISE Steroids this makes this process much much easier with the click of a button.

However there are times you just want to run a PowerShell script ‘as is‘ with the guarantee it will run – bearing in mind the default behaviour of a computer is Remote Signed meaning a PowerShell script from any remote source needs to be signed with a trusted certificate.

This is how you can do it on those ad-hoc occasions:

powershell.exe -ExecutionPolicy Unrestricted -File C:\script.ps1

And you can pop it into a scheduled task:


Below is an example how to map a network drive to Azure Files using PowerShell:

$net1 = new-object ComObject WScript.Network
$net2 = new-object ComObject Shell.Application
$net1.RemoveNetworkDrive("m:", $True, $True)
Start-Sleep Seconds 2
$net1.MapNetworkDrive("m:", "\\<StorageAccountName>.file.core.windows.net\music", $true, "<StorageAccountName>", "<StorageAccountKey>")
$net2.NameSpace('m:').Self.Name = "Drive 1 Label"
$net1.RemoveNetworkDrive("n:", $True, $True)
Start-Sleep Seconds 2
$net1.MapNetworkDrive("n:", "\\<StorageAccountName>.file.core.windows.net\music", $false, "<StorageAccountName>", "<StorageAccountKey>")
$net2.NameSpace('n:').Self.Name = "Drive 2 Label"

Save this script above as c:\M-Drive.ps1 (as an example).

Below is an example on how to add this PowerShell script as a scheduled task to ensure it is run as part of the user context.

$ShedService = New-Object comobject 'Schedule.Service'
$Task = $ShedService.NewTask(0)
$Task.RegistrationInfo.Description = 'M-Drive Mapping'
$Task.Settings.Enabled = $true
$Task.Settings.AllowDemandStart = $true
$trigger = $task.triggers.Create(9)
$trigger.Enabled = $true
$action = $Task.Actions.Create(0)
$action.Path = 'PowerShell.exe'
$action.Arguments = '-ExecutionPolicy Unrestricted -File c:\M-Drive.ps1'
# $action.WorkingDirectory = ''
$taskFolder = $ShedService.GetFolder("\")
$taskFolder.RegisterTaskDefinition('M-Drive Mapping', $Task , 6, 'Users', $null, 4)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s