I'm new at Powershell, and I'm trying to write a script that checks if a file exists; if it does, it checks if a process is running. I know there are much better ways to write this, but can anyone please give me an idea? Here's what I have:
我是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}}
}
The first part (check if the file exists, runs with no problem. But I have an exception when checking if the process is running:
第一部分(检查文件是否存在,运行没有问题。但是在检查进程是否正在运行时我有一个例外:
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
Any help would be appreciated!
任何帮助,将不胜感激!
1 个解决方案
#1
18
The equality comparison operator is -eq
, not eq
. The boolean value "true" in PowerShell is $true
. And if you want to compare the result of Test-Path
to something the way you do, you must run the cmdlet in a subexpression, otherwise -eq "True"
would be treated as an additional option eq
with the argument "True"
to the cmdlet.
等式比较运算符是-eq,而不是eq。 PowerShell中的布尔值“true”为$ true。如果要将Test-Path的结果与您的方式进行比较,则必须在子表达式中运行cmdlet,否则-eq“True”将被视为附加选项eq,其参数为“True”小命令。
Change this:
改变这个:
if(Test-Path "\\$_\c$\Windows\svchosts" eq "True")
into this:
进入这个:
if ( (Test-Path "\\$_\c$\Windows\svchosts") -eq $true )
Or (better yet), since Test-Path
already returns a boolean value, simply do this:
或者(更好),因为Test-Path已经返回一个布尔值,只需执行以下操作:
if (Test-Path "\\$_\c$\Windows\svchosts")
#1
18
The equality comparison operator is -eq
, not eq
. The boolean value "true" in PowerShell is $true
. And if you want to compare the result of Test-Path
to something the way you do, you must run the cmdlet in a subexpression, otherwise -eq "True"
would be treated as an additional option eq
with the argument "True"
to the cmdlet.
等式比较运算符是-eq,而不是eq。 PowerShell中的布尔值“true”为$ true。如果要将Test-Path的结果与您的方式进行比较,则必须在子表达式中运行cmdlet,否则-eq“True”将被视为附加选项eq,其参数为“True”小命令。
Change this:
改变这个:
if(Test-Path "\\$_\c$\Windows\svchosts" eq "True")
into this:
进入这个:
if ( (Test-Path "\\$_\c$\Windows\svchosts") -eq $true )
Or (better yet), since Test-Path
already returns a boolean value, simply do this:
或者(更好),因为Test-Path已经返回一个布尔值,只需执行以下操作:
if (Test-Path "\\$_\c$\Windows\svchosts")