PowerShell

The basics syntax’s for PowerShell

  • New: cmdlets beginning with the “New” prefix are used for: creating new objects. For example: create new Office 365 user.
  • Set: cmdlets beginning with the “Set” prefix are used for: update object properties. The “Update” could be implemented by – add a new value to the object, or update existing object property.
  • Add: cmdlets beginning with the “Add” prefix are used for: “add “something” to an object. For Example: add user to a distribution group, add Alias to Mailbox, add Mailbox permissions etc.
  • Remove: cmdlets beginning with the “Remove” prefix are used for: remove or delete objects or, removing “something” from an object. For example – remove (delete) Office 365 user accounts or, remove Mailbox permissions.
  • Get: PowerShell Cmdlets that start with the “Get” prefix are used for: retrieve or “fetch” an object. The “Get” prefix is special because we can use “Get cmdlets” for display information about objects or, we can use the “Get cmdlets”, as the “first part” of a PowerShell sentence.

Comparison operator

  • -lt – Less than
  • -le – Less than or equal to
  • -gt – Greater than
  • -ge – Greater than or equal to
  • -eq – Equal to
  • -ne – Not equal to
  • -like – Like; use wildcards for pattern matching

Logical operator

  • -not
  • -and
  • -or

Quick and Dirty Software Inventory with PsInfo and PowerShell: March 4, 2007
PsInfo is great for gathering asset information from Windows computers, both locally and remotely. PowerShell is great for automation and cleaning up output (among other things) as well as working with database driven data.
● Consider the following examples:
○ The output is merely displayed on the screen. With this method the output can be redirected to a file and imported into an application like Excel for further analysis or record keeping.
○ A database is used to drive the computers polled as well as store the output. The database table is very flat (one table) with 2 fields: ‘Computer’ and ‘Software’. For large amounts of data, this will need to be normalized.
● Example 1: Standard Screen Output
Before running this script, test your connectivity and credentials with a single PsInfo command:

PsInfo -s Applications \\somecomputer

 

Search Enterprise Desktop

Getting started using PowerShell for desktop management:
Remoting Requirements:
○ Windows PowerShell 2.0 or later ○ Microsoft .NET Framework 2.0 or later ○ Windows Remote Management 2.0
Windows Remote Management (WinRM) 2.0 is part of Windows 7 and Windows Server 2008 R2. For down-level versions of Windows, an integrated installation package must be installed, which includes PowerShell 2.0.
Using the following command, in a Admin Powershell console will turn on WinRM. To use Server Manager or GPO, follow the link.

Enable-PSRemoting

Developer OneNote: A Developer OneNote book for Microsoft Windows, Server and Cloud technology
How to run .PS1 scripts
:
PowerShell scripts are text files with “.ps1” extensions that contain PowerShell commands. Starting with Windows Server 2008, PowerShell is built into the OS. For earlier OS versions, you will need to download PowerShell at Microsoft PowerShell Site and install it.
To run ps1 scripts, you first need to enable scripts by running:

Set-ExecutionPolicy RemoteSigned

Otherwise, you will get this error message:

File {script} cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.

Enable/disable the built-in administrator account:

net user administrator /active:yes
net user administrator /active:no

Shutdown/Reboot the computer:

shutdown /s /t 0
shutdown /r /t 0

TechNig: Gateway for IT Experts & Tech Geeks
How to Convert VHD to VHDX Using Hyper-V and PowerShell?
:
Now try to convert vhd to vhdx with Windows Powershell. It is also easy and just requires one line command of convert-VHD. Remember, before starting conversion of vhd, you must turn off all you guest computers in Hyper-v environment.
○ Convert Single Virtual Hard Disk

Convert-VHD -Path ‘E:\Virtual Hard Disk-1.vhd‘ -DestinationPathE:\Virtual-HD.vhdx
Get-ChildItem E:\*.vhdx

○ Convert Single Virtual Hard Disk

