Powershell Core 6.2 Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

Install and open PowerShell Core on any system you prefer and execute the following steps:

  1. Type Get-Help about_Variables.
  2. Execute the following lines to create three new variables:
$timestamp = Get-Date
$processes = Get-Process
$nothing = $null
  1. Executing your variable will simply place it on the output again:
$timestamp
  1. Enter $timestamp. and then press the Tab key in the CLI or Ctrl + Space in CLI and VS Code. Observe the different properties and methods that can be used here.
  2. Try executing $timestamp.DayOfWeek and $timestamp.IsDaylightSavingTime().
  3. Accessing properties and methods on lists works just as well. Try executing the following:
$processes.Name
$processes.Refresh()

  1. Be careful when using uninitialized variables, as the result may be potentially devastating:
# Properties will be $null as well
$nothing.SomeProperty

# Method calls will throw an error
$nothing.SomeMethod()

# Be extra careful with cmdlets like Get-ChildItem!
# The default path is the current working directory
Get-ChildItem -Path $nothing -File | Remove-Item -WhatIf
  1. Lastly, you don't need to create a variable at all if you just need to access a property or method once:
# Accessing properties and methods while discarding the
# original object requires expressions, $( )
$(Get-TimeZone).BaseUtcOffset
$(Get-Process).ToString()