Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

windows - How to test what started a powershell script

I have a PowerShell script that can be started either by

  • running a shortcut on the desktop, OR
  • as a scheduled job from the windows Task Scheduler.

Is there any way within the script itself of identifying how it was started? In practice each method produces a slowly scrolling command window on screen, and once it's running I have no way of knowing how it was initiated. The script already logs some data about itself (name, date, time and $PID) but so far I've not found how to test the launch method i.e. task scheduler or manual run.

question from:https://stackoverflow.com/questions/65893468/how-to-test-what-started-a-powershell-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A script that is run by Task Scheduler has a parent process whose name is svchost, so you can use the following code in your script to detect this:

'svchost' -eq (Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessID = $pid").ParentProcessId).Name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...