Get-ChildItem E:\*.vhd | ForEach-Object {Convert-VHD -path $_.fullname -destinationpath (“E:\”+ $_.basename + “.vhdx”) }

Hyper-v Beginner: A Practical Guide to Virtualization: March 2015
You can install Hyper-v with a PowerShell command on Windows Server with “Add-WindowsFeature” command.

Add-WindowsFeature Hyper-V -IncludeManagementTools -Restart

Heuristic Andrew: R, SAS, machine learning, and statistics
Write directory listing to CSV in Windows PowerShell
September 17, 2014
This one-line command will invoke Windows PowerShell to write a directory listing to a CSV file, which is easy to use in spreadsheets and database programs. It recurses subfolders, and it includes the following information: full file name, creation time, last modified time, file size, and owner (last modified by).
To use it, simply modify the two paths: directory to scan and path to the CSV.

Get-ChildItem -Recurse "c:\directory\to\scan\" | ForEach-Object {$_ | add-member -name "Owner" -membertype noteproperty -value (get-acl $_.fullname).owner -passthru} | Sort-Object fullname | Select FullName,CreationTime,LastWriteTime,Length,Owner | Export-Csv -Force -NoTypeInformation "c:\folder\to\directory.csv"

Geeks with Blogs:
Getting a Directory or File Listing From PowerShell
November 6, 2008
It seems so obvious that getting a directory listing excluding file using the Get-ChildItem commandlet should be simple, right? Well, it is simple, but not obvious from the built-in commandlet commands. Here’s one way you can accomplish this task:

# initialize the items variable with the
# contents of a directory
$items = Get-ChildItem -Path "c:\temp"
# enumerate the items array
foreach ($item in $items){
      # if the item is NOT a directory, then process it.
      if ($item.Attributes -eq "Directory"){
            Write-Host $item.Name
} }

You can also return files and exclude directories with this simple change:

# initialize the items variable with the
# contents of a directory
$items = Get-ChildItem -Path "c:\temp"
# enumerate the items array
foreach ($item in $items){
      # if the item is NOT a directory, then process it.
      if ($item.Attributes -ne "Directory"){
            Write-Host $item.Name
} }

[H]ardForum:
PowerShell – how to create list of files in directory
Oct 19, 2010

get-childitem -include *.dat -recurse | format-table Name -hidetableheaders | out-file $file

$file wasn’t defined/ null
Try the code below, that should dump a text file with a list of pdf’s in the root of the current directory.

Get-ChildItem -Recurse -Include *.pdf | Format-Table name -hidetableheaders | Out-File 'c:\pdf list.txt'

 

Computer Performance Logon Scripts, Powershell, VBScripts, LDAP, WMI Scripts, CSV Imports

PowerShell Script to List Files:
● Find all dlls in the Windows\System32 folder:

# PowerShell script to list the DLL files under the system32 folder
$Dir = get-childitem "C:\windows\system32" -recurse
# $Dir |get-member
$List = $Dir | where {$_.extension -eq ".dll"}
$List | format-table name

● Discover Properties with: Get-member:
The purpose of this script is to list the properties of the file object controlled by the $dir variable. When we display the list, how much information do we want? What file properties are available? All is revealed by get-member.

# PowerShell script to list the DLL files under the system32 folder
$Dir = get-childitem "C:\windows\system32" -recurse
$Dir | get-member
# $List = $Dir | where {$_.extension -eq ".dll"}
# $List |ft fullname |out-file C:\scripts\dll.txt
# List | format-table name

This is the same script as example 1, all that has changed is the #.  I have ‘remmed’ out the list and activated the line: $Dir |get-member.
Get-member lists the properties and methods of the PowerShell object $Dir.  Once we have our list we can control the output specified by format-table.  See next example.  See more on Get-ChildItem -Filter.

● Output to a file:
Seeing the files on screen is fine, but with lists of files, it’s often handy to generate a file containing your script’s output.

