简体   繁体   English

Linux Cronjob 未运行 powershell 脚本,但该脚本能够在终端中运行

[英]Linux Cronjob not running powershell script, but the script is able to run in terminal

I have a PowerShell Script that updates a database table.我有一个更新数据库表的 PowerShell 脚本。 I would like to set this up in the Cronjob to run daily.我想在 Cronjob 中设置它以每天运行。 However it doesnt seem to work in the cronjob.但是它似乎在 cronjob 中不起作用。 At the moment I have setting it forward a couple minutes so that I dont have to wait.目前我已将其设置为几分钟,这样我就不必等待。

CronTab:定时标签:

* * * * * pswh -File "/home/administrator/PowerShellScripts/Update-Set-Table.ps1"

Terminal:终端:

pswh -File "/home/administrator/PowerShellScripts/Update-Set-Table.ps1"

Working perfectly when I run that command in the terminal but it doesnt seem to be running from the cronjob.当我在终端中运行该命令时工作完美,但它似乎不是从 cronjob 运行的。

you need to specify the full path to the executable pwsh .您需要指定可执行文件pwsh的完整路径。 you can do so by using which APPNAME in a terminal.您可以通过在终端中使用which APPNAME来实现。

which pwsh

then change the line in your crontab accordingly.然后相应地更改 crontab 中的行。 for me the working result looks like this:对我来说,工作结果如下所示:

* * * * * /snap/bin/pswh -File "/home/administrator/PowerShellScripts/Update-Set-Table.ps1"

Cron's lack of environment has this side effect: the working directory changes. Cron 缺乏环境有这样的副作用:工作目录发生变化。 In my case I was writing to a file I expected to be in the script's directory which was being created & written to nicely in $HOME.在我的情况下,我正在写入一个我希望位于脚本目录中的文件,该文件正在 $HOME 中创建并很好地写入。

The script's directory is held in the PoSh variable $PSScriptRoot脚本的目录保存在 PoSh 变量$PSScriptRoot

PoSh has a symlink at /usr/bin/pwsh so the full path is not necessary (for me anyway) PoSh 在/usr/bin/pwsh pwsh 有一个符号链接,所以不需要完整路径(无论如何对我来说)

The current (Vixie) cron allows standard variables which can be used for paths.当前(Vixie)cron 允许可用于路径的标准变量。 Check the author in man crontabman crontab查看作者

If you're script has a #!/usr/bin/pwsh shebang & is executable it executes like any script without specifying 'pwsh'如果你的脚本有一个#!/usr/bin/pwsh shebang & 是可执行的,它会像任何脚本一样执行而不指定 'pwsh'

BTW if you're displaying to screen, say a dialog, the cron job must be prefaced with env DISPLAY=:0 (or some other number) in order to display.顺便说一句,如果您要显示到屏幕上,例如对话框,则 cron 作业必须以env DISPLAY=:0 (或其他一些数字)开头才能显示。 eg env DISPLAY=:0 pwsh $ScriptHome/DiskFull-WereGoingToCrash.ps1 -display例如env DISPLAY=:0 pwsh $ScriptHome/DiskFull-WereGoingToCrash.ps1 -display

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM