I want to put in red some words to test a msg that i will deploy/activate when i connect remotely to a pc.
I have tried placing at the begining:
Set-PSReadLineOption -Colors @{ ContinuationPrompt = 'Red' }
powershell -WindowStyle hidden -Command "& {[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');...
It doesnt work.
And putting the function foregroundcolor at but gives me error.
powershell -ForegroundColor Red -WindowStyle hidden -Command "& {[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); ...
This is the code,the message pops and works well, i just want to put colour on the text.
I would like to put the words “please dont touch your keyboard or mouse” in red or if its not posible the whole text in red.
powershell -WindowStyle hidden -Command "& {[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('IT departament has connected to your PC please dont touch your keyboard or mouse, thank you','TEST/Message')}"
asked Aug 28, 2023 at 7:24
7 bronze badges
As far as I know, you can’t change the font color in MessageBox. However, you can use a warning icon, like so:
powershell -WindowStyle hidden -Command "& {
[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms');
[System.Windows.Forms.MessageBox]::Show('IT department has connected to your PC please dont touch your keyboard or mouse, thank you','TEST/Message',[System.Windows.Forms.MessageBoxButtons]::OK,[System.Windows.Forms.MessageBoxIcon]::Stop)
}"
answered Aug 28, 2023 at 8:43
1 gold badge4 silver badges12 bronze badges
As u guys suggested i created a new window and centered it , im able to put the text in red but cant make it bigger or center it in the text box but it works.So solved.
Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object System.Windows.Forms.Form
$Form.Width = 200
$Form.Height = 200
$StatisticsBox = New-Object System.Windows.Forms.RichTextBox
$StatisticsBox.Location = New-Object System.Drawing.Size(30, 30)
$StatisticsBox.Size = New-Object System.Drawing.Size(120, 100)
$StatisticsBox.MultiLine = $True
$StatisticsBox.ScrollBars = "Horizontal"
$StatisticsBox.ReadOnly = $True
$StatisticsBox.Font = "Lucida Console"
$StatisticsBox.BackColor = "White"
$Form.Controls.Add($StatisticsBox)
$StatisticsBox.SelectionColor = 'Red'
$StatisticsBox.Text = "`r`nSE HA CONECTADO EL DEPARTAMENTO DE INFORMÁTICA`r`n" + $StatisticsBox.AppendText("NO TOCAR RATON NI TECLADO GRACIAS") + "`r`n" +$StatisticsBox.Text
# Calculamos el centro de la pantalla.
$screenWidth = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width
$screenHeight = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height
$centerX = ($screenWidth - $Form.Width) / 2
$centerY = ($screenHeight - $Form.Height) / 2
# Ejecutamos la ventana al medio
$Form.StartPosition = 'Manual'
$Form.Location = New-Object System.Drawing.Point($centerX, $centerY)
[void]$Form.ShowDialog()
$Form.Dispose()
answered Aug 29, 2023 at 7:17
7 bronze badges
PowerShell provides several cmdlets for displaying text on the console screen. As you may have guessed, each cmdlet is intended for a specific purpose. In this article, I will introduce four of these cmdlets and demonstrate how to use them.
The first cmdlet is Write-Warning, which is useful when you need to display a warning message to whoever is running the script.
Write-Warning “This is an example warning.”
Console Output 1
You can display custom warning messages by using the Write-Warning cmdlet.
Write-Warning “This is an example warning.” -WarningAction Inquire
Console Output 2
Similar to generating custom warning messages, you can also create custom error messages. The cmdlet used for doing so is . Additionally, there’s a separate cmdlet called that allows you to generate an error.
Console Output 3
You can use the Write-Error cmdlet to display a custom error message.
Write-Error “This is an example error.” -Category InvalidOperation
You can see an example of how an error category works in Figure 4. Microsoft provides a list of all the available categories
Console Output 4
You can append a category to an error message.
cmdlet is similar to the Write-Host cmdlet, but with two notable differences.
Firstly, Write-Output exclusively supports plain text. You can’t change the text color or add other effects to the text.
The second difference is the automatic enumeration of objects by the Write-Object cmdlet. However, if you want to treat an array as a single object within pipeline operations, you can use the
Granted, this is a bit of a nonsense example, but it illustrates the idea that the output is treated as an object.
Such an operation would not be allowed with the Write-Host cmdlet.
Admittedly, I can’t seem to recall ever having used the Write-Output cmdlet in a script. While I am sure that the cmdlet has its place, I can’t think of anything that Write-Output can do that can’t be done using Write-Host and variables.
Console Output 5
he NoEnumerate switch allows a collection to be treated as a single item.
cmdlet is the standard command used to display text on the console screen in PowerShell. To use this cmdlet, you simply append the text you want to display. For example:
Write-Host “This text will be displayed on the screen.”
Unlike the Write-Output cmdlet, the Write-Host cmdlet allows you to change both the foreground and the background color of the text. Here’s an example:
Write-Host “White text on a blue background” -Foregroundcolor White -BackgroundColor Blue
Console Output 6
The Write-Host cmdlet supports colorful output.
Unfortunately, Write-Host does not support other text effects such as bold or blinking text. While it was once possible to achieve such effects by embedding various ANSI escape sequences, Microsoft appears to have disabled support for ANSI-based text effects within the PowerShell console. Some ANSI escape sequences, like those for creating a new line or inserting a tab, still work, but those related to text color and attributes (bold, underline, etc.) no longer function.
About the Author(s)
Brien Posey is a bestselling technology author, a speaker, and a 20X Microsoft MVP. In addition to his ongoing work in IT, Posey has spent the last several years training as a commercial astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space.
In this article, we will discuss how to send messages to Telegram using PowerShell. PowerShell is a command line shell and scripting language developed by Microsoft to automate and manage system tasks.
Telegram is a popular instant messaging service that provides APIs for interacting with its services. This means that you can use PowerShell to automatically send messages to Telegram.
And you can use PowerShell to automatically send messages to Telegram.
Creating a Telegram bot
- Write @BotFather in the Telegram search box. This is the official bot for creating other bots in Telegram.
- Click on “Start” or “Start” to start interacting with the bot.
- Enter the command “/newbot” and follow the instructions. You will have to choose a name and username for your bot.
- After creating the bot, BotFather will provide you with an access token. This token will be used to authorize requests to the Telegram API.
PowerShell and Telegram API
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$botToken = "Your token"
$chatID = "Your chat id"
$messageText = "Test massage"
$url = "https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatID&text=$messageText"
Invoke-RestMethod -Uri $url -Method Post
In this example, we use the PowerShell command Invoke-RestMethod
to send a POST request to the Telegram API. $botToken
is the access token you received from BotFather, $chatID
is the ID of the chat room you want to send a message to, and $messageText
is the text of the message you want to send.
$messageText
is the text of the message you want to send.
And then you’ll see the chat ID in the reply.
Let’s look at a small script that will send a message that will indicate whether the server is running or not.
To check if the server is available, you can use the PowerShell Test-Connection
cmdlet, which is similar to the ping
cmdlet on the command line. Here’s an example script that sends a message to Telegram, depending on whether the server is available or not:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$botToken = "Your token"
$chatID = "Your chat id"
$serverIP = "Server IP"
# Check server availability
if (-not (Test-Connection -ComputerName $serverIP -Count 1 -Quiet)) { $messageText = "Server down!"
$url = "https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatID&text=$messageText"
Invoke-RestMethod -Uri $url -Method Post }
In this example, the Test-Connection
command checks if the server is available. If the server is unavailable, Test-Connection
returns False
, and thanks to the -not
operator, the condition in if
becomes True
. Then the script sends the message “Warning! The server is unavailable” to Telegram. If the server is available, the script does nothing.
Now you can add this script in your scheduler, to run it, for example, every 30 min. We will see how to do this in the next article.
Conclusion
Organizations in all industries need to ensure the integrity, security, and timely delivery of online messages and emails to improve productivity and streamline workflow.
However, troubleshooting and optimizing email delivery can turn into a real challenge, especially in larger organizations, if you don’t know how to proceed.
In this guide, we’ll explore how to use Get-MessageTrace in PowerShell to ensure efficient email tracing.
What is Get-MessageTrace in PowerShell?
Get-MessageTrace is a PowerShell command used in Microsoft Exchange Online Protection (EOP) and Office 365 environments to retrieve detailed information about the delivery and status of email messages.
This cmdlet is only available in the cloud-based service, which means it can only trace messages as they flow through organizations that use cloud-based infrastructure.
Get-MessageTrace Cmdlet Syntax & Meaning
Depending on the parameters, the cmdlet input and output types will change based on your needs.
Each one of these switches and parameters has a meaning. This is a complete list and breakdown of this cmdlet’s full meaning:
- EndDate <DateTime>: Specifies the end date and time for the message trace query, indicating the upper limit for the time range of messages to be included in the results;
- FromIP <String>: Filters messages based on the source IP address from which the emails originated;
- MessageId <MultiValuedProperty>: Allows you to specify one or more message IDs to retrieve details about specific email messages;
- MessageTraceId <Guid>: Specifies the unique identifier (GUID) of a specific message trace. Useful for retrieving details about a particular message trace;
- Page <Int32>: Specifies the page number when retrieving a large set of results. Helps in navigating through the pages of the result set;
- PageSize <Int32>: Sets the number of entries to be displayed on each page of the result set. Useful for controlling the granularity and precision of the output;
- ProbeTag <String>: Filters messages based on the probe tag. A probe tag is associated with messages used for testing or monitoring purposes.
- RecipientAddress <MultiValuedProperty>: Filters messages based on the email addresses of the recipients, useful if you want to generate a report by recipient address;
- SenderAddress <MultiValuedProperty>: Filters messages based on the email addresses of the senders;
- StartDate <DateTime>: Specifies the start date and time for the message trace query, indicating the lower limit for the time range of messages to be included in the results;
- Status <MultiValuedProperty>: Filters messages based on their delivery status, allowing you to focus on messages with specific statuses;
- ToIP <String>: Filters messages based on the destination IP address to which the emails were delivered.
What Can You Use The Get-MessageTrace Command For?
- Email Delivery Tracking: Use Get-MessageTrace to track the delivery status and path of specific email messages;
- Security Threat Detection: Identify and investigate potential security threats, such as phishing attempts, through the analysis of message traces;
- Compliance and Auditing: Meet compliance requirements by auditing and tracking email communication within the organization using message trace data;
- Email Flow Monitoring: Monitor the overall health of your email system by reviewing message trace data and identifying patterns or anomalies in email traffic;
- Policy Enforcement and Optimization: Enforce email policies and optimize email delivery based on the analysis of message trace data, ensuring compliance and efficient communication.
Prerequisites to Run Get-MessageTrace in PowerShell
According to Microsoft Resources, these are the prerequisites to comply with before being able to run this command:
- Connect to Exchange Online: Use a valid Microsoft Account with admin credentials to connect to Exchange Online PowerShell. Then, move on to the following step.
- Run the Get-ManagementRole Command: Once you have logged into your Microsoft Account, run the following command: Get-ManagementRole -Cmdlet <Cmdlet>. Replace <Cmdlet> with Get-MessageTrace, and press enter.
- Check the Required Permissions: After running the command, PowerShell will return the list of roles necessary to run Get-MessageTrace. If you need additional roles or permissions, you’ll need to contact your organization administrator for further assistance.
How to Use Get-MessageTrace in PowerShell
Now that you know what Get-MessageTrace is for, it’s time to learn how to use it.
Before continuing, it is important to mention that the output of this command highly depends on its parameters.
Below, we’ll show you how to use Get-MessageTrace to retrieve emails for certain data ranges, allowing you more control over email workflows.
Step 1: Connect to Exchange Online PowerShell
Step 2: Run Get-MessageTrace to See Recent Message Trace Records
After accessing Exchange Online PowerShell and ensuring you have all the required permissions, it’s time to run the Get-MessageTrace cmdlet.
According to Microsoft, running this cmdlet without any parameters will only retrieve data from the last 48 hours.
The output of the cmdlet will look like this, depending on your organization’s size and the number of emails tracked:
Need a paper notebook? | ||||
How are you doing? | ||||
I’m here if you need something | ||||
Latest company report |
Step 3: Set a Specific Date Range with Message Trace in PowerShell
On the other hand, if you want to perform email tracing for certain dates or for specific addresses, then it’ll be necessary to modify the cmdlet a bit more.
Get-MessageTrace -StartDate <mm/dd/yyyy> -EndDate <mm/dd/yyyy> |
Of course, the aforementioned cmdlet could be modified to add more parameters based on the information you want to retrieve.
Get-MessageTrace Errors, Limitations, & How to Fix Them
- It is not possible to set the start date on Get-Message Trace older than 10 days, meaning it can’t trace email data greater than 10 days old. Otherwise, the output will return an error message. If you want to see the processing of email messages greater than ten days old, Microsoft recommends using the Start-HistoricalSearch and Get-HistoricalSearch cmdlets;
- Running the Get-MessageTrace cmdlet without specific parameters will oftentimes return irrelevant information, as it can cause it to timeout after 1,000 results. To prevent this from happening, make sure to modify the Get-MessageTrace parameters to get a clean output, also referred to as “Get-MessageTrace clean results;”
- In case the cmdlet is not running properly or returning the expected results, try using smaller StartDate and EndDate intervals, opt for a broader time window, check if you have the necessary permissions to run the command, and ask for further help from your organization administrator.
How to Obtain Get-MessageTrace Data in PowerShell
- Get-MessageTrace allows us to trace emails in cloud-based organizations by returning in-detail email information from senders and recipient email addresses as instructed in the command;
- It is advisable to set specific date ranges to retrieve email tracing information. Otherwise, the command’s output will return lists of irrelevant information to your query, mainly if you work at a large organization;
- Keep in mind that the Get-MessageTrace cmdlet has some limitations, such as the impossibility of tracking emails older than 10 days, and a maximum return of only 1,000 results.

