PowerShell scripting is an essential skill each sysadmin has to know as it provides an efficient and reliable way to automate IT tasks. When it comes to using AI technology to enhance PowerShell scripting, two of the most prominent options are Bing AI and ChatGPT. While both offer unique features and benefits, it’s important to understand the differences and compare them to determine which one is better suited for your specific needs. In this blog post, we’ll dive into the capabilities of each platform and explore the strengths and weaknesses of Bing AI and ChatGPT in PowerShell scripting.

What Bing AI Can Do

Bing AI is an AI-powered search engine that is built on top of the OpenAI large language model. It can help you with a variety of tasks. It can sift through search results and synthesize the findings to answer complex queries in a chatbot window. It can suggest recipes, write poems, and more. The new Bing can generate content to help you. It takes key learnings and advancements from ChatGPT and GPT-3.5.

On the 14th of March, Microsoft confirms that Bing AI runs on OpenAI GPT-4

It’s a new and enhanced search experience for any topic. You can ask Bing AI to explain a topic or summarize a webpage.

Bing AI responds to the question and also provides a link for the website it uses in the answer, a nice feature.

Bing AI
Bing AI

Read more about Bing AI and Edge at Reinventing search with a new AI-powered Microsoft Bing and Edge, your copilot for the web.

If you want to know what ChatGPT can do, feel free and read the OpenAI Chat GPT 3 Can Write Your PowerShell Script

Let’s Test Bing AI and ChatGPT about PowerShell.

As a Sysadmin, these AI solutions provide a nice, easy, and quick way to write a script. But which one is better?
I had multiple questions for ChatGPT and Bing AI about PowerShell scripting, and let’s see how they respond.

One thing to say before starting and to save time and reduce the post length I wont add the AI code explanation, the focus on the AI code solution and quality.

Search for all files And Move Them.

Let’s start by asking the following.

  • Using PowerShell, Can you write a PowerShell script that searches for all files on a server with a specific extension and larger than 1 MB and moves them to a C:\MyNewFolder folder?

Bing AI responds as the following.

$sourceFolder = "C:\SourceFolder"
$destinationFolder = "C:\MyNewFolder"
$extension = "*.txt"
$size = 1MB

Get-ChildItem -Path $sourceFolder -Recurse -Include $extension | Where-Object { $_.Length -gt $size } | Move-Item -Destination $destinationFolder

ChatGPT Responds as the following:

# Set the file extension to search for
$extension = "*.txt"

# Set the minimum file size in bytes
$minFileSize = 1MB

# Set the destination folder
$destination = "C:\MyNewFolder"

# Find all files with the specified extension and minimum size
$files = Get-ChildItem -Path "C:\" -Recurse -Filter $extension | Where-Object { $_.Length -gt $minFileSize }

# Move the files to the destination folder
foreach ($file in $files) {
    Move-Item $file.FullName $destination
}

Here are some quick findings for the example above

  • ChatGPT wrote the script and added the comments before each line making it easier to understand. Also, ChatGPT uses Foreach to go through the files and perform the moving action.
  • Bing AI wrote the script without comments, making the code look shorter, and Bing AI uses the pipeline to perform the moving action. But you can ask Bing AI to rewrite the script and add the comment, and it will do it.

Using Regex to Extract Email address from a String

The prompt: Using PowerShell and in the following string “Hey @PowerShellCenter, I am someone@gmail.com and I love your site, I will refer it to s.one@yahoo.com” can you extract the email address

Bing AI Response

$string = "Hey @PowerShellCenter, I am someone@gmail.com and I love your site, I will refer it to s.one@yahoo.com"

# Use regex to match email addresses
$regex = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"
$matches = [regex]::Matches($string, $regex)

# Output matches
foreach ($match in $matches) {
    Write-Output $match.Value
}

ChatGPT Response

# Define the string
$string = "Hey @PowerShellCenter, I am someone@gmail.com and I love your site, I will refer it to s.one@yahoo.com"

