2017-02-21 53 views
1

我正在使用PowerShell查詢遠程計算機C驅動器上的文件,如果文件存在狀態爲「映像已完成」,它應該運行其他檢查。檢查遠程計算機上的文件中的文本

$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 
    } 

但是,當我運行下面的命令我得到的錯誤。 任何人都可以幫忙嗎?

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 
+0

使用的測試路徑,以確保文件是存在的 –

+0

我想,以確保文件是存在的,需要讀取文件來檢查image.log文件更新狀態與其他檢查進行。如何可以在這裏修復 – SNair

回答

2

Test-Path會檢查文件是否存在,以及Select-String可以用來搜索字符串的文件,使用-Quiet PARAM將使命令返回True如果字符串被發現,而不是在返回的每一行包含字符串的文本文件。

然後用簡單的兩個命令if語句來檢查它們的狀態:

$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中每行有一個主機名。

$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" 
    } 
} 
+0

謝謝詹姆斯。它的工作很好local.But當我嘗試相同的遠程它不工作。這是$文件= 「C:\ GhostImage.log」 如何 $ SEARCHTEXT = 「成像完成:」 $主機=獲取內容「C:\ hostnames.txt 如果(測試的路徑$文件) { 如果(獲取內容 - $主機名$文件|選擇字符串$ SEARCHTEXT -Quiet) 其他 { 回聲 '文本文件不存在' }} { 回聲 '文本文件存在'} else { echo'文件不存在' } – SNair

+0

'Get-Content'不能除了這樣的主機名,請參閱我的編輯。 –

+0

非常感謝。它工作完美 – SNair

相關問題