当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 星期五乐趣:挠痒痒我的 PowerShell!

作者:精品下载站 日期:2024-12-14 07:46:29 浏览:14 分类:玩电脑

星期五乐趣:挠痒痒我的 PowerShell!


我在家为自己工作,这意味着我必须充当自己的助手,提醒我重要的事件和任务。有时我需要一点帮助。那么为什么不使用 PowerShell 呢?过去,我曾使用过并撰写过有关使用后台作业等待一定分钟数,然后使用 MSG.EXE 命令行实用程序显示弹出消息的文章。我之前的方法的缺点是,如果我关闭 PowerShell 会话,我就会失去后台作业。在接下来的 10-30 分钟内提醒也许没问题。但对于长期提醒,我需要更好的解决方案。

我不知道为什么我没有从一开始就走这条路,但我可以使用 PowerShell 计划作业来完成相同的结果。 PowerShell 计划作业通过任务计划程序运行,这意味着它会在 PowerShell 外部持续存在。我真正需要的只是三件事:

  1. 开始任务的时间
  2. 要运行的命令
  3. 已注册的预定作业对象

开始的时间是工作触发器。以下是我如何创建 30 分钟后的触发器。我的提醒只需要运行一次。

$trigger = New-Jobtrigger -Once -at (Get-Date).AddMinutes(30)

该命令将是 MSG.EXE 命令。

$cmd = "msg.exe $env:username Important phone call in 5 minutes"

这需要采用脚本块的形式。

$sb = {
Param($cmd,$jobname)
Invoke-Expression $cmd
#forcibly remove the scheduledjob
Get-ScheduledJob -Name $jobname | Unregister-ScheduledJob -Force
}

在我的脚本块中,我还将删除预定的作业。最后我需要注册它。

$jobname = "phone call"
Register-ScheduledJob -ScriptBlock $sb -Name $jobName -MaxResultCount 1 -Trigger $Trigger -ArgumentList $cmd,$jobname

当时间到来时,我的屏幕上会出现一条弹出消息。

[玩转系统] 星期五乐趣:挠痒痒我的 PowerShell!

您可以配置消息在自动消失之前显示的时间。这是该过程的重要部分。这是定义函数的完整脚本,包括可选的别名。

#requires -version 4.0
#requires -module PSScheduledJob