# Define the regular expression pattern to match email addresses
$regex = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"

# Extract the email addresses from the string
$emailAddresses = [regex]::Matches($string, $regex) | ForEach-Object { $_.Value }

# Print the extracted email addresses
$emailAddresses

Here are some quick findings for the example above

Both used the same Regex as this regex provides the correct answer, but each one small changes in the way the results are presented.

Creating an AD User and Enable Exchange Online

The prompt: “using PowerShell Create an AD User named as “Faris Malaeb” and enable Exchange Online mailbox for this user”

In the answer, I won’t include the AI script explanation. Just let’s see the results

Bing AI Response

# Import modules
Import-Module ActiveDirectory
Import-Module MSOnline

# Connect to Azure AD
Connect-MsolService

# Set user information
$firstName = "Faris"
$lastName = "Malaeb"
$username = "fmalaeb"
$password = "P@ssw0rd"
$emailAddress = "$username@example.com"

# Create AD user
New-ADUser -Name "$firstName $lastName" -GivenName $firstName -Surname $lastName -SamAccountName $username -UserPrincipalName $emailAddress -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Enabled $true

# Enable Exchange Online mailbox
Enable-RemoteMailbox -Identity $username -RemoteRoutingAddress "$username@TENANT.mail.onmicrosoft.com"

# Assign licenses
$licenseOptions = New-MsolLicenseOptions -AccountSkuId TENANT:STANDARDPACK
Set-MsolUserLicense -UserPrincipalName $emailAddress -AddLicenses TENANT:STANDARDPACK -LicenseOptions $licenseOptions

ChatGPT Response

# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName admin@example.com -ShowProgress $true

# Create the new AD user account
New-ADUser -Name "Faris Malaeb" -SamAccountName "fmalaeb" -GivenName "Faris" -Surname "Malaeb" -Path "OU=Users,DC=example,DC=com" -AccountPassword (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) -Enabled $true

# Get the user object
$user = Get-ADUser -Identity "fmalaeb"

# Enable the Exchange Online mailbox for the user
Enable-RemoteMailbox -Identity $user.SamAccountName -Alias $user.SamAccountName -PrimarySmtpAddress "$($user.SamAccountName)@example.onmicrosoft.com"

# Assign all the required licenses
$licenses = @("Microsoft 365 Business Basic", "Microsoft 365 Business Standard", "Exchange Online Plan 2")
Set-MsolUserLicense -UserPrincipalName $user.UserPrincipalName -AddLicenses $licenses

Here are some quick findings for the example above

  • Both AI uses the MSOnline PowerShell Module, which is end-of-life as Microsoft now uses the Graph API PowerShell Module. This may be because these AI are unaware of these changes and depend on the learning sources.
  • The Bing AI used the RemoteRoutingAddress parameter, this means that Bing AI assumes that there is an Exchange Server on-premises, but ChatGPT did not use this parameter. When I asked ChatGPT why it did not use the RemoteRoutingAddress parameter, ChatGPT responded, “I assumed that you are using Exchange Online exclusively and not in a hybrid deployment scenario. Therefore, the RemoteRoutingAddress parameter is not needed”.
  • Both AI did not import Exchange Management Shell. But Bing AI mentioned that the Exchange Management Shell must be installed.

Writing Log files and acting at a certain time

The Prompt: Write a PowerShell script that writes a log to a file from 1 PM till 2 PM, clear the log at 4 PM, and remove the file by 6 PM

Bing AI Response

$LogPath = "C:\Logs\MyLog.log"
$StartTime = "1:00 PM"
$EndTime = "2:00 PM"
$ClearTime = "4:00 PM"
$RemoveTime = "6:00 PM"

# Start logging
Start-Transcript -Path $LogPath

# Wait until the start time
while ((Get-Date).ToString('h:mm tt') -ne $StartTime) {
    Start-Sleep -Seconds 1
}

