缩短现有的类方法调用

时间:2019-08-27 17:24:01

标签: powershell

我目前用PowerShell编写以下代码。 基本上使脚本每隔几分钟按一次键盘上的空格键。

Add-Type -AssemblyName System.Windows.Forms.SendKeys

# Interval in seconds between two consecutive keypresses
$interval = 300 # == 5 minutes
# String code for key to press.
$Key = " " # Hit spacebar

Write-Host "Pressing key for the first time in 10 seconds"
Start-Sleep -Seconds 10 # Key will be pressed once 10 seconds after execution to confirm the script is running.
While ($true) {
    [System.Windows.Forms.SendKeys]::SendWait($Key)
    Write-Host "Sleeping $interval seconds"   
    Start-Sleep -Seconds $interval
}

我对此脚本不满意的是,我必须使用这种长符号来调用“ SendKeys”方法:

[System.Windows.Forms.SendKeys]::SendWait($Key)

我想找到一种简单的方法来调用它,只需使用:

SendKeys::SendWait($Key)

我究竟如何“导入”类SendKeys以使表示法更短。 我一直在互联网上寻找,但找不到解决方案。 在这一点上,我想知道是否有可能。

如果有人可以帮助我,将不胜感激。并不是说它会改变脚本的功能,但至少我很高兴知道它是如何完成的。

预先感谢, 亲切的问候, Insannik

1 个答案:

答案 0 :(得分:1)

在PowerShell v5 +中,您可以使用using指令:

using namespace System.Windows.Forms

Add-Type -AssemblyName System.Windows.Forms

[SendKeys]::SendWait(' ')

注意:using语句必须是脚本中的第一个非注释项。

或者,您可以将类型分配给变量并使用静态调用语法:

$s = [System.Windows.Forms.SendKeys]

$s::SendWait(' ')

顺便说一句,System总是被导入,可以忽略类型路径:

[Windows.Forms.SendKeys] # valid