Skip to main content

Posts

Showing posts with the label PowerShell

PowerShell Tip : How to fetch XML Event Data log using Powershell

  So Today, one of the member of our PowerShell Forum asked me the question - How to Fetch the XML Event Data like Prop_DeviceName , Prop_ContainerID etc of a specific event ID 112 from the event log. So here is the solution for the same. In this example we will use the cmdlet Get-WinEvent and will try to grab the details. CODE : Get-WinEvent -FilterHashtable @{Logname="Microsoft-Windows-DeviceSetupManager/Admin";Id=112} -MaxEvents 1 | %{ $eventXml = ([xml]$_.ToXml()).Event $eventXml.EventData.Data } OUTPUT : You can modify the script as per your need. Happy Learning!

PowerShell Tip : How to copy a file remotely using WINRM

Today, we are going to see how to copy a file to remote destination using WINRM. Traditionally SMB Protocol (File Sharing \\Servername\C$) was used to transfer the files but nowadays you will find SMB Protocol disabled on some servers so you will require firewall changes to perform that.  On the other hand WINRM Protocol 5985 is mostly open for Powershell Remote sessions, so we will use that to transfer the files. Lets get started : Step 1 : Create a PS Session for that server  $Session = New-PSSession -ComputerName <ServerName> Step 2 : Use Copy-Item with -ToSession to transfer the file using WINRM Copy-Item -Path C:\Scripts\Amar\TestFile.txt -ToSession $Session -Destination "D:\" TestFile.txt file will get copied from local system to the D Drive of the remote server. Happy Learning :)

PowerShell Tip : How to find Host node name from inside the VM

Let's assume a scenario where you are inside the Virtual Machine but you want to the know the Host node name. Unless you maintain some inventory management system, it would be a troublesome job to identify the same. Here is how this can be achieved using Powershell. Just run the below one-liner on the VM : (Get-item "HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters").GetValue("HostName")

Powershell Tip : How to fetch public ip using Powershell Console

There are several ways to fetch your public ip like below : But today we are going to see the simplest way to fetch the same via Powershell console : Command : (Invoke-WebRequest -uri "http://ifconfig.me/ip").Content

Powershell Tip : How to find the IP Address of a VM from a HyperV

Today we are going to see how to fetch the IPv4 Address details of a VM from a HyperVisor console. We will be using Powershell to achieve the same with a One-Liner code.  You can modify the Command as per your need. Our requirement is to check Only the Running VM's and  get the VM Name and its corresponding IPv4 Address. So lets get started. CODE (Execute in HyperV ): Get-VM | ? State -eq "Running" | select Name, @{l="IPv4Address";e={($_.NetworkAdapters.IPAddresses -match "(?<Address >((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))")} } CODE DETAILS : 1. Get-VM : Fetches the VM List present on the HyperVisor 2. ? State -EQ "Running" : It is similar to Where-Object {$_.State -eq "Running"} , here we are using where-object to fetch only the Running VM list from the Pipeline. 3. NetworkAdapters properties of the VM Contains the IPAddresses information, we are using IPv4 address Regex to get

Powershell Tip : How to Change the Error Foreground Color in PowerShell

For one or the other reason we sometimes don’t like the "Red colored ERROR" which we used to get when we come across some error in powershell like below : So lets change this red color shown in the console, although its of no use(i.e technically speaking, it will work in the same way) but still just for learning purpose lets do it. In order to make this ERROR Foreground as any other color(over here green), write the below command in the Powershell console. $Host.PrivateData.ErrorForegroundColor = "Green" Output : Quite interesting right, Not only this you can change colors of several properties like Warning, Debug, Verbose etc. Just run  $Host.PrivateData | get-member Hope you all enjoy this Post, Do Like, Share and Comment if you have any suggestion or queries.

Powershell Tip : How to find the disk type of your System ( HDD or SSD )

Hi Friends😀 Today we are going to learn how to find the disk type of your system i.e. whether it is SSD ( Solid State Drive ) or HDD ( Hard Disk Drive ). Powershell has a cmdlet which helps to achieve the same :  Get-PhysicalDisk Get-PhysicalDisk | Select FriendlyName , MediaType , Size

How to Bypass execution policy in Powershell

Hi Geeks, Today we are going to learn the tips and tricks which can be used to bypass or run a Powershell script or command if its blocked using the below methods : 1. RemoteSigned Execution Policy 2. AllSigned Execution Policy 3. Restricted Execution Policy Steps : Source :  Netspi Blog

Powershell interview questions

