如果可以运行包含选项的命令,如何使用Powershell进行验证?

时间:2014-07-06 10:01:17

标签: powershell

跟进this question

执行

if ( get-command java -erroraction silentlycontinue ) {
  "Command was found"
}
else {
  "Command was not found"
}
运行

时,

会产生Command was found

if ( get-command "java -version" -erroraction silentlycontinue ) {
  "Command was found"
}
else {
  "Command was not found"
}

返回Command was not found

1 个答案:

答案 0 :(得分:4)

Get-Command查找命令(即可执行程序,cmdlet,函数,这些东西的别名等),而不是构成要执行的有效命令行的事物。如果你想要,你只需要尝试执行它:

try {
  $javaVersion = java -version
  Write-Host Java found with version $javaVersion
} catch {
  Write-Host Command was not found
}

当然,应该注意,无论你在那里尝试执行什么都不会做任何你可能会后悔的事情。