• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Clatent

Technology | Fitness | Food

  • About
  • Resources
  • Contact

AD

Module Monday July 31, 2023

July 31, 2023 by ClaytonT Leave a Comment

Well, here it is!  Module Monday, but this one is a module I’ve been working on for a bit and figured it’s time to put it out to the community for others to enjoy and improve. Have you had to test PowerShell scripts on your 365 tenant and really didn’t want to use your production environment, but wanted to keep the close as possible for testing accuracy? Then you’ll want 365AutomatedLab in your tool chest. It can also be used to add multiple users to an environment from an excel sheet or add multiple groups to a user per their title from an excel sheet. Hope you check it out and leave some feedback! So much I want to do with it and super excited about this project that I feel can help so many!

I’ll be doing some blog posts and video tutorials in the near future. Any preferences?

Thanks to Andrew Pla for the extra push 😆

https://github.com/DevClate/365AutomatedLab

Tagged With: 365, AD, Automation, Documentation, Module Monday, PowerShell

Read-Only Friday 365 Developer Program

July 14, 2023 by ClaytonT Leave a Comment

Want to have some fun with Office 365, but don’t want to mess up your production environment? Or what about being able to try out scripts and not having to brace yourself as you run them and hope they don’t clear out all your data? Now you can do whatever you want with the Microsoft 365 Dev Center.

That is right, up to 25 E5 licensed users at your disposal for 90 days and will be renewed as long as you are using it. They will even create 16 users for you, mail traffic, and more. This isn’t just for PowerShell, this all aspects of 365.

Awesome, right? Here are few examples:

  1. You could copy up to 25 of your current users and import them into this Developer tenant and test scripts see exactly how it would work with your information. Think of those times where you test a script with fictional users and your script works perfect, but once you put it into production, your script fails because one username had a character that your test data didn’t have. Now your spending unnecessary time trying to figure out what went wrong when it worked perfectly in proof of concept.
  2. You want to test new features or policies, but you don’t want to enable them in your production environment, as your not 100% sure how it will react to your environment. Configure this test environment how your current tenant is then enable those features or policies you want to test. Much safer to test in the dev environment, then do it in production and all of a sudden your users can’t access critical resources or anything at all!
  3. Your boss wants you do a proof of concept on how to streamline the onboarding process and to make it as simple as possible for the organization. It is recommended that you use Sharepoint and Teams as the company already uses both and are familiar. Instead of using your production environment, you can do this all in the dev tenant without affecting anything in production. You can even invite key players in this project to login and test it with you. Now you don’t have to worry about a teams alert that you setup for when a new hire has been added to AD or Microsoft Entra ID spamming a your production channel because your script or flow errored.

These are just a few scenarios that the 365 Dev tenant can be useful, but there are so many more. I’m barely scratching the surface, and hope you sign up right away for this if you haven’t already. It is free, if you administer or develop 365, you need this.

I hope you found this helpful, and if you have any questions, I’d be glad to help out in anyway I can.

Sign up for the Microsoft 365 Dev Center

Tagged With: 365, AD, Automation, Development, Documentation, PowerShell, Read-Only Friday, Reporting, Sharepoint

Creating a Company Standard Naming Computers with PowerShell

April 21, 2023 by ClaytonT Leave a Comment

Tired of guessing or remembering which prefix to use when setting up a new computer? Or what about when you by accident fat finger it, and you have to redo it? Or even, you have multiple people in your department, and you want to make sure everyone is creating them the same way?

This function I created will solve all of these issues, and you can customize it to your company standards very easily.

I’ll break it down to smaller parts, then we will put it all together.

