2017-04-18 4 views
0

ファイルが存在するかどうかを調べる以下のコードがあります。存在していれば、1行のコードを書き込み、それ以外の行のコードを書き込むことはありません。Powershell - ファイルはユーザーマシンに存在しますか?出力特定のファイル

# PowerShell Checks If a File Exists 
$WantFile = "C:\Windows\System32\oobe\info\backgrounds\backgroundDefault.jpg" 
$FileExists = Test-Path $WantFile 
If ($FileExists -eq $True) {Write-Host "Path is OK"} else {Write-Host "Path is wrong"} 

このコードでは、書き込みホストごとに出力ファイルを作成したいと考えています。パスがtrueの場合は、c:\ true \ true.txtにテキストファイルを作成し、パスが間違っている場合は、パスC:\ false \ false.txtにtxtを作成します。

私はアウトファイルを使用しようとしましたが、動作させることができませんでした。どんな助けもありがとう。

おかげで、

スティーブ

答えて

2

Write-Hostコマンドレットは、それは(あなたの場合、おそらくコンソールでの)ホストアプリケーションに直接出力です書き込みます。

だけOut-Fileに直接パイプあなたの文字列を削除します。

:あなたが画面上 をファイルに書かれた文字列をしたい場合は

$WantFile = "C:\Windows\System32\oobe\info\backgrounds\backgroundDefault.jpg" 
$FileExists = Test-Path $WantFile 
# $FileExists is already either $true or $false 
if ($FileExists) { 
    # write to \true\true.txt 
    "Path is OK" |Out-File C:\true\true.txt 
} 
else { 
    # write to \false\false.txt 
    "Path is wrong" |Out-File C:\false\false.txt 
} 

TheMadTechnician notesとして、あなたはTee-Objectを使用することができます

"Path is OK" |Tee-Object C:\true\true.txt |Write-Host 
+0

もし両方が欲しいなら... "Path is OK" | TeeオブジェクトC:\ Path \ To \ True.log [-append] | Write-Host' – TheMadTechnician

+0

@TheMadTechnician ++が答えを更新します –

0

解決策は、正確に何をしたいかによって決まります。

ディレクトリが存在しない場合は、単に

# PowerShell Checks If a File Exists 
$WantFile = "C:\Windows\System32\oobe\info\backgrounds\backgroundDefault.jpg" 
$FileExists = Test-Path $WantFile 
If ($FileExists -eq $True) {Write-Host "Path is OK"; Out-File C:\true\true.txt} else {Write-Host "Path is wrong"; Out-File C:\false\false.txt} 

を使用し、空白のテキストファイルを作成するには、|;を置き換え、ファイルにテキストを書き込むにはnew-item -force -type file

Out-Fileを交換します。 (これらの両方が当てはまる場合は、アイテムを作成し、次にOut-FileをNew-Itemに作成する必要があると思います)

関連する問題