powershellscriptinglog-filesfilterxml

Adding space between paths in powershell


I'm having a problem with my script that filters trough my logs and opens relevant ones in baretail. My problem at the moment is that some of the filepaths are printing without spaces in between and some have the space. I have been trying to get the spaces by putting + "" + but that does absolutely nothing.

picture of output

My code

$files = ""
[xml]$photonconfig = Get-Content 
C:\Users\Administrator\Desktop\PhotonServer.config

$photonconfig.SelectNodes("Configuration/*")  | Select-Object -Expand Name | 
% {$_.replace("CriticalOps","")} | ForEach {
$files+= Write-Host ""
$files+= Get-ChildItem C:\Users\Administrator\Desktop\log\log/*$_*.log |sort -property LastWriteTime -Descending | Select-Object -first 3 


}

$clr= Get-ChildItem  C:\Users\Administrator\Desktop\log\log/PhotonCLR.log | 
Select-Object 

$all = $files + $clr 

$all

Complete code:

 $files = @()
 [xml]$photonconfig = Get-Content 
 C:\Users\Administrator\Desktop\PhotonServer.config

 $photonconfig.SelectNodes("Configuration/*")  | Select-Object -Expand Name | % {$_.replace("CriticalOps","")} | ForEach {
 $files+= Write-Output ""
 $files+= Get-ChildItem C:\Users\Administrator\Desktop\log\log/*$_*.log |sort -property LastWriteTime -Descending | Select-Object -first 3 


}

$clr= Get-ChildItem  C:\Users\Administrator\Desktop\log\log/PhotonCLR.log | Select-Object 

$all = "$clr " + "$files" 

$cmd=Start-Process C:\Users\Administrator\Desktop\baretail\baretail.exe $all

Solution

  • Take the following object types in consideration:

    PS D:\PShell> (Get-ChildItem).GetType().FullName
    System.Object[]
    
    PS D:\PShell> (Get-ChildItem)[0].GetType().FullName
    System.IO.DirectoryInfo
    
    PS D:\PShell> (Get-ChildItem)[-1].GetType().FullName
    System.IO.FileInfo
    
    PS D:\PShell> "".GetType().FullName
    System.String
    
    PS D:\PShell> ( Write-Host "" ) -eq $null
    
    True
    

    Therefore, there comes some automatic type casting e.g. in $files+= Get-ChildItem …

    1. Use array $files = @() instead of string $files = "".
    2. Avoid using Write-Host at all.
    3. Consider the difference between the two type casting approaches:
      • [xml]$photonconfig = Get-Content C:\…\Desktop\PhotonServer.config would strongly type the variable $photonconfig
      • $photonconfig = [xml]$( Get-Content C:\…\Desktop\PhotonServer.config ) (I'd prefer this variant)