我在PowerShell脚本中遇到了一些麻烦。这样做的目的是蜘蛛网络,并寻找任何PC上存在的文件/文件夹。
这里是原始来源:
#FiToFin Script#
$Fltr = "how_recover*.*"
$Online = "C:\Users\<username>\Scripts\Logs\Online.log"
$CSV = "C:\Users\<username>\Scripts\Devices.csv"
#$Tstpath = test-path "\\$computer\c$"
$Offline = "C:\Users\<username>\Scripts\Logs\Offline.log"
##################################################
$devices = Get-Content "$CSV"
foreach ($computer in $devices) {
Test-Path "\\$computer\c$" > $Tstpath
if ($Tstpath -eq $True) {
ls -Path "\\$computer\c$\users" -Filter $Fltr -Recurse |
Out-File -Append $Online
} else {
Write-Host "$computer is NOT Online" | Out-File -Append $Offline
}
}
##################################################
Write-Host "_____________________"
Write-Host "Online file = $Online"
Write-Host "Offile file = $Offline"
Write-Host "_____________________"
我已经改变了if
声明if($Tstpath -eq "True")
,if ($lastexitcode -eq $true)
和if($Tstpath -eq $false)
,他们都只是解析第一个{Do command}
不管。他们永远不会掉入else
。甚至试图将Tstpath = Test-Path \\$computer\c$
作为一个变量,然后运行它。
当解析第一个{Do Command}
回报是
ls : Cannot find path '\\<computerName>\c$\u' because it does not exist.
At C:\Users\<username>\Scripts\FiToFin.ps1:19 char:3
+ ls -Path "\\$computer\c$\users" -Filter $Fltr -Recurse | Out-File -Append $On ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\<computername>\c$\u:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
什么工作:
如果我的测试机器上,我可以ls -Path "\\$computer\c$\users" -Filter $Fltr -Recurse | Out-File -Append $Online
就好了。
我从Test-Path \\$computer\c$
True
或False
和甚至可以> $var
和Write-Host
结果就好了。
我不知道这是为什么,并希望知道。
这也适用于:
###################################################################
$computer = "TestPC"
$Tstpath = Test-Path \\$computer\c$
####################################################################
$Tstpath > $null
if($Tstpath -eq $True) {
Write-Host "$computer is Online"
} else {
Write-Host "$computer is NOT Online"
}
但是当你添加的命令ls
或Get-ChildItem
它怪胎。 所以,问题是:为什么它永远不会执行else
部分?
为什么还要保存结果呢?你有几个处理问题,但主要是'$ Tstpath'的值永远不会改变。 'if(test-path“\\ $ computer \ c $”){}' – Matt
保存结果可以看到文件在〜2k机器上的位置。为什么它没有改变?底部工作的很好,但是当你把'ls'放在'$ true'上时,它立即刹车。 – Benny
我的意思是'test-path'的结果。如果你的成功,那么你知道它通过与否。我通过跳过一些冗余逻辑来帮助你。只需将测试放在'if'中 – Matt