Function New-ScheduledReminderJob {

<#
.Synopsis
Create a scheduled reminder background job.
.Description
This command uses the MSG.EXE command line tool to send a reminder message to the currently logged on user, presumably yourself. The intention is to set ad-hoc popup reminders for the current user. The message will automatically dismiss after 1 minute unless you use the Wait parameter.

You can schedule the reminder for a certain number of minutes set the reminder to run at a specific date and time. The default is to schedule a reminder in 1 minute.

The function creates a scheduled background job so that you can close your PowerShell session without losing the job as well as persisting during reboots. The scheduled job will be removed upon completion. 

.Parameter Message
The text to display in the popup.
.Parameter Time
The date and time to display the popup. If you enter just a time, it will default to the current day. See examples. 
This parameter has aliases of date and dt. 
.Parameter JobName
A name to assign to the job. If you don't specify a name, the function will use the name Reminder-N where N is an incrementing counter starting at 1. This parameter has an alias of Name.
.Parameter Minutes
The number of minutes to wait before displaying the popup message.
.Parameter Wait
The number of minutes to display the message before it automatically is dismissed. The default is 1 minute.
.Example
PS C:\> new-scheduledreminderjob "Switch over laundry" -minutes 40 -name SwitchLaundry

Id         Name            JobTriggers     Command                                  Enabled   
--         ----            -----------     -------                                  -------   
1          SwitchLaundry   1               ...                                      True

This command creates a new job that will display a message in 40 minutes
.Example
PS C:\> new-scheduledreminderjob "Go home" -time "5:00PM" -wait 2 | out-null

Create a reminder to be displayed at 5:00PM today for 2 minutes but don't display the job result.

.Notes
Last Updated: July 24, 2015
Version     : 2.2
Author      : Jeff Hicks (@JeffHicks)
              https://jdhitsolutions.com/blog

Learn more about PowerShell:
Essential PowerShell Learning Resources

  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************

.Link
msg.exe
Register-ScheduledJob
.Inputs
None
.Outputs
ScheduledJob
#>

[cmdletbinding(DefaultParameterSetName="Minutes",SupportsShouldProcess)]
Param(
[Parameter(Position=0,Mandatory,HelpMessage="Enter the alert message text")]
[string]$Message,
[Parameter(ParameterSetName="Time")]
[ValidateNotNullorEmpty()]
[Alias("date","dt")]
[datetime]$Time,
[Parameter(ParameterSetName="Minutes")]
[ValidateNotNullorEmpty()]
[int]$Minutes = 1,
[Alias("Name")]
[string]$JobName,
[int]$Wait = 1
)

Begin {
    Write-Verbose -Message "[Starting] $($MyInvocation.Mycommand)"  
   
} #begin

Process {
 Write-Verbose -Message "[Trace] Parameter set = $($PSCmdlet.ParameterSetName)"
    If ($PSCmdlet.ParameterSetName -eq 'Minutes') {
     #calculate the scheduled job time from the number of minutes
     [datetime]$Time= (Get-Date).AddMinutes($minutes)
    }

    #create the scheduled job trigger
    $Trigger = New-JobTrigger -At $Time -Once
    Write-Verbose "[Trace] Reminder Time = $Time"

    if (-Not $JobName) {
        #get last job ID to build the jobname
        #ignore any errors if job not found
        Write-Verbose "[Status] Checking for previous Reminder scheduled jobs"
        $lastjob = Get-ScheduledJob -Name "Reminder*" -ErrorAction SilentlyContinue | sort ID | select -last 1
    
        if ($lastjob) {
            #define a regular expression
            [regex]$rx ="\d+$"
            #extract the counter number
            [string]$counter = ([int]$rx.Match($lastJob.name).Value +1)
        }
        else {
            [string]$counter = 1
        }
        #define the job name
        $jobName = "Reminder-$Counter"
    } #if no job name specified

    Write-Verbose -Message "[Trace] Jobname = $jobname"
    
    #define the msg.exe expression   
    [int]$WaitTime = $Wait * 60
    Write-Verbose "[Trace] Display Wait time = $WaitTime seconds"
    Write-Verbose "[Status] Defining expression"
    [string]$cmd = "msg.exe $env:username /Time:$WaitTime $Message"
    
    Write-Verbose "[Trace] Command to execute = $cmd"
    
    #the scriptblock to run
    $sb = {
    Param($cmd,$jobname)
    Invoke-Expression $cmd
    #forcibly remove the scheduledjob
    Get-ScheduledJob -Name $jobname | Unregister-ScheduledJob -Force
    }

    Write-Verbose "[Trace] Scriptblock = $($sb | Out-String)"

    #add some options to support laptop users
    Write-Verbose "[Status] Creating scheduled job options"
    $options = New-ScheduledJobOption -ContinueIfGoingOnBattery -WakeToRun

    #create the scheduled job
    Write-Verbose "[Status] Registering the scheduled reminder job"
    Register-ScheduledJob -ScriptBlock $sb -Name $jobName -MaxResultCount 1 -Trigger $Trigger -ArgumentList $cmd,$jobname
 
} #process

End {
    Write-Verbose -Message "[Status] Ending $($MyInvocation.Mycommand)"
} #end

} #end function

#add an alias
Set-Alias -Name Tickle -Value New-ScheduledReminderJob

现在我可以轻松地为自己设置提醒,甚至是明天、下周或下个月的提醒。我可以使用计划作业 cmdlet 来管理我的提醒。我写这篇文章的假设是您正在为自己设置弹出提醒。

让我知道你的想法。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