# PowerShell script to list the DLL files under the system32 folder
$Dir = get-childitem "C:\windows\system32" -recurse
# $Dir | get-member
$List = $Dir | where {$_.extension -eq ".dll"}
$List | ft fullname | out-file "C:\Scripts\dll.txt"
# List | format-table name

Here is the line that I activated by removing the #. $List |ft fullname |out-file c: \Scripts\dll.txt. What this does is create a file in the c: \Scripts folder. (Note it does not create the \Scripts folder itself, you must do that) In that dll.txt file are the names of all the files with a .dll extension.
ft, meaning format-table, is one of the built-in aliases which make the code shorter to write.

FoxDeploy.com Scripting and all things Automation

Admin’s CheatSheet:
● Get all ‘Error’ events from the last two weeks from a remote computer:

Get-WinEvent -LogName Application -computername RemoteComputer1,RemoteComputer2 | Where-Object LevelDisplayname -eq Error | Where-Object TimeCreated -ge ((Get-Date).AddDays(-14)) | Export-Csv .\Temp\SDC.csv

● Get all members of the Administrators group of a remote machine:

Get-WMIObject -Query " SELECT * FROM Win32_GroupUser WHERE GroupComponent='Win32_Group.Domain='RemotePC',Name='Administrators'" -ComputerName RemotePC

● Export all mailboxes from an Exchange Server, 5 at a time:
Thanks to StackOverflow for some help with the logic on waiting for a job to finish

$mailboxes = Get-Mailbox
ForEach ($mailbox in $mailboxes){
    $running = @(Get-Job | Where-Object{ $_.State -eq 'Running' })
    if ($running.Count -ge 8){
         #too many jobs, we'll wait for the first to complete
         $running | Wait-Job -Any
         }
         #there weren't too many jobs, or a job just completed, let's go
    Start-Job {
            New-MailboxExportRequest -Mailbox $mailbox.Alias -FilePath "\\SERVER01\PSTFileShare\$($mailbox | select -Expand Alias)_Export.pst"
            while ((get-mailboxexportrequest -mailbox $mailbox.Alias).Status -eq 'InProgress'){
                "Mailbox export in progress, waiting"
                start-sleep 60
                }
        }
    #End of this Mailbox
    }
#lets wait for everything to finish
Wait-Job * | out-null
# Process the results
foreach($job in Get-Job){
    $result = Receive-Job $job
    Write-Host $result
}
Learning DSC Series: Desired State Configuration
● Step 1 Getting Started, renaming our machine and joining a workgroup
● Step 1.5 Creating our first local user
● Step 2 Making our user a local administrator
● Step 3 Making our system a Domain Controller
● Step 4 One-Click Domain Controller with DSC
● Step 5 DSC Revisited.  The simplest Domain Controller config, Ever.
● FoxDeploy DSC Designer – A point and click driven, guided DSC Configuration tool Part VI – In-Depth Building the FoxDeploy DSC Designer
DSC Background
● DSC – What it is and why you should care
● DSC – Solving the Chicken and the Egg Problem
● DSC v. GPO v. SCCM – The Case for Each
 
Learning GUI Toolmaking Series:
XAML And Visual Studio
 PART VIStep by step, building an advanced application
● Original ISE Snippet – XAML to GUI Loader
 Runspace-Powered multi threaded ISE Snippet
● Part V – Building responsive PowerShell apps with progress bars
● Part IV – Handling events and making a tabbed interface
● Part III – Using Advanced GUI Elements in PowerShell
● Part II – Deploying PowerShell GUIs in Minutes using Visual Studio
● Part I – Creating PowerShell GUIs in Minutes using Visual Studio – A New Hope
.Net Method / Windows Forms
● Part III – Two Ways to Provide GUI Interactions to users
● Part II –  Continued: Creating a GUI Natively using .Net Methods
● Part I – Creating a GUI Natively using .Net Methods
 

● 
● 

 