1. Which is not a built-in variable out of this         a) $Args b) $Hostname c) $Pid d) $? 2. Which one will override the default alias in Powershell a) Set-Alias -Name ls -Value hostname -Scope Local -Force b) Set-Alias -Name ls -Value hostname -Force c) Set-Alias -Name ls -Value hostname -Option AllScope d) None of the above, we can't override the default aliases 3. Out of the below which command won't work ( Renaming directory ) a) Rename-Item "C:\`[Test File`]\" "Test" b) Rename-Item "C:\``[Test File``]\" "Test" c) Rename-Item -LiteralPath "C:\`[Test File`]\" "Test" d) Rename-Item -LiteralPath "C:\[Test File]\" "Test" 4. What is the default execution policy in Powershell     a) Bypass b) Restricted c) UnRestricted d) RemoteSigned 5. W

Powershell Tip: where does recovered file get stored in Powershell ?

Hey Geeks, Hope you are having a great day. Lets come to one of our interesting section i.e Powershell >_ Tip of the Day. Ever wondered if you have some unsaved data in Powershell ISE and ISE process get stopped suddenly either it is through system shutdown or any other means. WHAT HAPPENS TO YOUR UNSAVED DATA?? Once you open ISE you might see that old unsaved data as (untitled*.ps1(Recovered)), But from where did it came. So the answer is here, its the same way Sticky notes saves the unsaved data. Powershell stores it in the below path : $env:USERPROFILE\AppData\Local\Microsoft_Corporation\PowerShell_ISE.exe_StrongName_lw2v3wmtzzpebq33gybmeoxukb04w\3.0.0.0\AutoSaveFiles\ If you already knew this then its great, if not hope you learned something new! Share your thoughts by commenting below. :)

How to get the list of WiFi Passwords stored on your computer using Powershell

Hi Geeks, Today we are going to see how to fetch the list of SSID passwords which are stored on your computer. Although through GUI, we can view the same by checking Wireless Network Properties --> Network Security Key. But today we are going to see how to fetch all the list at once using Powershell instead of checking them individually one by one. So let's get Started : 1. Copy the below Powershell script 2. Execute the powershell Function Get-WiFiPass Hope you all liked this post, do share and comment for any queries. Script Credits : https://github.com/ajackal/ideal-alligator

How to get SID of all Domain Users using PowerShell

Hey All, Today we are going to cover an interesting topic to fetch SID of all domain users. What is SID ? SID (Security Identifier ) is an unique id or value assigned to each and every domain object. Each domain object whether its a Group, User account , Computer , OU is assigned with an unique id in order to get identified by a Domain controller. All these SID's are stored in a Security Database. It looks like  S-1-5-32-545 etc. NOTE :   Domain Controller identifies object with their SID and not with the name. In order to understand this concept, open any box which is in Domain and go to any Folder properties , in Security tab you will observe it will show SID something like  S-1-5-32-545  and then it tries to convert it to name. So Lets Begin There are several ways to find the list of SSID's , I will be covering the easiest ones. 1. To get the list of all the domain users and their SSID Get-WmiObject win32_account | Select FullName,Name,SID,Description |

Use Powershell to Read daily news or get Live Sports updates

Hey guys, today we are going to learn how to get news updates using Powershell. For this we will be using API's provided by newsapi.org  . Through this method we can get news update from CNN, Times of India, ESPN, TechCrunch, The Huffington Post and much more. Steps : 1. Open the url  newsapi.org 2. In order to get you own API key you will need to register on the website, to do so click on "Get API Key" present in the Homepage and register. 3. Once you have registered , you will get an API key, don't share the same with anyone. 4. Next, visit  https://newsapi.org/sources  and select the source from where you want to get the news update. We choose "Times of India" 5. Once done, switch to Powershell ISE , and input the below commands : 6. Save it and Execute, you will get the news update instantly. Further this can used to get LIVE Scores and much more. Hope you all liked it. Do share and Comment if any queries.

How Invoke-Command works

To know how Invoke-Command works remotely check the below image : Apart from this, lets talk more about Invoke-Command. If you run invoke-command locally will this DeSerialization, conversion to XML etc will happen? the answer is NO. Since you are running it locally all this process are not performed. Further a Deserialized object Type i.e. the data fetched remotely through invoke-command contains only few methods as shown in the below image. Hence suppose you are fetching service info using invoke-command remotely and storing the output in a variable, you won’t get methods to Start or Stop the service. Example : $Service = Invoke-Command -Cn “Test” -ScriptBlock {get-service bits} $Service will show the process details, but you can’t perfom $Service.Stop() or $Service.Start() since its the deserialized data. But you can perform like this : $Service = Invoke-Command -Cn “Test” -ScriptBlock {get-service bits | Stop-Service} This will do the task you are lo

How to close a Process run by a specific User using PowerShell

