Some PowerShell Basics

email me

You ever needed just to write a quick script, but you don’t have time to learn the ins and outs of scripting? Well, here are some PowerShell basics to get you up and running. By using the code here, you can quickly create some simple scripts. Just open notepad, paste the segments you need, update the paths and/or file names, and save as script.ps1.

Let me know if you’d like to see something else.

#========================================================================
# Created on: 10/13/2016 11:48 AM
# Created by: Eddie Jackson
# Organization: Commlink Industries
# Filename: script.ps1
#========================================================================

# Create Registry Key
$Date = Date
New-ItemProperty -Path HKCU:\Contoso.com\App1 -Name Timestamp -Value "$Date" -Force

# Read Registry Key
$RegPath = "HKCU:\Contoso.com\App1"
$Reg = Get-ItemProperty $RegPath -Name Timestamp
$(New-Object -comobject "WScript.Shell").Popup($Reg,0,"Reg Key",0)

# Delete Registry Key
$RegPath = "HKCU:\Contoso.com\App1"
$Reg = Remove-ItemProperty $RegPath -Name Timestamp
$(New-Object -comobject "WScript.Shell").Popup("The Reg Key was deleted!",0,"Reg Key",0)

# Copy File
$SourceFile = "Test.txt"
$NewFile = "Test2.txt"
if ([System.IO.File]::Exists($SourceFile)) {
Copy-Item $SourceFile $NewFile
"Source File ($SourceFile) copied to ($newFile)"
}

# Delete File
$FileName = "test3.txt"
if ([System.IO.File]::Exists($FileName)) {
Remove-Item $FileName
}

# Check Folder, Create or Delete Folder
$FolderPath = "c:\_PS\sample1\test\"
if ([system.io.Directory]::Exists($FolderPath)) {
$(New-Object -comobject "WScript.Shell").Popup("That folder does exists!",0,"Folder Path",0)
Remove-Item -Path $FolderPath
$(New-Object -comobject "WScript.Shell").Popup("The folder was deleted!",0,"Folder Path",0)
}

Else {
$(New-Object -comobject "WScript.Shell").Popup("That folder does not exist",0,"Folder Path",0)
New-Item -path $FolderPath -itemType "directory"
$(New-Object -comobject "WScript.Shell").Popup("The folder was created!",0,"Folder Path",0)
}

# Create text file
$CreateFile | Out-File 'test3.txt'

# Writing to a text file
$AddTextToFile = 'This is some sample text'
$AddTextToFile | Out-File 'test3.txt'

# Appending to a text file
$AddTextToFile = 'This is another line'
$AddTextToFile | Out-File 'test3.txt' -Append

# Reading from a text file
$TheTextFile = Get-Content test3.txt
$(New-Object -comobject "WScript.Shell").Popup($TheTextFile,0,"Contents of file",0)

# Create Event Log
New-Eventlog -Logname Application -Source 'AppName1' -ErrorAction SilentlyContinue
Write-Eventlog -Logname Application -Message 'Your Message Goes Here' -Source 'AppName1' -id 777 -entrytype Information -Category 0

# Launch Process
Start-Process notepad.exe
#-Wait -WindowStyle Maximized