Powershell - writing and listing things


Hello World script from Powershell command line

# to execute at Powershell command line: PS C:\Windows> &"C:\test\hello_world.ps1"
Write-Host "Hello World"

Hello World script from batch (.bat) file

# to execute a powershell script within a batch file  
Powershell.exe -executionpolicy remotesigned -File  "C:\trash\hello_world.ps1"

List files and directories starting from specific directory

$myDirectory = "c:\tests"
Get-ChildItem -Path $myDirectory

List files and directories starting from specific directory with subdirectories - recursively

$myDirectory = "c:\tests"
Get-ChildItem -Recurse  $myDirectory
output:
    Directory: C:\tests
 
 
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        2023-02-27   3:41 PM                test1_dir
d-----        2023-02-27   3:41 PM                test2_dir
d-----        2023-02-27   3:41 PM                test3_dir
-a----        2023-02-27   4:09 PM              0 new_file.txt
 
 
    Directory: C:\tests\test1_dir
 
 
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2023-02-27   3:41 PM              0 file1.txt
-a----        2023-02-27   3:41 PM              0 file2.txt
-a----        2023-02-27   3:41 PM              0 file3.txt
 
...

List only files starting from specific directory with subdirectories - recursively -

Note: ! $_.PSIsContainer excludes directories

$myDirectory = "c:\tests"
Get-ChildItem -Recurse $myDirectory | Where { ! $_.PSIsContainer }

...Showing specific attributes only

# to execute: PS C:\Windows> &"C:\tests_master\ps_01.ps1"
$myDirectory = "c:\tests"
Get-ChildItem -Recurse $myDirectory | Where { ! $_.PSIsContainer }  | Select Name, FullName, Length
ouput:
 
Name          FullName                         Length
----          --------                         ------
new_file.txt  C:\tests\new_file.txt                 0
file1.txt C:\tests\test1_dir\file1.txt      0
file2.txt C:\tests\test1_dir\file2.txt      0
file3.txt C:\tests\test1_dir\file3.txt      0
file4.txt C:\tests\test2_dir\file4.txt      0
file5.txt C:\tests\test3_dir\file5.txt      0   
 

... Showing specific file type only

# to execute: PS C:\Windows> &"C:\tests_master\ps_01.ps1"
$myDirectory = "c:\tests"
Get-ChildItem -Recurse $myDirectory | Where { ! $_.PSIsContainer }  | Select Name, FullName, Length
ouput:
Name    FullName                   Length
----    --------                   ------
Doc.odt C:\tests\test1_dir\Doc.odt   7334