Hi Geeks, Today we are going to learn how to close or kill a process run by a specific user. Lets take an example, there are 2 different users : Admin and TestUser , Now Admin and TestUser both are logged into the same machine and performing some important task in Internet Explorer. If Admin does this : Get-Process -Name “iexplorer” It will get all the list of Internet Explorer process run by both Admin as well as TestUser. Now Admin wants to Kill or Stop the Processes which are being executed by him only. So in order to perform this task you can to use the GETOWNER Method. Full Script : Hope you all enjoyed the post, Do Like , Share and comment if you have any query related to this.

How to take Snapshot of the screen using PowerShell

Hi Guys, Welcome to the Powershell Tips and Trick section. Today one of the follower of my page The Powershell Geek asked me how to take Snapshot of the Screen using PowerShell. Before beginning let me tell you , few months back one of my friend got the same requirement from our client i.e. Login to a website, then performing certain tasks and once done take snapshots as a proof that its done successfully. So here’s the Code, its already available in Technet anyways. CODE : OUTPUT IMAGE FILE : So now you can keep the code in between your script or where ever required to take the Snapshot. Hope you all enjoyed it, do Like and Share. Source : Technet

Error Handling Tips in PowerShell

Hi Geeks, We all know the ways to handle error in scripting or programming languages i.e Try, Catch, Finally and so on. The same thing can also be done in PowerShell. Example : Try { $a = 1/0 } Catch { Write-Host “Got Exception” } But suppose your script is too long and you want your Error should be handled in such a way that you can know exactly what caused the error and at which path or line number. So to do so PowerShell provides some cool properties as given below : To Catch the Complete Exception -> $_.Exception To Find the exact Error Line number -> $_.InvocationInfo.ScriptLineNumber To only get the Exception Message -> $_.Exception.Message So will look like this : Try {           Your Script Goes here  } Catch {         $Exception = $_.Exception         $Line = $_.InvocationInfo.ScriptLineNumber         $Message = $Exception.Message } FINAL OUTPUT :                                                             Hope yo

How to add multiple contents in a HTML Report using Powershell

Hey Geeks, Today em gonna show you how to add multiple contents like CPU Utilization, Disk check, Services Check etc. into a single HTML Report file. Few days back I got this requirement to add multiple contents into a single report file and once the report generation is done send a mail. So lets learn how to achieve this through Powershell. Powershell provides two properties for this PRECONTENT & POSTCONTENT ,so whatever you want to add should be kept in Pre Content and finally we can merge it using Post Content. Further you can also use Add-Content , Append or Out-File to do the same. But in this example I will show you Pre Content and Post Content. Sample 1 : How to Add contents  $Services = gwmi -Class Win32_Service -ComputerName $Server -Credential $Cred |?{$_.name -match ‘Test’} | Select Name,State | Select -last 4 | ConvertTo-HTML -AS Table -Fragment -PreContent ‘<h2>Services Report</h2>’| Out-String Sample 2 : How to Merge all the contents

How to customize the Powershell Prompt

By default when you open up Powershell console, you will get a screen as shown below : so today we are going to learn how to replace the PS C:\windows\system32> with any thing lets say I ♥ PowerShell.  So lets learn how to do it. STEP 1 :  We are going to modify the Powershell Profile for this. So open PowerShell as Administrator & give the below command :  Test-Path $Profile If it return True that means Powershell profile is created, if it's False then create the powershell profile by executing the below comand :  New-Item -Path $PROFILE -Type File -Force STEP 2 : Since the Profile is now created, now open the profile in Notepad i.e.  notepad $Profile STEP 3 : Now Copy-Paste the below function in that file and Save it. You can the change the content as per your choice. If any message or warning comes then change the encoding type while saving (Since I am using a Heart Shape by default ANSI Encoding will not s

How to Zip and UnZip files using PowerShell

Today we are going to Learn all about Compressing and Decompressing a file using Powershell. So lets get started. Powershell 5.0 have lots of features added to its feather. One of them is Zipping and Unzipping . Powershell 5.0 contains 2 functions by default for Zipping and Unzipping a file i.e. Compress-Archive and Expand-Archive Syntax : Zip   :   Compress-Archive -path <Source_File_Path> -DestinationPath <Destination_File> Unzip : Expand-Archive -path <Zip_file_path_to_Extract> -DestinationPath <Destination_path_where_to_Extract>   >_ If you are using Powershell version below 5.0 then you can achieve the same by Calling a Class. ZIP - FILE Add-Type -Assembly "System.IO.Compression.FileSystem" ; [System.IO.Compression.ZipFile]::CreateFromDirectory("E:\The Powershell Geek", "E:\sample.zip") UNZIP -FILE Add-Type -Assembly "System.IO.Compression.FileSystem" [System.IO.Compression.ZipFil