Write-Output and Echo in PowerShell
echo ["message"]
echo "This is a sentence."

The output prints the This is a sentence message.
- Text printing.
- Object printing.
- Formatting the output using the
-Format
cmdlets. - Specifying the output encoding.
- Redirecting the output to a file.
- Parameters that allow users to customize the output.
Example of echo in PowerShell
echo "This is another sentence."

$name = "Sara"

echo $name

The output prints the content of the variable.
Available cmdlets are:
Format-Custom
. Customizes the output with different views.Format-Hex
. Shows data in hexadecimal format.Format-List
. Creates lists of objects’ properties.Format-Wide
. Depicts a single object’s property spanning across the screen.Format-Table
. Presents the data in the form of a table.
echo "Number", "Name", "Age", "Location" | Format-Table

Function CheckIfNumberIsPrime($num) {
if ($num -lt 2) {
echo "$num is not a prime number"
}
else {
$isPrime = $true
for ($i = 2; $i -lt $num; $i++) {
if ($num % $i -eq 0) {
$isPrime = $false
break
}
}
if ($isPrime) {
echo "$num is a prime number"
}
else {
echo "$num is not a prime number"
}
}
}
To test the function, run:
CheckIfNumberIsPrime($num)
Replace ($num)
with a prime number, for example:
CheckIfNumberIsPrime(7)

