Powershell

Using Object properties

A lot of people see PowerShell as conversion tool, but it can do so much more.

It can uninstall apps, inventory your applications. Rename files to a standard. Create shares, modify files and sessions and give an Administrator access to a computer without interrupting a session.

It is built on .net/c# so it can do everything a program can. You just have to know your property and methods on your objects.

I am mainly speaking about windows platform. I may do a write up on Linux impact.

I can write excel, word files with out office being installed, send emails and query websites for remote data. Consolidated information and write to databases. The list is ridiculous.

I wanted to interact more so I would like to take on a challenge from the comments. What is something you think you cannot do in PowerShell?!

Functions, Learning your way around., Powershell, Scripting Technique

PowerShell Importing Data from Excel

If you want to import Excel data I recommend giving the people who toke the time to develop this module Import-Excel. It can be Read about on the PSGallery here: https://www.powershellgallery.com/packages/ImportExcel/

After reading we will try to find the module using built im module package for powershell :

“find-module importexcel”

we can pipe this into an “install-module” command with a few parameters to ensure a smooth install.

find-module importexcel | install-module -Scope CurrentUser -SkipPublisherCheck

this should install the module and you import Excel workbooks as easily as you can excel and text files.

Import-Excel, Export-Excel with a few extra parameters like -worksheet so you can target data sets and even write reports with details on different pages!

I use this to write share permission reports with different shares on different worksheets. So other things you can do is a security audit on servers and write a server to each worksheet and then write a pivot table for a summary report.

I how you download and support this module because it is nothing short of amazing, you dont have to have the excel application installed to import or export to Excel!

Learning your way around., Powershell

Formatting dates from text or objects

Ever imported data just to have a non readable date stamp?

Get-date can take your text that is a date and turn it into something more readable.

Take “15-FEB-20” for example. It’s not really a wildly used format.

Pipe that to get-date like so:

Then you can format your date to remove time and what not.

If you have imported the data you can fix the entry using the select statement.

$data |select name,@{name=’Birthday’;e={$_.birthday | get-date -format MM-dd-yyyy}}

Powershell

Google cloud and the absence of PowerShell.

I was looking into google cloud to explore some options for a client to leverage some automation elements and was very interested until I learned of the lack of PowerShell support.

For the life of me I cannot understand Google’s purpose to neglect populations of individual platforms and still want professionals to take their platform seriously as their competitors. Okay I’m done complaining.

It is something I sincerely hope Google notices and rectifies so that it supports PowerShell as it installs on all OS genres. To leave out automation potential is saying I’m just doing this cloud thing to be like everyone else.

So in my humble opinion there is simply no Power in google cloud shell.

How many others are fine learning python and writing shorthand and okay with not embracing a world where we take any OS as a catalyst that connects your tools to all the cloud providers.

Let me know what you think in the comments below.

Powershell

Mobile PowerShell Needed?

I have always wanted to get my mittens on a mobile iteration of the prized management tool.

Pocket PowerShell

I made sure I got a mobile sized tablet that would allow for me to use this on the go. Remote Desktop, Team viewer, Screen connect, VNC just dont respond like a native client. Wouldn’t it be something to truly take your scripting on the road with you?!

I believe this is possible now with todays mboile phones and tablets.

Ready to script.

What are your thoughts and your ideal access to management and automation tools?

Powershell

VS code ready to replace PowerShell ISE?

There is a push to go to Visual Studio Code, which is a plug-in rather than the PowerShell.exe having its own dedicated ISE application. It can be seen as smart, others see this as allowing for distractions.

Convenient Or inconvenient?

I do not like the syntax in the responses of commands, I don’t like the lack of the warm tab complete I am used to, and app stability. I complain about ISE lacking UI updates, but I hate the clumsy attempts to cram PowerShell into VS Code. It’s great if you want to do things across OS platforms.

I do however love VS Code for web coding and even do other one off projects.

I find the built in ISE to be the reliable of the two. It doesn’t ask me to update every time I launch it to do work.

I will say you lose some of the cool features if you are managing an updated landscape. For companies living in the past, PowerShell ISE is still relevant for interactions of windows 10 and server 2016 and you save space and can relax knowing you aren’t breaking unwritten standards as far as automation or script development.

What’s your favorite ISE? Let me know in the comments below.

