In Every day, sysadmins have to perform various standard operations on the numerous files and folders on their Windows servers like creating directory and copy files from one location to another, finding duplicated files etc., Here we will discuss how create a directory with the help of Powershell. For this, please open PowerShell console with administrative privileges.
I hope you have an idea of different methods for Creating a Directory with PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Mostly you will use common notification like display message in console using Write-* cmdlets to write the text to the console and Commonly we use Write-Error or Write-Warning for displaying Error and warnings.
Apart from displaying the message through the console, sometimes we required to get the user’s attention when something has completed or an issue is encountered. In that case, a pop-up window will helps you to built and displayed to the information/Warning/Error to the User. In this type of situation, we can implement the Balloon Tool Tip notification.
To achieve this, we need to work with the System.Windows.Forms.NotifyIcon type to build our notification balloon tip.
STEP 1# :
To get started, you need to load up an assembly to take advantage of a method that will help to extract the icon image from the file.
Add-Type -AssemblyName System.Windows.Forms
STEP 2# :
Second, you need to add the System.Windows.Forms assembly into our PowerShell session before we can make use of the NotifyIcon class. So your function would have to check whether there is already an icon that you can reuse. This is done by using a “shared variable”, which really is a variable that has “script:” scope. Shared variables will be active their value as long as the script runs.
if ($script:balloonToolTip -eq $null) { $script:balloonToolTip = New-Object System.Windows.Forms.NotifyIcon }
STEP 3# :
Then you want to set the system tray icon of the PowerShell ISE by just locating its path via Get-Process and locating the Path property. After you have the path, then you need to extract the icon from the file so it can be applied to the Icon property.Using this approach, you can pull any icon from a file and use it for the system tray icon when the balloon tip is launched.
As per above statement, the Get-Process -id $pid command gets the PowerShell process that is hosting the current session.The ExpandProperty expands the collections, that is, it will output the properties of every object in the collection. For example the out of $path variable will be “C:\windows\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe”
function ShowBalloonTipInfo
{
[CmdletBinding()]
param
(
[Parameter()]
$Text,
[Parameter()]
$Title,
#It must be 'None','Info','Warning','Error'
$Icon = 'Info'
)
Add-Type -AssemblyName System.Windows.Forms
#So your function would have to check whether there is already an icon that you can reuse.This is done by using a "shared variable", which really is a variable that has "script:" scope.
if ($script:balloonToolTip -eq $null)
{
#we will need to add the System.Windows.Forms assembly into our PowerShell session before we can make use of the NotifyIcon class.
$script:balloonToolTip = New-Object System.Windows.Forms.NotifyIcon
}
$path = Get-Process -id $pid | Select-Object -ExpandProperty Path
$balloonToolTip.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balloonToolTip.BalloonTipIcon = $Icon
$balloonToolTip.BalloonTipText = $Text
$balloonToolTip.BalloonTipTitle = $Title
$balloonToolTip.Visible = $true
#I thought to display the tool tip for one seconds,so i used 1000 milliseconds when I call ShowBalloonTip.
$balloonToolTip.ShowBalloonTip(1000)
}
ShowBalloonTipInfo ("The Notification from Dotnet-helpers : ","Read the latest topics of poweshell from dotnehelpers.com")
One of the simplest way to build simple message boxes in PowerShell is to “borrow” from .NET COM objects. Basically you initialize the object, and then you need to create instances of the object and finally call the Popup method. These messagebox code may be familiar to anyone who has programmed in vbScript, or any of the Microsoft programming languages such as Visual Basic or C#. The boxes can look pretty good, even though the coding is a bit monster.
In simple, all it really takes is two lines. One line to create the Wscript.Shell COM object and one to invoke the Popup method. Before the execution, let we discuss about the syntax below
The command will write the return value of the clicked button to the pipeline as shown below
Button the return value :1 – OK button ,2 -Cancel button , 3 – Abort button , 4 – Retry button ,5 – Ignore button , 6 – Yes button , 7 – No button
Example #1:
#creating object os WScript
$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop
#invoking the POP method using object
$wshell.Popup("Are you want to continue from here?",5,"Hello User?",48+4)
Script Explanation:
From the syntax, please find parameter values.
strText : Are you want to continue from here? nSecondsToWait : 5 (wait for 5 second) strTitle : Hello User? nType : 48+4 (Exclamation Mark icon + Yes and No buttons) IntButton : Get the selected input as show in below table
OUTPUT:
What do you think?
I hope you have an idea of How to display a pop-up message box with PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Monitoring the Computer up-time is an important statistic in systems management.There are several ways we can retrieve a computer’s uptime using WMI (Windows Management Instrumentation) . PowerShell provides an easy way to accomplish this with the Get-WMIObject commandlet, In this post we will discuss how you can get both the last boot time as well as the current up time for a computer.
Step #1: The first step you need get the required WMI Object Class and its property for the last boot-up time. Finally assing the value to variable
Step #2: The second step is to convert the property of LastBootUpTime to a Date and Time object. If you try $userSystem.LastBootUpTime commands then you will see that the output is not an user-friendly because the date and time expressed in the property is formatted as a CIM (Common Information Model) date time string. So its necessary to user conversion to see friendly format.
#Getting Last Boot time $userSystem.ConvertToDateTime($userSystem.LastBootUpTime)
Step #3: We you can determain and print the Last Boot Time
I hope you have an idea of how to Getting Computer Up-time Using PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Mostly we will simply copy an already created shortcut but With PowerShell you can create a shortcut by using the New-Object cmdlet. Let we look in to this detail below. Here’s a quick script to create a shortcut to Notepad and put it on the desktop.
Step #1: The First step is to define the location and name of your shortcut. The following example will add the shortcut to the user’s desktop with a name of Your Shortcut.
Step #4: The final step is to envoke the Save() method to save your shortcut.
$Shortcut.Save()
Final Code
# Create a Shortcut with Windows PowerShell
$SourceFileLocation = "$env:SystemRoot\System32\notepad.exe"
$ShortcutLocation = "C:\Users\thiyagu.a.selvaraj\Desktop\Notepad.lnk"
#New-Object : Creates an instance of a Microsoft .NET Framework or COM object.
#-ComObject WScript.Shell: This creates an instance of the COM object that represents the WScript.Shell for invoke CreateShortCut
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation)
$Shortcut.TargetPath = $SourceFileLocation
#Save the Shortcut to the TargetPath
$Shortcut.Save()
What do you think?
I hope you have an idea of how to create the Create Shortcuts on Desktops using Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Most we will use the graphic interface of Taskschd.msc console to create Windows Task Scheduler jobs and Building a single scheduled task via the GUI task scheduler might not be a big deal. But if you find yourself creating scheduled tasks repeatedly it might be a good idea to use a method that scales better than a GUI like PowerShell. However, in various scripts and automated jobs, it is much more convenient to use the PowerShell features to create scheduled tasks. In this article, we will discuss about how to create new Windows Scheduler tasks using PowerShell.
PowerShell v4 introduced a ScheduledTasks module that greatly simplified the times of creating Task Scheduler COM objects to build scheduled tasks from the command line. To create Task Scheduler, we can utlize the below setting.
Example: Passing PS file as argument
# Specify the trigger settings
$trigger= New-ScheduledTaskTrigger -At 10:00am –Daily
# Specify what program to run and with its parameter
$action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\dotnet-helpers\TestScript.ps1"
# Specify the name of the task
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "EventLog" -Description "Application Logs"
Example: Passing scrip as argument
# In argument section - The script will get the evetlog and save in the excel in specific location.
$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {get-eventlog -logname Application -After ((get-date).AddDays(-2)) | Export-Csv -Path c:\dotnet-helpers\eventlog.csv -Force -NoTypeInformation}"'
$trigger = New-ScheduledTaskTrigger -Daily -At 7:41PM
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "EventLog" -Description "Application Logs"
OUTPUT
Explanation
New-ScheduledTaskAction
The New-ScheduledTaskAction cmdlet creates an object that contains the definition of a scheduled task action. A scheduled task action represents a command that a task executes when Task Scheduler runs the task.
New-ScheduledTaskTrigger
The New-ScheduledTaskTrigger cmdlet creates and returns a new scheduled task trigger object.
New-ScheduledTaskPrincipal
Creates an object that contains a scheduled task principal. Using this we can registers a scheduled task that will run as the Local Service account or scheduled task that runs under logged-in members of the Administrators user group that has the highest privileges.
New-ScheduledTaskSettingsSet
The New-ScheduledTaskSettingsSet cmdlet creates an object that contains scheduled task settings. Each scheduled task has one set of task settings.
New-ScheduledTask
The New-ScheduledTask cmdlet creates an object that contains the definition of a scheduled task. New-ScheduledTask does not automatically register the object with the Task Scheduler service.
Register-ScheduledTask
The Register-ScheduledTask cmdlet registers a scheduled task definition on a local computer.
What do you think?
I hope you have idea of how to create Task in Window task scheduler using Powershell . I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Managing drives, monitoring space to ensure that a drive run out of available capacity and to understanding just how many drives are on a single system this are simply able to monitor using PowerShell instead of manual monitoring. WMI – Windows Management Instrumentation can be a wealth of information that anyone should be able to query to get pretty much whatever information they need.
#Look at only local drives
Get-WmiObject -Class Win32_logicaldisk -Filter "DriveType = '3'"
In this post, we going to discuss about very simple query to get the Drive information. You can run the below query using the Get-WMIObject cmdlet to get more information about all of the drives on your system. From the above output, you can able to see that we have the DeviceID, which is the drive letter assigned to the drive; the FreeSpace, which is measured in bytes, as well as the capacity (size) of the drive; along with the volume name that has been specified.
Using the above information you can able to easily filter using the query for only drives that matched a certain type and while viewing the size in bytes is necessary to keep the size at the lowest possible level, sometimes it is nice to see it in a more readable format, such as in GB like below, The property is specified by a hash table with two keys, Label and Expression.The name of the property is assigned to the Label key. The calculation is assigned to the Expression key.
Dot-sourcing is a concept in PowerShell that allows you to reference code defined in one script.
When you writing large size of PowerShell scripts, then there always seems to come a time when a single script just isn’t enough. If we working on large size of script then it important to keep your scripts Simple and Reusable, so you can keep your block of script as modular. The Dot-sourcing is a way to do just that. Making script as modular it also useful when requirment came for adding some more functionlaiyt in exting script. Other than building a module, dot-sourcing is a better way to make that code in another script available to you.
For example, let’s say I’ve got a script that has two functions in it. We’ll call this script CommunicateUser.ps1. Here i had created single module which contain the two functionality in single file which used for sending email and SMS to the customer.
CommunicateUser.ps1
function SendEmail {
param($EmailContent)
#Write your Logic here
Write-Output "****************************************"
Write-Output "Sending Mail" $EmailContent
Write-Output "****************************************"
}`
function SentSMS {
param($SMSContent)
#Write your Logic here
Write-Output "****************************************"
Write-Output "Sending SMS" $SMSContent
Write-Output "****************************************"
}
Now i had created another script called UpdateUser.ps1. Here we needs to invoke those functions for sending the information to user. The CommunicateUser.ps1 script is located on the root of my C drive, so we can just put a period followed by a space and then the path of the script like shown below.
UpdateUser.ps1
# My CommunicateUser.ps1 script were located on the root of my C drive, so I just put a period, followed by a space and then the path of the script.
. C:\Users\MYPC\Desktop\PowerShell\CommunicateUser.ps1
$mailContent = 'MAIL - Hi Welcome to dotnet-helpers.com'
$smsContent = 'SMS - Hi Welcome to dotnet-helpers.com'
# Method Name (SendEmail) Parameter Name (-EmailContent) Parameter Value ($mailContent)
SendEmail -EmailContent $mailContent
SentSMS -SMSContent $smsContent
To make those functions available in the same scope, let we invoked CommunicateUser.ps1 script now, so now SendEmail and SentSMS are now available in the scope for use. To dot source a script is very simple. I’ll now dot source my functions script inside of my CommunicateUser.ps1 script.
OUTPUT:
What do you think?
I hope you have an idea of how to utilize the dot-sourcing concept in Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
When writing larger scripts, logging is a must, so in this post I will share a simple function for logging PowerShell script. PowerShell scripts can easily be written without any kind of help content, documentation, commenting, or logging. Functionally, these scripts will sometimes work just fine, but what happens it failed in some case? You soon find yourself pulling your hair out trying to troubleshoot and debug this script in the most inefficient way possible. So logging the error is the best practice to handle the huge script.
One way to build in some kind of monitoring and troubleshooting assistance is through logging.
#This creates a log file with a date and time stamp
$logfile = "C:\EMS\dotnet-helpersErrorLog_$(get-date -format `"yyyyMMdd_hhmmsstt`").txt"
#this is our logging function, it must appear above the code where you are trying to use it.
function logger($val1 , $val2)
{
try
{
echo $val1 $val2
if ($val1 -eq 'Fail')
{
"Wrong Input passed so it was logged as error" + $val1 | out-file -Filepath $logfile -append
}
}
catch
{
$_.Exception.Message | out-file -Filepath $logfile -append
}
}
#Calling Logger function and passing parameters
logger 'Dotnet-helpers.com','Pass'
logger 'Dotnet-helpers.eu','Fail'
OUTPUT
What do you think?
I hope you have an idea of how to create simple log files for handling the issue. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
For this article, I would encourage you to un-mute your speakers and keep them at a reasonable level,or use headphones in case you are going through this in a public area or at work so you do not bother your neighbors.
Which scenario SPEAK class will required?
IF when you have a script that’s going to run a long time, say 10-20 minutes. We all KNOW that we’re not going to sit there and watch the output!. In this scenario, PowerShell talk when some condition comes up and its is really useful if you’ve relegated the window to the background and are doing something else like working with other items.
Example of Real Scenario:
In below sample code the script will start to check the 10 lakhs record for finding the detail of specific user. If it match with user id it start specking with user details, so it will be make aware of the details by informaging through voice, if we working with other items.
#Loop through 1000000 users
foreach ($userId in $ListOfUsers)
{
if ($userId -eq '1456')
{
write-host "Got the User details"
write-host $userId
$speak.speakAsync("We found the User $($userId.FirstName) $($userId.LastName)")
}
Example: 1
The first thing that we want to do is create our SpeechSynthesizer object and then we can utilize the methods in it. During the execution of below script, the speak method talk which mentioned in the double quotes ie., “Hello from dotnet-helpers”.
ADD-TYPE -AssemblyName System.Speech
$speak = new-object System.Speech.Synthesis.SpeechSynthesizer
$speak.speakAsync("Hello from dotnet-helpers!")
$speak.Speak("The current date and time is $(Get-Date)")
If you wanted to increase the volume of the voice, you can adjust the Volume property from 0-100 on your object.You can even control the rate at which the words are spoken to you.
$speak.Volume = 100
If you want a faster response, you can also increase the rate to something like 10 using “Rate”.
Speed it up!
$speak.Rate = 10 $speak.speakAsync(“Hello from powershell!”)
Slow it down!
$speak.Rate = -10 $speak.speakAsync(“Hello from powershell!”)
What do you think?
I hope you have an idea of how to use the PowerShell SpeechSynthesizer during our long time execution for the output. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.