The output confirms seven is a prime number. Next, try 135:
CheckIfNumberIsPrime(135)

The output verifies 135 is not a prime number.
Example of Write-Output in PowerShell
The Write-Output
cmdlet is a powerful command which prints text, objects, and formatted output to the console.
The basic Write-Output
syntax is:
Write-Output [object]
Write-Output "This is another sentence."

Function PrimeNumber?($num) {
if ($num -lt 2) {
Write-Output "$num is not a prime number"
}
else {
$isPrime = $true
for ($i = 2; $i -lt $num; $i++) {
if ($num % $i -eq 0) {
$isPrime = $false
break
}
}
if ($isPrime) {
Write-Output "$num is a prime number"
}
else {
Write-Output "$num is not a prime number"
}
}

Test the function with the number seven by running:
PrimeNumber?(7)

Next, test with 135:
PrimeNumber?(135)

The outputs confirm seven is a prime number while 135 is not.
Write-Host vs. Echo
Write-Output
, on the other hand, writes data to the PowerShell pipeline. The output is displayed on the screen if there is no subsequent command in the pipeline to receive this data.
A key Write-Host
advantage is the customization capability. Write-Host
supports a broader range of formatting options.
To specify the output’s foreground and background colors, use:
Write-Host "Text" -ForegroundColor [Color] -BackgroundColor [Color]
For instance, print a line This sentence is white with a magenta background:
Write-Host "This sentence is white with a magenta background" -ForegroundColor White -BackgroundColor Magenta

The output is displayed in the requested format.
Next, learn how to set environment variables in Windows.
Table of Contents
Scripting Teams Urgent Messages for a Set of Users
A reader asked if it was possible to write a PowerShell script to send chats to a set of people when something important happened, like a failure in an important piece of plant or a medical emergency. They explained that they have the facility to broadcast this kind of information via email, but a lot of their internal communications have moved to Teams and they’d like to move this kind of scripted communication too.
Teams supports urgent messages for one-to-one chats. Originally, these messages were called priority notifications and Microsoft planned to charge for their use. That idea disappeared in the mists of the Covid pandemic, and anyone can send urgent messages today. The nice thing about urgent messages is that Teams pings the recipient every two minutes until they read the message or twenty minutes elapses.
- Run the Connect-MgGraph cmdlet to connect to the Graph. Delegated permissions must be used, and I specified the Chat.ReadWrite and User.Read.All permissions.
- Because the script works with delegated permissions, the chats are sent by the signed-in user. The script runs the Get-MgContext cmdlet to find out what that account is.
- The script sends chats to a set of users. Any Entra ID group will do.
- The New-MgChatMessage cmdlet eventually sends the chat message. Because I want to include an inline image and a mention in the message, work must be done to construct the payload needed to tell Teams what content to post.
- In Graph requests, this information is transmitted in JSON format. PowerShell cmdlets don’t accept parameters in the same way. Three different parameters are involved – the body, the mention, and the hosted content (image uploaded to Teams). Each parameter is passed as a hash table or array, and if the parameter takes an array, it’s likely to include some hash tables. Internally, Teams converts these structures to JSON and submits them to the Graph request. You don’t need to care about that, but constructing the various arrays and hash tables takes some trial and error to get right. The examples included in Microsoft documentation are helpful but are static examples of JSON that are hard to work with programmatically. I use a different approach. Here’s an example of creating the hash table to hold details of the inline image:
# Create a hash table to hold the image content that's used with the HostedContents parameter $ContentDataDetails = @{} $ContentDataDetails.Add("@microsoft.graph.temporaryId", "1") $ContentDataDetails.Add("contentBytes", [System.IO.File]::ReadAllBytes("$ContentFile")) $ContentDataDetails.Add("contentType", "image/jpeg") [array]$ContentData = $ContentDataDetails
- After populating the hash tables and arrays, the script runs the New-MgChat cmdlet. If an existing one-on-one chat exists for the two users, Teams returns the identifier of that chat thread. If not, Teams creates a new chat thread and returns that identifier.
- The script runs the New-MgChatMessage cmdlet to post the prepared message to the target chat thread. Setting the importance parameter to “urgent” marks this as a Teams urgent message.
$ChatMessage = New-MgChatMessage -ChatId $NewChat.Id -Body $Body -Mentions $MentionIds -HostedContents $ContentData -Importance Urgent
The Urgent Teams Message

You can download the script from GitHub.
Plain Sailing After Understanding Parameter Formatting
There’s no doubt that it’s more complicated to create and send one-to-one chats than it is to send email to a group of recipients, especially if you stray away from a very simple message body. However, much of the complexity is getting your head around the formatting of parameter input. Once you understand that, it’s reasonably easy to master the rest of the code.
Learn about using the Microsoft Graph PowerShell SDK and the rest of Microsoft 365 by subscribing to the Office 365 for IT Pros eBook. Use our experience to understand what’s important and how best to protect your tenant.
Key Takeaways
- Customizing Windows login messages enhances security and user experience.
- The provided PowerShell script offers a swift method to update login titles and messages.
- Admin privileges are required due to changes in the system registry.
- The script is compatible with Windows 10 and Windows Server 2016 onwards.
- While Group Policy Objects can perform similar tasks, this script provides quicker, more agile adjustments.
- Misuse, like sharing sensitive information via login messages, can pose security threats.
- Always test the script in a sandboxed environment before wide deployment.
- Platforms like NinjaOne further facilitate management and deployment of such scripts across large networks.
Background
The Script
#Requires -Version 5.1 <# .SYNOPSIS Changes the logon title and message. .DESCRIPTION Changes the logon title and message. .EXAMPLE -Title "My Title" -Message "My Logon Message" Set the title and message. .EXAMPLE PS C:> Set-LogonMessage.ps1 -Title "My Title" -Message "My Logon Message" Set the title and message. .OUTPUTS None .NOTES Minimum OS Architecture Supported: Windows 10, Windows Server 2016 Release Notes: Renamed script and added Script Variable support, updated Set-ItemProp By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use. Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA). .COMPONENT OSSecurity #> [CmdletBinding()] param ( [Parameter()] [String]$Title, [Parameter()] [String]$Message ) begin { if ($env:title -and $env:title -notlike "null") { $Title = $env:title } if ($env:message -and $env:message -notlike "null") { $Message = $env:Message } function Test-IsElevated { $id = [System.Security.Principal.WindowsIdentity]::GetCurrent() $p = New-Object System.Security.Principal.WindowsPrincipal($id) if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Output $true } else { Write-Output $false } } function Set-ItemProp { param ( $Path, $Name, $Value, [ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")] $PropertyType = "DWord" ) # Do not output errors and continue $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue if (-not $(Test-Path -Path $Path)) { # Check if path does not exist and create the path New-Item -Path $Path -Force | Out-Null } if ((Get-ItemProperty -Path $Path -Name $Name)) { # Update property and print out what it was changed from and changed to $CurrentValue = Get-ItemProperty -Path $Path -Name $Name try { Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null } catch { Write-Error $_ } Write-Host "$Path$Name changed from $CurrentValue to $(Get-ItemProperty -Path $Path -Name $Name)" } else { # Create property with value try { New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null } catch { Write-Error $_ } Write-Host "Set $Path$Name to $(Get-ItemProperty -Path $Path -Name $Name)" } $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue } } process { if (-not (Test-IsElevated)) { Write-Error -Message "Access Denied. Please run with Administrator privileges." exit 1 } try { Set-ItemProp -Path "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem" -Name "legalnoticecaption" -Value $Title -PropertyType String Set-ItemProp -Path "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionPoliciesSystem" -Name "legalnoticetext" -Value $Message -PropertyType String } catch { Write-Error $_ exit 1 } } end { }
Access 300+ scripts in the NinjaOne Dojo
Detailed Breakdown
Let’s delve into the mechanics of the script:
- Cmdlet Binding and Parameters: The script is designed as a PowerShell function using the CmdletBinding attribute. This means the script can be used as a reusable function and can accept parameters, specifically the title and message for the login prompt.
- Administrator Check: Two embedded functions are utilized, Test-IsElevated and Set-ItemProp. The former checks if the script is run with administrator privileges, vital since modifying registry keys (which the script does) requires elevated permissions.
- Registry Modifications: The Set-ItemProp function either modifies existing registry values or creates new ones. The script targets two primary keys, legalnoticecaption (for the title) and legalnoticetext (for the message), which govern the login message on Windows.
Potential Use Cases
Comparisons
While Group Policy Objects (GPO) can also be used to set login messages, this script offers a more agile approach. GPOs might take time to propagate and may not be suitable for rapid changes. The PowerShell script, on the other hand, can be swiftly executed on a machine-by-machine basis or deployed widely via a system management tool.
FAQs
- Can this script be run on any Windows machine?
It’s designed for Windows 10 and Windows Server 2016 and above. Earlier versions may not support the involved cmdlets. - Is it necessary to run the script with administrative rights?
Yes, since it modifies the system registry, elevated permissions are mandatory.
Implications
Recommendations
- Ensure clarity and brevity in your login messages.
- Test the script in a controlled environment before broad deployment.
- Maintain regular backups of your system registry.