Home > front end >  How to set up a Powershell script in order to run it every day
How to set up a Powershell script in order to run it every day

Time:07-29

I'm trying to set up a powershell script that mounts/umounts my external hard drive depending on the time. I just need it to run before (mount) and after (umount) a backup execution.

The commands I need to tun are:

Get-Disk | Where-Object UniqueId -Eq '3074478411965382' | Set-Disk -isreadonly $false
Get-Disk | Where-Object UniqueId -Eq '3074478411965382' | Set-Disk -IsOffline $false

and the other script is:

Get-Disk | Where-Object UniqueId -Eq '3074478411965382' | Set-Disk -isreadonly $True
Get-Disk | Where-Object UniqueId -Eq '3074478411965382' | Set-Disk -IsOffline $true

I tried to put each couple of commands in a file with ps1 extension, and then, configure a scheduler task in order to run them one minute before, and after the backup execution, but nothing happens.

I tried to create the scheduler task this way:

$User= "NT AUTHORITY\SYSTEM" # Specify the account to run the script
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\PS\StartupScript.ps1" # Specify what program to run and with its parameters
Register-ScheduledTask -TaskName "MonitorGroupMembership" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force # Specify the name of the task```

Is there anything I'm missing? I already configured my computer in order to be able to run ps1 scripts

Set-ExecutionPolicy Unrestricted

Thank you very much in advance

CodePudding user response:

Hi i would always add -NoProfile -NonInteractive -ExecutionPolicy Bypass in a scheduled task. Maybe the missing -File is your problem

$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\PS\StartupScript.ps1" # Specify what program to run and with its parameters

CodePudding user response:

I changed the script in order to run your way, like this

$Trigger= New-ScheduledTaskTrigger -At 10:00am –Daily 

$User= "NT AUTHORITY\SYSTEM" 

$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File 'E:\COSAS\PROGRAMAS\Utilidades\Uranium Backup\Uranium-Conf\activar_disco.ps1'" 
Register-ScheduledTask -TaskName "Activadisco" -Trigger $Trigger -User $User -Action $Action -RunLevel Highest –Force

But it keeps failing. If I run it directly in powershell, it works. Any other idea? Thanks a lot!strong text

  • Related