简体   繁体   English

获取在 PowerShell 脚本上执行的最后一条命令

[英]Get the last command executed on a PowerShell script

I'm updating the logging function I use for all my scripts and making it compatible with the SCCM logging viewer.我正在更新我用于所有脚本的日志记录 function 并使其与SCCM日志记录查看器兼容。

Under the fields that the SCCM viewer takes is the component field, and I'll like to fill it with the main command that it's run and I'm logging.在 SCCM 查看器使用的字段下是组件字段,我想用它运行和记录的主要命令填充它。 For example, if I'm logging "Data copied" and I did that with Copy-Item , I'd like that the logs says Copy-Item for that line of the log.例如,如果我正在记录“数据已复制”并且我使用Copy-Item进行了记录,我希望日志中的那一行日志显示为 Copy-Item 。

So far I've tested the following methods, using $$ and the history cmdlets ( Get-History , Add-, etc.), but they only work with the PowerShell console, not with script execution.到目前为止,我已经使用$$和历史 cmdlet( Get-History 、Add- 等)测试了以下方法,但它们仅适用于 PowerShell 控制台,不适用于脚本执行。

The final result I'd like to get is:我想得到的最终结果是:

在此处输入图像描述

I think this is what you're talking about?我想这就是你说的?

$Folder = "some path" $Folder = "一些路径"

$Cmdline = 'Remove-Item $Folder -Force -Recurse' $Cmdline = '删除项目 $Folder -Force -Recurse'
Invoke-Expression $Cmdline调用表达式 $Cmdline
Write-Host $Cmdline.replace("`$Folder",$Folder)写主机 $Cmdline.replace("`$Folder",$Folder)

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

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