Thursday, May 14, 2015

Open Socket using PowerShell

To open a socket connection on a specific host and port using PowerShell do the following:

(new-object Net.Sockets.TcpClient).Connect("proxy.us.dhl.com", "8080")

If it can't connect it will timeout. If it can connect it will return to the Powershell prompt.

wget equivalent in PowerShell

As some have pointed out there is not the equivalent for wget in PowerShell 1 or 2. It is included as Invoke-WebRequest in PowerShell 3.

To implement it yourself in PowerShell 1 or 2, you can use the following:



## Declare a function that takes source and destination arguments
Function Get-Webclient ($url, $out) {
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$request = New-Object System.Net.WebCLient
$request.UseDefaultCredentials = $true ## Proxy credentials only
$request.Proxy.Credentials = $request.Credentials
$request.DownloadFile($url, $out)
}

## Call the function with our source and destination.
Get-Webclient "http://www.google.com" "C:\Foo3.txt"


Credit to this post.

Tuesday, May 12, 2015

Merge multiple MP3 files into one file

It is not a simple thing to merge MP3 files because they have header information at the beginning of each file before the actual content. So, in theory you can't just merge them together without writing a single header for the new merged file. However, many MP3 players will still read the files okay even though there are multiple headers (all but one mixed where the content should be). This hack exploits this robust implementation of MP3 players.

WARNING: This is most definitely a hack and does not always work because it is technically not correct. However, in a pinch it can work (sometimes). Do not trash your original files unless you don't mind losing the data.

Here is the very simple DOS command for merging multiple MP3 files into one MP3 file (that will likely play on most MP3 players, but is technically not correctly formatted so it will not play on all MP3 players).

copy /b *.mp3 output.mp3


Monday, May 11, 2015

Using Powershell to email free space

Below are two script


Put the following into a PowerShell file (EmailFreeSpace.ps1) and execute.

