lundi 21 décembre 2015

Powershell: Executing $true statement when $false

I am having a bit of trouble with a powershell script. The intent of this is to spider the network and look for files/folders that exist on any PC.

Here is the original source:

#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 "_____________________"

I have changed the if statement to if($Tstpath -eq "True"), if($lastexitcode -eq $true) and if($Tstpath -eq $false) and they all just parse the first {Do command} no matter what. They never drop into }else{. Even tried the Tstpath = test-path \\$computer\c$ as a variable and just running that.

When it parses the first {Do Command} the return is

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], ItemNotFoundExcep 
   tion
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

What does work: If my test machines are on I can ls -path "\\$computer\c$\users\" -Filter $Fltr -recurse | Out-File -Append $Online just fine.

I get True or False from test-path \\$computer\c$ and can even > $var and write-host the results just fine.

I have no idea why this is and would love to know.

This even works

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

But when you add the command ls or Get-childItem it freaks out. So.....question is: Why is it never dropping into the } else { portion?

Aucun commentaire:

Enregistrer un commentaire