# Log some information
Write-Host "Logging information..."

# Wait until the end time
while ((Get-Date).ToString('h:mm tt') -ne $EndTime) {
    Start-Sleep -Seconds 1
}

# Stop logging
Stop-Transcript

# Wait until the clear time
while ((Get-Date).ToString('h:mm tt') -ne $ClearTime) {
    Start-Sleep -Seconds 1
}

# Clear the log
Clear-Content -Path $LogPath

# Wait until the remove time
while ((Get-Date).ToString('h:mm tt') -ne $RemoveTime) {
    Start-Sleep -Seconds 1
}

# Remove the log file
Remove-Item -Path $LogPath

ChatGPT Response

# Set the start and end times
$startTime = Get-Date "1:00 PM"
$endTime = Get-Date "2:00 PM"
$clearTime = Get-Date "4:00 PM"
$removeTime = Get-Date "6:00 PM"

# Loop until it's time to clear the log
do {
    # Check if it's time to write to the log
    if ((Get-Date) -ge $startTime -and (Get-Date) -le $endTime) {
        # Write to the log file
        "Log entry $(Get-Date)" | Out-File "log.txt" -Append
    }
    # Wait for 1 minute before checking again
    Start-Sleep -Seconds 60
} until ((Get-Date) -ge $clearTime)

# Clear the log file
Clear-Content "log.txt"

# Wait until it's time to remove the file
while ((Get-Date) -lt $removeTime) {
    # Wait for 1 minute before checking again
    Start-Sleep -Seconds 60
}

# Remove the log file
Remove-Item "log.txt"

I noticed that ChatGPT understood the question better than Bing AI, ChatGPT included the log writing in the Do Until loop, but Bing AI did not, so the result is Bing AI wrote a single line in the time period from 1 PM to 2 PM, while ChatGPT loops the writing process to write a proper log.

Send Email Message

The Prompt: Create a PowerShell script to send an email message

Bing AI Response

$credential = Get-Credential
Send-MailMessage -From me@company.org -To joe@gmail.com -Subject 'this is a subject' -Body 'this is the body' -UseSsl -Port 587 -Credential $credential

ChatGPT Response

$smtpServer = "smtp.example.com"
$smtpPort = 587
$smtpUsername = "sender@example.com"
$smtpPassword = "password"

$to = "recipient@example.com"
$from = "sender@example.com"
$subject = "Test Email"
$body = "This is a test email."

$email = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
$email.IsBodyHtml = $false

$smtpClient = New-Object System.Net.Mail.SmtpClient $smtpServer, $smtpPort
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = New-Object System.Net.NetworkCredential $smtpUsername, $smtpPassword

$smtpClient.Send($email)

Write-Host "Email sent to $to"

I noticed multiple times that ChatGPT uses the .Net classes more than the Cmdlet. In the example above, ChatGPT uses the System.Net.Mail.MailMessage and builds the entire email structure instead of simply using the Send-MailMessage

So Which One to Use

Both solutions are great. Actually, Bing AI is a GPT-4, But as I am writing and doing some quick tests, I notice the following:

  • Both don’t use parameter splatting unless asked to do so, which is not a big deal.
  • Sometimes they use cmdlet from the old PowerShell Module.
  • They are not error-free and can write some incorrect scripts or steps.
  • Both write and can save a lot of time writing the PowerShell script.
  • Review for the generated script is a must. NEVER trust the code any tool generates.
  • The AI can build a great script with complex logic, which saves a lot of time.

Conclusion

Using AI tools to automate PowerShell scripting can be a game-changer for IT professionals. With the help of AI, you can automate repetitive tasks, reduce errors, and increase productivity. AI tools can help you write better code, optimize your scripts, and improve your overall workflow. By using AI tools, you can save time and focus on more important tasks. In conclusion, AI tools can help you become a more efficient and effective IT professional. I hope this helps. Let me know in the comment if there is any comparison you like to see.

5/5 - (3 votes)