Clear-Host
$Body = Get-WmiObject Win32_logicaldisk -ComputerName LocalHost `
| Format-Table DeviceID, MediaType, `
@{Name="Size(GB)";Expression={[decimal]("{0:N0}" -f($_.size/1gb))}}, `
@{Name="Free Space(GB)";Expression={[decimal]("{0:N0}" -f($_.freespace/1gb))}}, `
@{Name="Free (%)";Expression={"{0,6:P0}" -f(($_.freespace/1gb) / ($_.size/1gb))}} `
-AutoSize


$EmailFrom = "test@gmail.com"
$EmailTo = "test@gmail.com"
$Subject = "Notification from XYZ"  

$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("test@gmail.com", "password here");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)


The output of the first part of the script will look like this:

DeviceID MediaType Size(GB) Free Space(GB) Free (%)
-------- --------- -------- -------------- --------
C:              12      232            174   75 %
D:              12      233            155   67 %
H:               0     7500           5634   75 %
J:               0      100            100  100 %
K:              11        0              0
Q:              12        0              0


The second part of the script will send an email using Gmail. You need to have a Gmail account and you will need to put the password on the second to last line of the script. You can also use any other STMP server such as Hotmail, etc.

Tuesday, April 28, 2015

Understanding GitHub

GitHub is a great improvement over subversion if for now other reason it has great performance for global teams that have network latency. It can be confusing when learning it though.To make things easier GitHub has created a GUI called GitHub for Windows, so you don't have to use the command line. The command line can do anything GitHub for Windows can. Here is one of the best tutorials I have found for using the GUI. It can still be a bit confusing because of the 2-3 repositories suggested by GitHub. Below is a diagram to show the steps needed to make a change, share it with others, and merge it back into the main repository.

Let's walk through the diagram in detail. The first thing to notice in this example is that there is an existing repository called AwesomeCode in github.com in the account for user Jane. The goal is that all changes will end up back in Jane's repository (repo). If your goal is not to contribute to the main repository and just want to work on your own copy (aka fork) that will not affect the main repo at all you don't create pull requests. The steps below assume you would like to contribute to the main repo (Jane's).

1. Fork - A fork is like a branch or a copy of the main repo. To fork a repo you need to use github.com and click the fork button. This will not do anything to your laptop. It will copy the main repo to your github.com account. Notice the difference in the urls for the main and your forked copy.

2. Clone - When you clone a repo you are getting a local copy of it on your laptop. You can use github.com to do this or you can use GitHub for Windows. When you do this you will need to specify the directory where the repo will be located. This command will create files in the specified directory, but it will also create a .git directory in that same directory you specified. This is known as the Local Repository or Index. The name index because there is and Index file in the .git directory.

3. Modify File - Here is where you use your favorite editor or program to modify or create a file.

4. Save - This is simply using your favorite editor or program to save the changes you made to the file to the local disk. If you re-open the file you will see the changes.

5. Commit - Commit in GitHub is different than in Subversion, CVS, etc because you don't have to be connected to the internet, cloud, network, etc to commit the change. All your commits will be done to your Local Repo. This make working with GibHub very efficient for networks with latency. Commits are not visible on the main or even your repo on github.com yet. If your laptop was lost so would your changes.

6. Push / Sync - Push is what the command is called, but in GitHub for Windows it is the Sync button. When you Push / Sync the changes on your Local Repo are pushed (similar to a commit) to your repository on github.com. You changes are now visible on your repository on github.com, but it is NOT visible in the main repository (Jane's). If you don't want to make your changes available to Jane then you are done. You have updated your repository.

7. Create Pull Request - A pull request is a way to say to share what you have done with others. You can use the pull request to get approval for your change, or get feedback, or help, etc. Other users can then comment on your pull request. It is the last step before merging your changes with the main repo. A pull request is a made while on your repository on github.com or you can now use GitHub for Windows to do it, but the pull request is actually available on the main repo (Jane's) under Pull Requests. Try to keep your pull requests small (5-10 lines or changes) and descriptive so other people can understand what your were doing.

8. Merge Pull Request - When you want to incorporate a the changes in a Pull Request into the main repo you need to merge the changes. Sometimes it can be automatically done, but other times it can't. Once the changes are merged the changes you made in your Pull Request are now part of the main repo. The general rule is that no Pull Requests should be merged into the main repo unless they are ready for releasing to production.

Monday, March 23, 2015

Make sure my Windows Service is enabled and running

The situation

I recently had a need to keep the ASP.NET State Service (aspnet_state) running. For some reason it was getting disabled and stopped sometimes. I assume a corporate security policy is doing it periodically, but I don't know exactly how or why it happens. However, I do know that every time the ASP.NET State Service goes down so does my web applications on my web farm because they are using the ASP.NET State Service.

The Workaround

Luckily, PowerShell makes it very easy to set the StartupType to Automatic and then start a Windows Service. No need to test state before calling since it seems to only change something if it is needed.

Set-Service -name aspnet_state -StartupType Automatic
Set-Service -name aspnet_state -Status Running

Save the two above lines in a file with any name you like ending in .ps1. I'll use EnsureStateService.ps1 for this example.

Automating the workaround

Every minute I want to execute the above PowerShell file. That way at most I will have 1 minute of downtime (minus the time it takes to enable and start the ASP.NET State Service). To create a scheduled task in Windows Task Scheduler do the following:

1. Create a task
2. Set the task to be executed as the user System.
3. I used Windows Vista, Windows Server 2008 configuration, but I don't think it matters in this case.
4. For the trigger, I set it to run Daily, running every 1 days, Repeated task every 1 minute, and stopped task if running for more than 1 minute as shown below:


5. For the Action, do the following:
For Program/script field enter PowerShell
For Add argument (optional): field enter the path to the powershell script file surrounded by double-quotes. In this example, it is "D:\MDM\EnsureStateService.ps1"