我是Powershell的新手,我正在尝试编写一个脚本来检查文件是否存在。如果存在,它将检查进程是否正在运行。
我知道有很多更好的方法可以写这篇文章,但是有人可以给我一个主意吗?
这是我所拥有的:
Get-Content C:\temp\SvcHosts\MaquinasEstag.txt | `
Select-Object @{Name='ComputerName';Expression={$_}},@{Name='SvcHosts Installed';Expression={ Test-Path "\\$_\c$\Windows\svchosts"}}
if(Test-Path "\\$_\c$\Windows\svchosts" eq "True")
{
Get-Content C:\temp\SvcHosts\MaquinasEstag.txt | `
Select-Object @{Name='ComputerName';Expression={$_}},@{Name='SvcHosts Running';Expression={ Get-Process svchosts}}
}
第一部分(检查文件是否存在,运行没有问题。但是检查进程是否正在运行时,我有一个异常(exception):
Test-Path : A positional parameter cannot be found that accepts argument 'eq'.
At C:\temp\SvcHosts\TestPath Remote Computer.ps1:4 char:7
+ if(Test-Path "\\$_\c$\Windows\svchosts" eq "True")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Test-Path], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.TestPathCommand
任何帮助,将不胜感激!
最佳答案
相等比较运算符是-eq
,而不是eq
。 PowerShell中的 bool 值“true”为$true
。并且,如果您想将Test-Path
的结果与您做的事情进行比较,则必须在子表达式中运行cmdlet,否则-eq "True"
将被视为附加选项eq
,并将cmdlet的参数设为"True"
。
更改此:
if(Test-Path "\\$_\c$\Windows\svchosts" eq "True")
到这个:
if ( (Test-Path "\\$_\c$\Windows\svchosts") -eq $true )
或者(更好),由于
Test-Path
已经返回了 bool 值,只需执行以下操作:if (Test-Path "\\$_\c$\Windows\svchosts")
关于用于检查远程计算机列表上是否存在文件的Powershell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18155198/