How can I pass a powershell variable into a CMD command?

老子叫甜甜 提交于 2019-12-11 20:19:00

问题


I am trying to run the following command through powershell:

schtasks /query /s $compname /v /fo csv | ConvertFrom-Csv

$compname is set in the first part of the powershell script, but cannot be passed into the command like this. For example, when I try passing in $localhost, I get the following error:

ERROR: Invalid syntax. Value expected for '/s'.
Type "SCHTASKS /QUERY /?" for usage.

Is there a way to pass the variable into this command? I don't plan to change to powershell's native way to access scheduled tasks (through a COM object).


回答1:


Working for me, tested in v2. Does it help if you enclose the variable in double quotes (e.g "$compname") ?

$compname = 'localhost'
schtasks /query /s $compname /v /fo csv | ConvertFrom-Csv



回答2:


Try this:

Invoke-Expression -Command "schtasks /query /s $compname /v /fo csv" | ConvertFrom-Csv


来源:https://stackoverflow.com/questions/13462020/how-can-i-pass-a-powershell-variable-into-a-cmd-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!