function Rename-ComputerWithTag {   

First we name our function with the function “verb-noun” naming convention then the { and we will add a closing one below it(If you are using VSCode it will automatically create it).

[CmdletBinding(SupportsShouldProcess=$true)]
param (

Then we add [CmdletBinding(SupportShouldProcess=true)], to make it an advanced function and also to support -WhatIf and -Confirm, which I highly recommend when you are changing(adding/deleteting) anything with PowerShell. WhatIf will show you what is going on without actually doing it and Confirm will ask you to confirm that is what you really want to do.

[Parameter(Mandatory = $true, Position = 0)]
[ValidateSet('CA', 'MA', 'NC', 'NY', 'FL')]
[string]$Prefix,

Next we have have the parameters for the function. The mandatory = $true, means you can’t go any farther unless this is filled out. The position 0 means that it muse be the first or only unnamed parameter. A quick example that would work is Rename-ComputerWithTag NY-23221, but if you did Rename-ComputerWithTag 9322 NY-23221, where the 9322 is the asset tag number, this wouldn’t work because the computer name isn’t first.

Then we have one of my favorites, ValidateSet. It is exactly what you think it is, if you don’t put in one of those values, you can’t go any further. This is great for a couple of reasons; you can ensure the user is inputting a company approved value and it gives them tab completion, so if they can’t remember the exact spelling, they can just press tab and it will tab through each option for that parameter. This has saved me many times!

Finally, we get to the variable, where you see [string] right before it. The reason for that is to define what type of variable it is and so that PowerShell knows to handle that value as a string, and not like a date. I always define the type, as I’ve been burned before when I wasn’t getting the expected results and troubleshooted longer than I’d like to admit!

[Parameter(Mandatory = $false, Position = 1)]
[string]$AssetTag,

Here you can see that the $AssetTag parameter isn’t required, and should be in the 2nd position. I know it’s a little confusing at first if your new to PowerShell/Coding, but I promise you’ll learn quickly. Again, you see that we used the string type for the asset tag as it could have both letters and numbers in it.

[Parameter(Mandatory = $true)]
[string]$ComputerName

For the final parameter in the function, you can see that the computer name is mandatory, but there is no required position for it. You can also just put (Mandatory) instead of Mandatory = $true, if you want. I’m just use to still doing the = $true, but both ways work.

$ComputerStatus = Test-Connection -ComputerName $ComputerName -Count 1 -Quiet

The next part of this script is making sure the computer you want to change of the of is reachable. Make sure that the computer you are trying to change the name of can be pinged, if not it will fail. Test-Connection is what sends the ping, -Count is how many times do you want to try and ping the computer, and -Quiet makes it so it returns back $true or $false depending on the state of the computer. Then it is saved into the $ComputerStatus variable for future use.

if ($ComputerStatus -eq $true) {
       Write-Verbose -Message "$ComputerName was found. Beginning Rename Process"
    }

What this does is take the result from $ComputerStatus, and if it returns $true, then write a message if -Verbose is used, to say that it was found and it will begin renaming the computer.

else {
        Write-Error "The computer $ComputerName is offline. Please try again when the computer is online."
    }

And this will write an error that the computer is offline if the $ComputerStatus comes back as $flase

if (-not $AssetTag) {
        $AssetTag = (Get-CimInstance -ClassName Win32_BIOS).SerialNumber
    }

Now that we know if we’ve gotten this far that the computer is online. Now we will check if an Asset Tag was given, if not it will find the computer’s serial number and use that.

$NewName = '{0}-{1}' -f $Prefix, $AssetTag

This will combine the Prefix and the AssetTag(or serial) with a hyphen inbetween, and save it to the $NewName variable. It knows to format it like this due to the -f and assigns the Prefix the 0 position and the AssetTag the 1 position.

if ($PSCmdlet.ShouldProcess($ComputerName, $NewName, "Rename-Computer")) {
        Rename-Computer -ComputerName $ComputerName -NewName $NewName -Force
    }

Now the part we have all been waiting for… the actual renaming of the computer! What this does is makes sure that the -WhatIf and -Confirm do work, and we have it so it will force the renaming. This will not automatically reboot the computer, it will ask you to, but if you wanted to, you could add that feature in.

Write-Verbose -Message "$ComputerName changed to $NewName"
    $NewName

And this will write that the computer name has changed if you use -verbose, and if you don’t this will just show the computer’s new name.

I didn’t go line by line on the Help for it, but I’ll do another Blog Post specifically on help and it’s importance(It’s very important!)

Hoping you found this useful, as it it makes it very easy to make sure everyone follows the same procedures when naming computers.

If you have any questions or see anyway to improve the function, please reach out!

Below is the full function, and here is the link to the GitHub

PowerShellGeneral/Rename-ComputerWithTag.ps1 at main · DevClate/PowerShellGeneral

<#
.SYNOPSIS
Renames a computer with a prefix and asset tag.

.DESCRIPTION
This function renames the local computer with a prefix of CA, MA, NC, NY, or FL followed by a hyphen and an asset tag. If an asset tag isn't given, it uses the computer's serial number with CIM.

.PARAMETER Prefix
The prefix to use for the new computer name.

.PARAMETER AssetTag
The asset tag to use for the new computer name. Optional.

.PARAMETER ComputerName
Computer you want to change the name of. Local or Remote.

.PARAMETER WhatIf
Displays what the command would do if run, without actually running the command.

.PARAMETER Confirm
Prompts you for confirmation before running the command.

.EXAMPLE
Rename-ComputerWithTag -Prefix CA -AssetTag 900123 -Confirm

This prompts you for confirmation before renaming the computer with the prefix "CA" and the asset tag "900123".

.EXAMPLE
Rename-ComputerWithTag -Prefix FL -WhatIf

This displays what the command would do if run, without actually renaming the computer. The new computer name will have the prefix "FL" and the asset tag set to the computer's serial number.

.EXAMPLE
Rename-ComputerWithTag -Prefix NC -AssetTag 900134 -ComputerName DESKTOP-4I9DF1

This prompts you for confirmation before renaming the remote computer "DESKTOP-4I9DF1" with the prefix "NC" and the asset tag "900134".

#>

function Rename-ComputerWithTag {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateSet('CA', 'MA', 'NC', 'NY', 'FL')]
        [string]$Prefix,

        [Parameter(Mandatory = $false, Position = 1)]
        [string]$AssetTag,

        [Parameter(Mandatory = $true)]
        [string]$ComputerName
    )

    #Check if the computer is online
    $ComputerStatus = Test-Connection -ComputerName $ComputerName -Count 1 -Quiet

    #If the computer is online, proceed with the name change
    if ($ComputerStatus -eq $true) {
        #Write that computer was found and beginning renaming process
        Write-Verbose -Message "$ComputerName was found. Beginning Rename Process"
    }

    #If the computer is offline, display an error message
    else {
        Write-Error "The computer $ComputerName is offline. Please try again when the computer is online."
    }

    # Get the computer's serial number with CIM if an asset tag isn't given
    if (-not $AssetTag) {
        $AssetTag = (Get-CimInstance -ClassName Win32_BIOS).SerialNumber
    }

    # Build the new computer name
    $NewName = '{0}-{1}' -f $Prefix, $AssetTag

    # Rename the computer
    if ($PSCmdlet.ShouldProcess($ComputerName, $NewName, "Rename-Computer")) {
        Rename-Computer -ComputerName $ComputerName -NewName $NewName -Force
    }

    # Output the new computer name
    Write-Verbose -Message "$ComputerName changed to $NewName"
    $NewName
}

Tagged With: AD, Automation, PowerShell, Windows Server

Extracting Excel Worksheet Names to a CSV

April 14, 2023 by ClaytonT Leave a Comment

I know it’s Friday, but I’m changing it a bit up today. I just created this little script that I think could be helpful to others. This one isn’t for the masses, but I have a feeling it will help out more than a few people, and trigger some more ideas for script ideas.

# Specify the path to the Excel file
$excelFilePath = "C:\Scripts\WorksheetTitle.xlsx"
$outputCsvPath = "C:\Scripts\exportworksheetlabels.csv"

if (!(Test-Path $ExcelFilePath)) {
    Write-Error "Excel file not found at the specified path: $ExcelFilePath"
    return
}

# Open the Excel file
$excel = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList (Get-Item $excelFilePath)

# Get the worksheet names
$worksheetNames = $excel.Workbook.Worksheets | ForEach-Object { $_.Name }

# Add quotes around each worksheet name and convert them to a comma-separated string
$commaSeparatedWorksheetNames = ($worksheetNames | ForEach-Object { '"' + $_ + '"' }) -join ','

# Export the worksheet names to a CSV file
$commaSeparatedWorksheetNames | Set-Content -Path $outputCsvPath

# Dispose the ExcelPackage object to release resources
$excel.Dispose()

What this script does, is takes all of your worksheet names in an excel sheet, and exports them with quotes and commas as if they were an array. An example would be “Dog”, “Cat”, “Cheetah”, where Dog, Cat, and Cheetah were the 3 different worksheet names. Don’t ask how I picked those names, but I’d be curious to see who has those worksheet names in an excel workbook!

Now you are probably wondering what the use case for this is, and for me, which I found very useful was we have an excel workbook that is separated by job title. And inside each of these worksheets are the 365 Distribution/Security Lists and 365 Groups for that title. This makes it so we have one “database” of lists, and only need to make the change once, if a standard changes. This works for both adding and removing them. But, the user who is adding/removing these groups for that user, needs to know the exact title for that user and how it is spelled on the worksheet…

This is why we export the titles this way, so then we can copy and paste them into a validateset within the function for the script, so the user has tab completion and so the script won’t even start without having the correct title.

Hope this helped you out and/or gave you some more ideas, and if you see anyway it can be improved, I’m all about being more efficient. Let me know if you would want to see the script to add users by title from an excel worksheet. Have a great Friday!

Github – Copy-ExcelWorksheetName

Tagged With: 365, AD, Automation, Excel, PowerShell

Read-Only Friday March 10, 2023

March 10, 2023 by ClaytonT Leave a Comment

It’s Friday, and I’m going to keep this one short in sweet copy. I’ve mentioned this module before, but it is so helpful if you use any of the products, that I want to make sure you don’t miss out on it! Yes, I know it’s Read-Only Friday, but this module will step up your documentation game ten fold.

AsBuiltReport on Github or you can find them on asbuiltreport.com.

What they have created is multiple modules depending on the product you need documentation on, and with one quick line of code, you get a full breakdown of the product you requesting information on. How about a 144 page document on your Active Directory? Not bad, right?

Check them out, and let me know what you think!

GitHub:
https://github.com/AsBuiltReport

Website:
https://www.asbuiltreport.com/

Tagged With: AD, Automation, Documentation, Fortigate, Fortinet, Module Monday, PowerShell, Read-Only Friday, Reporting, Veeam, VMWare, Windows Server

One-Liner Wednesday February 22, 2023

February 22, 2023 by ClaytonT Leave a Comment

Ever wanted a quick and easy way to see what operating systems all your computers are running to the detail of the version number? Then wanting to know the last time they logged on?

PowerShell provides a powerful and efficient way to perform this task. In this blog post, we will show you how to use a PowerShell one-liner to search for computers in a specific OU and view their name, operating system, OS version, and last time they logged in.

Searching for computers in a specific OU

You can start by searching for computers in a specific OU. The “Get-ADComputer” cmdlet can be used to retrieve information about computer objects in Active Directory. Here is an example command that retrieves all computers in the “Computers” OU:

Get-ADComputer -SearchBase "OU=Computers,DC=example,DC=com" -Filter * -Properties Name, OperatingSystem, OperatingSystemVersion, LastLogonDate

This command uses the “-SearchBase” parameter to specify the distinguished name of the search base where the search should be conducted. In this case, we are searching in the “Computers” OU of the “example.com” domain. You should replace this with the distinguished name of the OU you want to search in.

The “-Filter” parameter is used to retrieve all computer objects in the specified OU, and the “-Properties” parameter is used to specify the properties you want to retrieve. In this case, we are retrieving the “Name”, “OperatingSystem”, “OperatingSystemVersion”, and “LastLogonDate” properties.

Formatting the output

The output of the previous command is not very user-friendly, so we need to format it to make it easier to read. We can use the “Select-Object” cmdlet to select the properties we want to display and format the output using the “Format-Table” cmdlet. Here is the final PowerShell one-liner:

Get-ADComputer -SearchBase "OU=Computers,DC=example,DC=com" -Filter * -Properties Name, OperatingSystem, OperatingSystemVersion, LastLogonDate | Select-Object Name, OperatingSystem, OperatingSystemVersion, @{Name="LastLogonDate";Expression={[DateTime]::FromFileTime($_.LastLogonDate)}} | Format-Table -AutoSize

This command retrieves all computer objects in the specified OU and selects the “Name”, “OperatingSystem”, “OperatingSystemVersion”, and “LastLogonDate” properties. The “LastLogonDate” property is converted to a readable date format using the “FromFileTime” method of the “DateTime” class. Finally, the output is formatted using the “Format-Table” cmdlet to display the information in a table format. You could even change “Format-Table” and use “Out-GridView” to give you an excel like experience where you can filter and sort columns… and to make it even more advance if you are trying to remove or disable computers, you could use the Out-GridView with a “-PassThru” parameter then pipe it to a delete or disable. ***Make sure to use -WhatIf so you don’t by accident delete all of the computers that you searched for!

Conclusion

In this blog post, we have shown you how to use a PowerShell one-liner to search for computers in a specific OU in your Active Directory and view their name, operating system, OS version, and last time they logged in. This information can be very useful for managing your domain and keeping track of your computers. This can be used for reporting and for autoamating tasks that only pertain to certain versions of Windows OS. By using PowerShell, you can quickly and easily retrieve this information and format it in a way that is easy to read and understand while using it for automations.

Tagged With: AD, Automation, One Liner Wednesday, PowerShell, Reporting, Windows Server

  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Go to Next Page »

Primary Sidebar

Clayton Tyger

Tech enthusiast dad who has lost 100lbs and now sometimes has crazy running/biking ideas. Read More…

Find Me On

  • Email
  • GitHub
  • Instagram
  • LinkedIn
  • Twitter

Recent Posts

  • New Feature Announcement for 365AutomatedLab
  • How ChatGPT saved our company $1500 in less than 15 minutes
  • Read-Only Friday August 4, 2023 End Of Life Server 2012R2 and managing EOL
  • One-Liner Wednesday August 2, 2023
  • Module Monday July 31, 2023

Categories

  • 365
  • Active Directory
  • AI
  • AzureAD
  • Cim
  • Dashboards
  • Documentation
  • Get-WMI
  • Learning
  • Module Monday
  • Nutanix
  • One Liner Wednesday
  • Passwords
  • PDF
  • PowerShell
  • Read-Only Friday
  • Reporting
  • Security
  • Windows
  • WSUS

© 2023 Clatent