#NeverStopLearning: PS Comments, Variables, IF, Remove-Item, Write to a file

Bunch of stuff today in 10 minutes; again, this is my collection of notes, so the actual blog post my be less glamorous than the excitement I felt. PowerShell appears to be a very powerful scripting language, and the more I use it, the more I like it. However, like most coding languages, the syntax varies. For example, I finally had to give up and Google how to write a comment.

#This is a single line comment in PowerShell
<#This is a 
multi-line comment in Powershell #>

Comments are useful as scripts get longer. For my sample script, I wanted to try a few things today:
1. write something to a text file
2. Do some conditional logic
3. delete a file, and
4. declare and use a variable

Script below, and explanations later:

#Define a variable
$File = "C:\list.txt"

#the following code will drop the file if it exists
IF (Test-Path $File) {
Remove-Item $File }

Get-ChildItem -Path C:\ | Set-Content -path $File

Code is straightforward, but one explanation that may be tough for experienced programmers; there’s no type declaration for the variable. Everything in PowerShell is an object, which is why the variable is simple to declare and re-use. Furthermore, when piping the contents of Get-ChildItem to a file, it knows to write them as text. This may confuse me later, but for now, I grok it.

Share