Powershell - 用户机器上是否存在文件 |输出特定文件
Powershell - Does file exist on users machine | output specific file
我有下面的代码检查文件是否存在。如果存在就写一行代码,如果不存在就写另一行代码。
# 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"}
我希望此代码为每个写入主机创建一个输出文件。如果路径为真,则在 c:\true\true.txt 中创建一个文本文件,如果路径错误,则在路径 C:\false\false.txt.
中创建一个 txt
我尝试使用 out-file 但无法正常工作。任何帮助将不胜感激。
谢谢,
史蒂夫
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
}
与一样,如果要在屏幕上写入文件和的字符串,可以使用Tee-Object
:
"Path is OK" |Tee-Object C:\true\true.txt |Write-Host
解决方案完全取决于您想要什么...
要创建空白文本文件,只需使用
# 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-File
替换为new-item -force -type file
要将文本写入文件,请将 ;
替换为 |
。 (如果这两个都是真的,我相信您将需要创建项目,然后将文件导出到新项目。)
我有下面的代码检查文件是否存在。如果存在就写一行代码,如果不存在就写另一行代码。
# 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"}
我希望此代码为每个写入主机创建一个输出文件。如果路径为真,则在 c:\true\true.txt 中创建一个文本文件,如果路径错误,则在路径 C:\false\false.txt.
中创建一个 txt我尝试使用 out-file 但无法正常工作。任何帮助将不胜感激。
谢谢,
史蒂夫
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
}
与Tee-Object
:
"Path is OK" |Tee-Object C:\true\true.txt |Write-Host
解决方案完全取决于您想要什么...
要创建空白文本文件,只需使用
# 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-File
替换为new-item -force -type file
要将文本写入文件,请将 ;
替换为 |
。 (如果这两个都是真的,我相信您将需要创建项目,然后将文件导出到新项目。)