Scripting Technique, Uncategorized

Add-Member if you want to effectively “object” all things and possess their property.

I thought I would clarify this as most articles don’t simplify this to easily wrap you head around.

Add-member is what I would use to add a new member to a group of properties on an object

  1. I create the object
  2.  Add a noteproperty that translate to text
  3. create a scriptmethod that can do things based on a scriptblock when called.
  4. create a scriptproperty that runs each time you call the $x object to display the results of it’s script block.
Here is the code:
$x=new-object psobject
$x| add-member -name ID – value “smithx” -membertype Noteproperty
$x| add-member -name ADlookup -value { get-aduser $x.name } -membertype scriptmethod
$x|add–member -name ADinfo -value {$x.adlookup()} -membertype Scriptproperty

if you want you can overwrite a member with the -force command.

Scripting Technique, Uncategorized

Try & Catching Errors so you can relax Finally.

Sometimes you gotta Try…. okay enough pep talk.

using the Try Command will allow you to catch any terminating errors. unless you specify for some commands you will not catch the errors and may not want to actually.

example:

 Try{ get-childitem c:\incorrectlyspelledfolder\  -erroraction Stop -recurse -errorvariable ErrorCity}

#for every Try there must be a catch

Catch {write-host "Error: $($errorCity.gettype().fullname)"}

I wrote this to have the error show the  expression needed to catch specific errors you actually care about.

so you can to catches or specific instructions to go with specific errors. lie write this to one file and email the results on another catch instance.

Example:

  Try{ 
$folder="c:\windows"
get-childitem $folder -erroraction Stop -recurse -errorvariable ErrorCity -OutVariable Results 
}
 #for every Try there must be a catch #specific to error records now it will write the line.
catch [System.Management.Automation.ErrorRecord]{Write-host "Typo?"} #this catch will catch any other error like permission denied, etc. 
Catch {write-host "Error: $($errorCity.gettype().fullname)" -ForegroundColor Red} 


Finally{write-host "finished processing $folder " -ForegroundColor Green
        write-host "Sub Folders are :"
        $Results.fullname
        }
#finally is optional to do a set of command regardless of error on the object being processed.
Good Luck Trying & catching errors and finally understanding.
Robocopy, Uncategorized

Robocopy and PowerShell working in harmony.

 

So lets create a scenario,  and say that they were having difficulty using Robocopy commands within or with PowerShell. Here’s a demonstration of how to use PowerShell to be able to deliver seamless and accurate commands that will ensure that you will have your data copied and have your PowerShell script.

The best part of PowerShell is the ability to manipulate objects of different types in the same way regardless of data type.

let’s start with planning out the end product and work towards constructing our objects.

 

Import your file with source and destination or you can wing it into a function. For demonstration purposes we will cover both.

 

Example 1: Scripted with external file input 

$data=import-csv data.csv

$count=0

$total=$data.count

foreach($item in $data)

{

$count+=1 #some people use $count++

$source= $item.source

$destination=$item.Destination

Write-Progress -Activity “Copying $source to $destination” -PercentComplete ($count/$total*100)

Robocopy $source $destination /mir /mt:8 /r:1 /w:1

} #end foreach statement in script

 

This one s a little tricky due to the possibility of quotation exceptions;  Folders with spaces that require quotes.

 Example 2: Interactive PowerShell session

set-location c:\rootoftargetfolders

get-childitem  |foreach-object {
$source= $_.fullname
$destination=”d:\destinationfolder\$($_.basename)”
Robocopy “$source” “$destination” /mir /mt:8 /r:1 /w:1
} #end foreach-object

 

Example 3: Function best saved in $profile (PowerShell Profile) 

function RoboCopy-Item ($Source,$destination)

{

Robocopy $Source” “$Destination /mir /mt:8 /r:1 /w:1

} #end function

#now to try it

RoboCopy-item  -Source c:\files -destination D:\usb_documents

 

Conclusion:

I know sometimes dealing with syntax can be a headache but when you take the time to experiment with the shell it is a good path to accumulate lessons learned.

RoboCopy and PowerShell can play nice, of course adding in some try/catch to control your logging output to a text, html or csv or installing a module that can output logs directly to Microsoft Excel or take the old-school approach and use the /log file switch for RoboCopy.