When you are running a Windows server and you need to find out the specification of your servers then this tutorial will helps you to achieve with the help of PowerShell script.
Step 1#: Open PowerShell with secific privileges.
Step 2#: Execute below script to get the specifications of the Servers
Get-wmiobject : Gets instances of WMI classes or information about the available classes. win32_computersystem: The Win32_ComputerSystem WMI class represents a computer system running Windows. win32_processor : Its WMI class represents a device that can interpret a sequence of instructions on a computer running on a Windows operating system.
OUTPUT:
What do you think?
I hope you have an idea of How to Find Out Specifications of Server Using PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
In many scenarios, we will get the requirement to upload the reports, tracker from one location to another location , so i decided to write this post to explain how to upload files like excel, txt… with the help of Powershell GUI. Instead of thinking high level, here i had split the three simple task to achieve the file upload functionality in the Powershell.
Create Simple PowerShell UI for browsing the location of files with one textbox and two button type (upload & cancel) with help of system.Windows.Forms
In Browse button click event, you can perform the browse with the specific file that need to be upload to destination folder using New-Object -TypeName System.Windows.Forms.OpenFileDialog. These make the selection of files or folders easy for users and prevent mistakes being made in file paths.
In upload button click event, you can perform the Move action on the selected file to place on Target location.
When designing PowerShell scripts, I have often found it useful to incorporate a file or folder dialogue to select files or folders. These make the selection of files or folders easy for users and prevent mistakes being made in file paths.
Example:
#######################################################
#Project : Upload the files using Powershell
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155
#E-Mail : mail2thiyaguji@gmail.com
#######################################################
#Form class
$Forms = 'system.Windows.Forms.Form'
#Button class
$Button = 'system.Windows.Forms.Button'
#Getting the font details for applying the fields
$FontStyle = 'Microsoft Sans Serif,10,style=Bold'
$SysDrawPoint = 'System.Drawing.Point'
# setting InitialDirectory which open as intially during the click of browse button
$InitialDirectory = "C:\New folder"
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
#The New-Object cmdlet creates an instance of a .NET Framework or COM object.
#Specifies the fully qualified name of the .NET Framework class. You cannot specify both the TypeName parameter and the ComObject parameter.
$TrackerFileUpload = New-Object -TypeName $Forms
$TrackerFileUpload.ClientSize = '400,114'
$TrackerFileUpload.text = 'dotnet-helpers.com - Please upload Daily Tracker'
$TrackerFileUpload.TopMost = $false
$txtFileName = New-Object -TypeName system.Windows.Forms.TextBox
$txtFileName.width = 280
$txtFileName.height = 20
$txtFileName.location = New-Object -TypeName $SysDrawPoint -ArgumentList (107,39)
$txtFileName.Font = $FontStyle
$btnFileBrowser = New-Object -TypeName $Button
$btnFileBrowser.BackColor = '#1a80b6'
$btnFileBrowser.text = 'Browse'
$btnFileBrowser.width = 96
$btnFileBrowser.height = 30
$btnFileBrowser.location = New-Object -TypeName $SysDrawPoint -ArgumentList (200,78)
$btnFileBrowser.Font = $FontStyle
$btnFileBrowser.ForeColor = '#ffffff'
$btnUpload = New-Object -TypeName $Button
$btnUpload.BackColor = '#00FF7F'
$btnUpload.text = 'Upload'
$btnUpload.width = 96
$btnUpload.height = 30
$btnUpload.location = New-Object -TypeName $SysDrawPoint -ArgumentList (291,78)
$btnUpload.Font = $FontStyle
$btnUpload.ForeColor = '#000000'
$lblFileName = New-Object -TypeName system.Windows.Forms.Label
$lblFileName.text = 'Choose File'
$lblFileName.AutoSize = $true
$lblFileName.width = 25
$lblFileName.height = 10
$lblFileName.location = New-Object -TypeName $SysDrawPoint -ArgumentList (20,40)
$lblFileName.Font = $FontStyle
#Adding the textbox,buttons to the forms for displaying
$TrackerFileUpload.controls.AddRange(@($txtFileName, $btnFileBrowser, $lblFileName, $btnUpload))
#Browse button click event
$btnFileBrowser.Add_Click({
Add-Type -AssemblyName System.windows.forms | Out-Null
#Creating an object for OpenFileDialog to a Form
$OpenDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
#Initiat browse path can be set by using initialDirectory
$OpenDialog.initialDirectory = $initialDirectory
#Set filter only to upload Excel file
$OpenDialog.filter = '.xlsx (*(.xlsx)) | *.xlsx | *.txt'
$OpenDialog.ShowDialog() | Out-Null
$filePath = $OpenDialog.filename
#Assigining the file choosen path to the text box
$txtFileName.Text = $filePath
$TrackerFileUpload.Refresh()
})
#Upload button click eventy
$btnUpload.Add_Click({
#Set the destination path
$destPath = 'C:\EMS\Destination'
#$txtFileName.Text = ""
Copy-Item -Path $txtFileName.Text -Destination $destPath
})
$null = $TrackerFileUpload.ShowDialog()
$txtFileName.Text = ""
Output:
What do you think?
I hope you have an idea of How To upload the files with help of PowerShell GUI. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Mostly No one have interest to wait for some time to complete the work/task/execution.But in certain situation, that’s is not always possible to completed the task without waiting for few seconds/Minutes. In Powershell if you wrote some automation and if sometimes it will to be take more time to execution due to gathering lot of information from then, reality, the script will take a time to complete.
In this scenario the script writer need to show some progress bar to indicate the user about the progress instead of blinking cursor at the delay. This can be achievable by using Write-Progress cmdlet which Displays a progress bar within a Powershell command window.
############################################################
#Project : How To Create Progress Bars in PowerShell
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155
#E-Mail : mail2thiyaguji@gmail.com
############################################################
$progressTimes = 20
$ioop_index = 0
for ($ioop_index=0;$ioop_index -lt $progressTimes; $ioop_index++) {
$completeStatus = ($ioop_index / $progressTimes) * 100
#Write-Progress: Displays a progress bar within a PowerShell command window.
#-Activity: Specifies the first line of text in the heading above the status bar. This text describes the activity whose progress is being reported.
#-Status: Specifies the second line of text in the heading above the status bar. This text describes current state of the activity.
#-PercentComplete: This command displays the progress of a For loop that counts from 1 to 20.
Write-Progress -Activity 'in Progress' -Status "Did thing $ioop_index times" -PercentComplete $completeStatus -SecondsRemaining ($progressTimes-$ioop_index)
#Suspends the activity in a script or session for the specified period of time.
Start-Sleep 1
}
Output:
What do you think?
I hope you have an idea of How To Create Progress Bars in PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
For most of the automation and report we will prefer and use Excel , instead of excel her we look at how you can use Word with PowerShell to create a document.One of the first things that you need to do is ensure that you have Word installed on your computer. Once you have that verified, we can begin by creating a COM object connection to Word.Application, which will help us to begin the interacting with Word.
Running the below script that was just looking to create the document without showing anything, and making Visible property on the object to True. So after creating this object ($word) which will help to interacting with Word and its ready for our operations.
Now we are ready to begin to edit and start writing in our Word document.Here i am going to generate the comments document from the PowerShell script, so you can achieve this using the TypeText() method, which is available on $myDoc object.
If we use of the TypeText method, the we need to understand the text will appear on the same line as the rest of the text. So we need to use the TypeParagraph method which use to start on a new line like break tag in HTML and then you use TypeText to begin writing on a brand-new line.
$myDoc.Style=”Strong” $myDoc.TypeParagraph() $myDoc.TypeText(“Hi All, “) $myDoc.TypeParagraph() $myDoc.TypeText(“This is Message from dotnet-helpers.com “)
Final Code:
#######################################################
#Project : Writing in Word doc using Powershell
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155
#E-Mail : mail2thiyaguji@gmail.com
#######################################################
$savepath="C:\dotnet-helpers\ReviewCommends.docx"
$word=new-object -ComObject "Word.Application"
$Word.Visible = $True
$doc = $word.documents.Add()
$myDoc = $word.Selection
$myDoc.Style="Strong"
$myDoc.Font.Bold = 1
$myDoc.TypeParagraph()
$myDoc.TypeText("Hi All, ")
$myDoc.TypeParagraph()
$myDoc.TypeText("This is Message from dotnet-helpers.com ")
$myDoc.Style="Normal"
$myDoc.Font.Italic = 1
$myDoc.TypeParagraph()
$myDoc.TypeText("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes,nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu,
pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel,aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae")
$myDoc.TypeParagraph()
$myDoc.TypeParagraph()
$myDoc.TypeText("Thanks")
$myDoc.TypeParagraph()
$myDoc.Style="Strong"
$myDoc.TypeText("Thiyagu S")
$myDoc.TypeParagraph()
$Date = Get-Date
$myDoc.TypeText("Date: $($Date)")
$doc.SaveAs([ref]$savepath)
$doc.Close()
$word.quit()
Invoke-Item $savepath
#Here you want to release all of these objects, so here we call the ReleaseComObject method, so we doing this each of objects which created.
#then you need to call garbage collection to scavenge memory, and I remove the variables.
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
Remove-Variable doc,Word
[gc]::collect()
[gc]::WaitForPendingFinalizers()
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.
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.