FoxDeploy.com
Description Date
■ ■ ■ Completed Script Ping-Tool.ps1 (Slight graphical interface for ping a device in the network, returns true or false) Jan 25, 2015
■ ■ ■ Using ConvertTo-HTML and CSS to create useful web reports (3 Step Process) May 23, 2014
■ ■ ■ Walkthrough – Parsing log or console outputPart two: Advanced Parsing with ConvertFrom-String Jan 5, 2015
■ ■ ■ Working with Web Services, SOAP, PHP and all the REST Nov 19, 2014
■ ■ ■ Safely storing credentials and other things Jul 14, 2016
■ ■ ■ Get the daily forecast in your console, with PowerShell Oct 20, 2014
■ ■ ■ Use Invoke-WebRequest to get your physical location Oct 23, 2014
■ ■ ■ Coding for speed Mar 23, 2016
■ ■ ■ Unholy Matrimony – wGet and PowerShell together Dec 19, 2014
■ ■ ■ New-Listbox-wMultiSelect  
■ ■ ■ My PS $Profile  
■ ■ ■ DSC Script and Output  
■ ■ ■ DSC Create Configuration on demand  
■ ■ ■ OCS PowerShell Functions  
■ ■ ■ PowerBullet : PushBullet for PowerShell  
■ ■ ■   

 

Site Description
   
PowerShell Blogger Create Shortcuts .lnk or .url Files With PowerShell
PowerShell Blogger Delivering Version Controlled Tools With PowerShell
PowerShell Blogger Get Last Computer Boot Time or Up Time With PowerShell
PowerShell Blogger Join Computer to Domain with Desired Computer Name and OU
PowerShell Blogger Remove Specific E-Mail or E-Mails From All Exchange Mailboxes (Outlook Auto Archive v1.0 Released)
PowerShell Blogger Export Subnets from Active Directory Sites and Services
PowerShell Blogger Automate Sip Address and UPN name changes in Lync / Skype for Business
PowerShell Blogger Connect To All Office 365 Services With PowerShell
   
   
   
   
   

.
.
.
.

Site Description Date
■ ■ ■ LazyWinAdmin PowerShell, Automation, Windows Server and Much more … (Scripts/Projects, Resources (Tools etc))  
■ ■ ■ blog.netnerds.net dbatools / dbareports / SQL, (PowerShell: Too Many If Elses? Use Switch)  
■ ■ ■ DexterPOSH’s Blog Get-PowerShell | Start-Automation | Invoke-Cloud (Scripts)  
■ ■ ■ Jeffrey Snover’s blog Inquiring mind opines… (not been updated since 2014)  
■ ■ ■ SpiceWorks.com Copy Icons to Windows 10 public desktop Using Powershell Jan 6, 2017
■ ■ ■ Pluralsight.com Writing Process Instructions and Directions  
■ ■ ■      
■ ■ ■      
■ ■ ■      
■ ■ ■      
■ ■ ■      

 HTML & CSS Scripting / Output:

Site Description Date
■ ■ ■ ExpertExchange.com Need a Powershell script to change css code 2014-07-09
■ ■ ■ Technet.Microsoft.com Gather website data with PowerShell Oct 28, 2016
■ ■ ■ @SPJeff.com Colorize PowerShell Transcript with CSS Oct 2, 2014
■ ■ ■    
■ ■ ■    
■ ■ ■    
■ ■ ■    
■ ■ ■    
■ ■ ■    

 Powershell Applications:

Site Description
◾ LazyWinAdmin LazyWinAdmin: ⚬ Connectivity and information check (Test-Connection, Test-Path, RDP, PowerShell Remoting, Os Version and Uptime)
◾ LazyWinAdmin PowerShell – Get a list of my domain Organizational Units
PowerShell Blogger Toolbox v1.0 Released: Map Network Drives, Refresh Group Policy, System Information, What is my Computer Name?, What is my IP Address? 
   
   

.