Machine Management

This article is about PowerShell and the tasks I use it for.

Disable-NetAdapter -Name 'Ethernet' -Confirm:$false

Tricks with ping: 

From cmd: powershell -command "0..500|foreach {$_;ping -n 1 server1;start-sleep -s 2}"

while ($true) { $ct++; $result=ping -n 1|Select-String "Lost";$ds=Get-Date;$show=$result.ToString();write-host $ct $ds $show.Substring($show.length - 10,10) to google;Start-Sleep -Seconds 1 }

Or save a script:


Write-Output "Target: $target"


 If (-not (Test-Connection -ComputerName $target -BufferSize 16 -Count 1 -Quiet)){


  Write-Output "$(Get-Date) Packet to $target was dropped. Drop count: $dropcount"  


 if (($_ % 60) -eq 0){Get-Date}

 Start-Sleep -Seconds 1



Merge hyper-v drive snapshots, one by one:

PS C:\Hyper-V\Virtual hard disks> function fakemerge { Param ([string]$targetpath);$targetvhd=Get-VHD -Path "$targetpath";$parentpath=$targetvhd.ParentPath;Write-Host "Merge: Merge-VHD -Path" $targetpath "-DestinationPath" $parentpath "-ErrorAction Stop";st

art-sleep -s 3;if ($parentpath){fakemerge "$parentpath"}else{Write-Host "No parent path for $targetpath"} };fakemerge "C:\hyper-v\Virtual Hard Disks\nameserver-drivename-datatype_EE77DAC6-B30D-40B0-BB8D-F719993EEE84.avhdx

Get IP address info for a list of machines:

PS C:\> $servers = @("server1","server2","serverd");foreach ($server in $servers) {write-host "$server";Invoke-Command -Script {Get-NetIPInterface -AddressFamily "IPv4"|where {$_.InterfaceAlias -notmatch 'Loopback'}; (Get-NetIPAddress |where AddressFamily -eq "IPv4" |where IPAddress -ne '').ipaddress} -ComputerName "$server"}

Check Active Directory against a list for lack of entries in the list:

Get-ADUser -Filter 'enabled -eq $true' -Properties UserPrincipalName|Select-Object -Property UserPrincipalName|%{$uid=($_.UserPrincipalName -split '@')[0];$uid;if (!(Select-String -Path C:\temp\list.csv $uid)){"Not Found $uid"}}

Set DNS servers

PS C:\> Set-DnsClientServerAddress -InterfaceIndex 23 -ServerAddresses ("","")

Enable a Hyper-V virtual adapter

PS C:\> GET-VM | GET-VMNetworkAdapter | Connect-VMNetworkAdapter –Switchname ‘New-cool-Hyper-V-Lan’ 

Assign the desired virtual switch to all the running virtual machines on a server at once:

PS C:> $vms=@();Get-VM|Where {$_.State -eq 'Running'}|%{$vms+=$_.Name};Connect-VMNetworkAdapter -VMName $vms -SwitchName Internet1;Get-VM|Where {$_.State -eq 'Running'}|Get-VMNetworkAdapter

Add a registry entry to trust a local domain

$UserRegPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains"

#Value 1 = Intranet

$DWord = 1

$Name = ""

if (-Not (Test-Path "$UserRegPath\$Name")){

 New-Item -Path "$UserRegPath" -ItemType File -Name "$Name"


Set-ItemProperty -Path "$UserRegPath\$Name" -Name "http" -Value $DWord

Set-ItemProperty -Path "$UserRegPath\$Name" -Name "https" -Value $DWord

Set-ItemProperty -Path "$UserRegPath\$Name" -Name "*" -Value $DWord

Watch a text file for changes

PS C:\> get-content -tail 10 -wait '\\server\c$\temp\serversmonitored.log'

Install XPS Viewer

dism /Online /Add-Capability /CapabilityName:XPS.Viewer~~~~

Run a DOS/CMD style command

PS C:\> $command = "dir 'c:\program files' "

PS C:\> $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)

PS C:\> $encodedCommand = [Convert]::ToBase64String($bytes)

PS C:\> powershell.exe -encodedCommand $encodedCommand

Logging into a webpage and pulling a download file


2018-11-08 B.M.C. created to pull a CSV download

           This was rather tricky because I couldn't get the fine grain control I wanted from the normal tools like WebRequest and WebClient.

   I needed to load a page to get the session cookie, then submit data with POST (including that session cookie) from an image input.

   Then after a successful login, I needed to go to another page, still with the session cookie, and from that page click another

   image input button which results in a stream of data which is the CSV data I'm actually after.


$url = ""

#Load initial page to get the session cookie

$request = [System.Net.WebRequest]::Create($url)

$request.CookieContainer = New-Object System.Net.CookieContainer


$response = $request.GetResponse()

$requestStream = $response.GetResponseStream()

$readStream = New-Object System.IO.StreamReader $requestStream



#Looping seems like it should be unnecessary, but normal pages 

#may have multiple cookies. In this case, I just needed the one.

foreach ($cook in $Response.Cookies)    {



#write-output "Last cookie: $lastcookie" 

#Now that we have the cookie, we post the login data back to the same page.

#I found Telerik Fiddler to be very handy for figuring out exactly what 

#my normal session was doing.

$url = ""

$postData = "Name=myusername&Password=mypassword&loginButton.x=0&loginButton.y=0"

$buffer = [text.encoding]::ascii.getbytes($postData)

[net.httpWebRequest] $req = [net.webRequest]::create($url)

$req.method = "POST"

$req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"

$req.Headers.Add("Accept-Language: en-US")

$req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")


$req.AllowAutoRedirect = $false

$req.ContentType = "application/x-www-form-urlencoded"

$req.ContentLength = $buffer.length

$req.TimeOut = 50000

$req.KeepAlive = $true

$req.Headers.Add("Keep-Alive: 300");

$reqst = $req.getRequestStream()

$reqst.write($buffer, 0, $buffer.length)



[net.httpWebResponse] $res = $req.getResponse()

$resst = $res.getResponseStream()

$sr = new-object IO.StreamReader($resst)

$result = $sr.ReadToEnd()



#The result is a 302 redirect, which means our session is now successfully authenticated

#Ignoring the redirect, we now go to the download page where we send input

#as if we'd clicked the "Download" button, which isn't an HTML button but an

#input image. As before, Fiddler came in handy.

$url = ""


$buffer = [text.encoding]::ascii.getbytes($postData)

[net.httpWebRequest] $req = [net.webRequest]::create($url)

$req.method = "POST"

$req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"

$req.Headers.Add("Accept-Language: en-US")

$req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7")


$req.AllowAutoRedirect = $false

$req.ContentType = "application/x-www-form-urlencoded"

$req.ContentLength = $buffer.length

$req.TimeOut = 50000

$req.KeepAlive = $true

$req.Headers.Add("Keep-Alive: 300");

$reqst = $req.getRequestStream()

$reqst.write($buffer, 0, $buffer.length)



[net.httpWebResponse] $res = $req.getResponse()

$resst = $res.getResponseStream()

$sr = new-object IO.StreamReader($resst)

$result = $sr.ReadToEnd()


Out-File -InputObject $result -FilePath 'result.csv'

#The resulting stream of data is a CSV file that I need for other tasks.



$cc = new-object Net.CookieContainer

$req = [Net.WebRequest]::Create("")

$req.CookieContainer = $cc

$req = [System.Net.HttpWebRequest] [System.Net.WebRequest]::Create($url)

$probe = $html.ReadToEnd() 

$cookie = $ResponseObject.Headers["Set-Cookie"]

$strt = $cookie .indexOf(';', 0)

$sessionid= $cookie.Substring(0,$strt)

$cookie= $data.Headers["Set-Cookie"]

$req.Headers.Add("Accept-Encoding: gzip,deflate")


"{0} = {1}"    -f $cook.Name, $cook.Value

"Domain      : {0}"     -f $cook.Domain

"Path        : {0}"     -f $cook.Path

"Port        : {0}"     -f $cook.Port

"Secure      : {0}"     -f $cook.Secure

"When issued : {0}"     -f $cook.TimeStamp

"Expires     : {0}"     -f $cook.expireds

"Expired?    : {0}"     -f $cook.expired

"Don't save  : {0}"     -f $cook.Discard

"Comment     : {0}"     -f $cook.Comment

"Uri for comments: {0}" -f $cook.CommentUri

"Version     : {0}"     -f $cook.Version

"String: {0} :"         -f $cook.ToString()


 Print number of cookies

if ($response.Cookies.Count -gt 0) {

"{0} Cookies returned from: {1}" -f $Response.Cookies.Count,$site








Then there was this bit. I found I could do everything I wanted to all the way through clicking the download

button by launching an Internet Explorer object. This can even be hidden. However, I found there was no

way to click the Save button of Internet Exporer without isolating the object, bringing the window to the active

or foreground state, then using sendkeys to send specific keys to the window. Since I want this task to run 

even when nobody is logged into Windows, I don't trust that window manipulation would work and sendkeys is a

little dangerous as I've learned in past programming. That said, it did prove useful to have a program I could run

to record activity to Fiddler without having to do interactive typing, so I'll leave that script here in the reference







$ie = new-object -ComObject "InternetExplorer.Application"

$ie.visible = $true #Do you want to see IE?

$ie.silent = $true #Do you want pop-up dialogs suppressed?


while($ie.Busy) { Start-Sleep -Milliseconds 2000 } #My example was something like 100... I had to increase it a LOT before it worked

$elements=$ie.Document.IHTMLDocument3_getElementsByName("txtLoginName");foreach ($element in $elements){ $element.value=$myusername }

$elements=$ie.Document.IHTMLDocument3_getElementsByName("txtPassword");foreach ($element in $elements){ $element.value=$mypassword }

$elements=$ie.Document.IHTMLDocument3_getElementsByName("btnLogin");foreach ($element in $elements){ $ }


while($ie.Busy) { Start-Sleep -Milliseconds 2000 }

$elements=$ie.Document.IHTMLDocument3_getElementsByName("btnDownload");foreach ($element in $elements){ $ }

while($ie.Busy) { Start-Sleep -Milliseconds 2000 }

#Hit "S" on the keyboard to hit the "Save" button on the download box

$obj = new-object -com WScript.Shell

$obj.AppActivate('Internet Explorer')



Find the model of a computer: (not really PowerShell)

wmic csproduct get name

Admin Powershell to check bitlocker status:

manage-bde -Status

Check the size of a folder

function sizefolder($path) { $objFSO = New-Object -com Scripting.FileSystemObject;("{0:N2}" -f (($objFSO.GetFolder($path).Size/1GB)))}


Check out Hyper-V logs:

Get-WinEvent -FilterHashTable @{LogName ="Microsoft-Windows-Hyper-V*"; StartTime = (Get-Date).AddDays(-1);} -ComputerName Hyper-Vserver