简体   繁体   中英

Need help understanding powershell method

Hello I'm new to Powershell and created a fairly complex code for myself and found out that their's more than one way that I could have written it for example:

$DayLimit = (Get-Date).AddDays(-8)
$Date = Get-Date -Format yyyyMMdd
$Path = Get-ChildItem G:\VLTNAS1_Backup\Active\Nightly\ -Force |
Where-Object { $_.PSIsContainer -eq $True -and $_.CreationTime -lt $DayLimit }

or

ForEach ($Folder in $Path)
{
if($Folder.PSIsContainer -eq $True -and $Folder.CreationTime -lt $DayLimit)
{
Write-Host $Folder
}
}

I Have 2 questions, the first is that I tested both methods out using Write-Host and they print the results differently.

The very first example with the conditions being nested into the variable is that they got printed in a single row for example: Test1 Test2 Test3

The second method I used the results got printed in a single column for example:

Test1

Test2

Test3

Why is that?

My last question is what is the difference from using these two methods, is creating conditions nested within the variable more powerful or vice-versa. I'm just trying to learn more about powershell and accept any help or critique, Thanks.

In the first example, you are assigning all of the output to $Path, and the output simply doesn't contain any line feeds so it all goes into the same line. In the second example, each folder name is output separately by write-host, and write-host creates a new line each time it is run.

Neither method is particularly more powerful, per se, but if it is lengthy script that is likely to need changes in the future, it is often much easier to understand what is going on in the script by avoiding pipelined commands. In your example, it's not really doing that much so it's not a big deal, but if you have several if checks and nested loops, you'll probably want to have more readable code so that debugging and maintenance are easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM