问题描述
我正在使用 powershell 查询远程计算机 C 驱动器上的文件,如果该文件存在状态为成像已完成",则应运行其他检查.
I am using a powershell to query a file on a remote machines C-drive and if the file exist with status 'imaging completed' it should run other checks.
$filetofind = Get-Content C:\Image.log
#Get the list down to just imagestatus and export
foreach ($line in $filetofind)
{
$file = $line.trim("|")
echo $file >> C:\jenkins\imagestatus.txt
}
但是当我运行下面的命令时,我收到了错误消息.有人可以帮忙吗?
But when I run below commands I am getting the error.Can anyone help ?
Get-Content : Cannot find path 'C:\Image.log' because it does not exist.
At line:18 char:15
+ $filetofind = Get-Content C:\Image.log
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Image.log:String) [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
推荐答案
Test-Path
会检查文件是否存在,Select-String
可用于搜索字符串的文件,使用 -Quiet
参数将使命令返回 True
如果找到字符串,而不是返回文本文件中包含该字符串的每一行.
Test-Path
will check if a file exists, and Select-String
can be used to search the file for a string, using the -Quiet
param will make the command return True
if the string is found, rather than returning each line in the text file that includes the string.
然后在简单的 if 语句中使用这两个命令来检查它们的状态:
Then using both commands in simple if statements to check their status:
$file = "C:\Image.log"
$searchtext = "imaging completed"
if (Test-Path $file)
{
if (Get-Content $file | Select-String $searchtext -Quiet)
{
#text exists in file
}
else
{
#text does not exist in file
}
}
else
{
#file does not exist
}
要在多台计算机上检查文件,您需要使用 foreach
循环在每台计算机上分别运行代码.下面假设您在 hostnames.txt 中每行有一个主机名.
To check the file on multiple computers you need to use a foreach
loop to run the code against each computer separately. The below assumes you have one hostname per line in hostnames.txt.
$hostnames = Get-Content "C:\hostnames.txt"
$searchtext = "imaging completed"
foreach ($hostname in $hostnames)
{
$file = "\\$hostname\C$\GhostImage.log"
if (Test-Path $file)
{
if (Get-Content $file | Select-String $searchtext -quiet)
{
Write-Host "$hostname: Imaging Completed"
}
else
{
Write-Host "$hostname: Imaging not completed"
}
}
else
{
Write-Host "$hostname: canot read file: $file"
}
}
这篇关于检查远程机器上文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!