Feb 142018

I needed to get all MAC addresses without hyphens today so I could match against some MAC Address barcodes.
Ended up writing this one-liner to get what I needed. I’ve added some variables to make it a bit easier to read here.

$svrDHCP = "DHCP Server"
$scope = ""
Get-DhcpServerv4Lease -ComputerName $svrDHCP -scope $scope | select IPAddress,ClientID,Hostname | ForEach-Object { Add-Member -InputObject $_ -name Mac -MemberType NoteProperty -Value $($_.clientID -replace "-",""); write-output $_} | out-gridview

Jul 022015

I’ve just started working with Powershell recently and wanted to create a CSV file from scratch.
I thought it’d be as simple as piping a string to Export-CSV, however Export-CSV only takes objects.
This meant that I had to create my own objects to then dump into Export-CSV.
This wasn’t immediately obvious to me initially, as I’ve little experience with Powershell, but since I’ve worked out how to do it, I’m going to document it here for reference.

$csvContents = @() # Create the empty array that will eventually be the CSV file

$row = New-Object System.Object # Create an object to append to the array
$row | Add-Member -MemberType NoteProperty -Name "User" -Value "John Doe" # create a property called User. This will be the User column
$row | Add-Member -MemberType NoteProperty -Name "UserID" -Value "JD01" # create a property called UserID. This will be the UserID column
$row | Add-Member -MemberType NoteProperty -Name "PC" -Value "PC01" # create a property called PC. This will be the PC column

$csvContents += $row # append the new data to the array

$csvContents | Export-CSV -Path C:\tmp\user.csv

The code above will result in the following output

#TYPE System.Object
"John Doe","JD01","PC01"

Dec 292011

So I’ve recently been playing around with Powershell to do some scripts at work, and ran into this hurdle.
I had to get today’s date, minus 2 days from it, and then output it in a certain format.
After much mucking about, I finally found out how to do it.

Firstly, assign the date to a variable

$a = Get-Date

And then, I can subtract the days I need and format it at the same time, and assign it to the second variable.

$b = $a.AddDays(-2).toString("yyyy/MM/dd hh:mm")

And voila, I now have the date minus 2 days in the format I need.

2011/17/27 11:17