2017-04-18 63 views
0

我有下面的代码检查文件是否存在。如果它存在,它会写入一行代码,如果它不写入另一行代码。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。

我试过使用out-file,但无法让它工作。任何帮助,将不胜感激。

感谢,

史蒂夫

回答

2

Write-Host cmdlet将写入它的直接输出到主机应用程序(在你的情况可能是控制台)。

只需直接删除它,管你的字符串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

如果他同时想要两个...''路径正常“| Tee-Object 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} 

如果该目录不存在,交换Out-Filenew-item -force -type file

将文本写入文件,与|更换;。 (如果这两个都是真的,我相信你将需要创建该项目,并随后将Out-File添加到New-Item中。)

相关问题