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

[玩转系统] 周五乐趣:PowerShell 宏

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

周五乐趣:PowerShell 宏


今天的星期五乐趣有点不同,它展示了我几乎每天使用的两种东西:Microsoft Word 和 PowerShell。我几乎每天都在写新的文章和材料,当然这些内容通常与 PowerShell 相关。通常我会使用Word中的博客文章模板,以便于上传。这非常有用,因为我可以在 Word 文档中插入链接,并且在复制到 WordPress 时它们将被保留。我在写作中开始采取的步骤之一是包含 cmdlet 在线帮助的链接。

例如,如果我正在撰写有关 Get-WinEvent 的文章,我将在 cmdlet 名称上包含一个链接。当然,我不会手动获取链接、复制它并在 Word 中创建超链接。因此,我创建了一个 Word 宏,它调用 PowerShell 脚本来获取在线链接并将其作为超链接插入。这就是这一切的运作方式。

有几种方法可以获取给定 cmdlet 的联机帮助链接。您可以使用 Get-Command 检索 HelpUri。

[玩转系统] 周五乐趣:PowerShell 宏

或者您可以使用 Get-Help 检索它。

[玩转系统] 周五乐趣:PowerShell 宏

正如您所看到的,尽管在线内容非常相似,但链接是不同的。但由于如果您在线运行 Get-Help Get-Service,您会得到后者,所以我决定这样做。我整理了一个简单的脚本。

#requires -version 3.0

#Get-HelpOnlineUri.ps1

[cmdletbinding()]

Param(
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a command name")]
[string]$Name
)

Try {
 $help = get-help $name -ErrorAction Stop 
 if ($help.RelatedLinks) {
 [string]$uri = $help | select -expand relatedlinks | select -expand Navigationlink | select -first 1 -expand uri
 #trim it just in case there are spaces
 $uri.trim()
 #send to clipboard as well
 $uri.trim() | clip
 }
 else {
    Write-Warning "No online help links detected for $name"
    #write null to the pipeline
    $null
 }
 
} #try
Catch {
    #write null to the pipeline
    $null
    Throw
    
} #catch

如果找到该函数,则将链接写入管道,否则写入 $Null。我稍后会解释原因。

有了这个脚本,我现在转向 Word 并创建了这个宏。

Sub InsertHelpLink()

Dim r, c, file
Dim cmd As String
Dim link As String
Dim tip As String
Dim iFile As Integer

'get the %temp% path
tempdir = CStr(Environ("temp"))
'define a temporary file
file = tempdir + "\uri.txt"

'selected text
c = ActiveDocument.ActiveWindow.Selection.Text

Debug.Print "Testing for " + c
'the command to run
'YOU MIGHT NEED TO EDIT SCRIPT PATH
cmd = "powershell -nologo -noprofile -command " + Chr(34) + "&{C:\scripts\Get-HelpOnlineUri.ps1 " + c + " | out-file " + file + " -force -encoding Ascii}" + Chr(34)
Debug.Print cmd

'invoke the command
r = shell(cmd, vbHide)

'wait a few seconds for process to complete and file to close
wait = Now() + TimeValue("00:00:02")
Do While Now < wait
Loop

'open the file and read its contents
iFile = FreeFile()

Open file For Input As #iFile

Do While Not EOF(iFile)
  Line Input #iFile, link
Loop

Close #iFile
Debug.Print link

'define the screentip
tip = "Read online help for " + c
Debug.Print tip

'insert the link
If Len(link) > 0 Then
    ActiveDocument.ActiveWindow.Selection.Hyperlinks.Add Anchor:=Selection.Range, Address:=link, SubAddress:="", _
        ScreenTip:=tip, TextToDisplay:=c, Target:="_blank"
Else
Debug.Print "no link found"
End If

End Sub

我找不到捕获 PowerShell 命令输出的方法,因此我最终创建了一个包含该链接的临时文件。如果未找到任何内容,则文件长度将为 0。我发现这更容易,因为宏读取文件并将内容保存到变量link。如果链接的长度> 0,则Word将插入超链接,并带有构造的屏幕提示。

我将宏存储在 Normal.dot 中,因此我始终可以使用它。

[玩转系统] 周五乐趣:PowerShell 宏

我什至在文件 - 选项 - 自定义功能区下给了它一个键盘快捷键

[玩转系统] 周五乐趣:PowerShell 宏

找到方法来自动完成一天中沉闷的任务是非常有价值的,而且我几乎总是学到新的东西。希望你做到了。

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

取消回复欢迎 发表评论:

关灯