Powershell – Copyrighting made easy

I recently needed to submit a program I’m working on for a copyright. One of the criteria is the first and last 25 pages of the program need to be submitted. I really didn’t want to go into every source code file and append it to a file manually, I have more important things to do than that. I used my old friend Powershell to get what I needed.

Here is the line:

> ls *.cs -recurse | ?{-not ($_.fullname -match “obj”) -and -not ($_.fullname -match “properties”)} | Get-Content > sourcecode.txt

What this is doing is grabbing all of my C# code from my solution (excluding code in the obj and properties folders) and dumping it to a text file.

From there I was able to upload one file.

Advertisement

Powershell ~ Shorten Shortcut Names

Renaming Files

Here is something I just came up with. It is a really short Powershell one-liner to remove the annoying ‘- Shortcut’ from your shortcuts.

dir “*- Shortcut*” | foreach{ren -Path $_.Name -NewName $_.Name.Replace(” – Shortcut”,””)}

It is a good idea to execute it first with -whatif in the foreach loop.

Note: Be sure to be in the desktop directory when you run this.

Powershell Retrieving Remote System Time

Compare Local Date and Time to a Remote Computer

This is a rather interesting problem. I was doing a comparison between an audit table and a trace for SQL Server, which was proving to be dificult as I soon realized there was latency as well as the system date’s had an offset. So I turned to my good old friend, Powershell. Powershell has a very nice interface for coding against WMI, which I fully leveraged in this code snippet.

#Server name here. 
$ServerName = <Server Name Here>
#Retreive the localtime of the server. 
$remoteDate = Get-WmiObject -ComputerName $ServerName -Class win32_operatingsystem -Property LocalDateTime
#Converting a WMI time to a standard datetime format. 
$remoteDate = [System.Management.ManagementDateTimeConverter]::ToDateTime($remoteDate.LocalDateTime)

$localDate = Get-Date

#Displaying the difference. 
$remoteDate - $localDate

DirectoryOperationException – The object does not exist.

System.DirectoryService.Protocols Library

This was a very frustrating error. I was able to connect to LDAP through LDAPadmin but not through a program I was creating. “The object does not exist” error occurs, at least in my experience when the credentials you are passing to the server do not authenticate.

In this case I was getting nowhere. Resorting to Wireshark, filtering against port 389, which is the port for LDAP resulted in me seeing a backslash in the credentials being passed as well as the username coming after the organization, which is wrong for my environment.

The resolution was to set the domain to nothing in VB or null in C# in my Net.NetworkCredential object. At the same time moving the organization to the username property.

Dim credLDAP As New Net.NetworkCredential(“cn=username”,”password”, “o=domain”)
does not work, but this does:
Dim credLDAP As New Net.NetworkCredential(“cn=username,o=domain”,”password”, nothing)

Powershell – Remove Columns From Fixed Width Files

Here is something that works incredibly well.

This is a quick description enter the file names you wish to use. Powershell then reads in all the data and creates a new file by joining all the elements in the char array to a string. It then takes the row and ends it in a carriage return / line feed. Finally it saves the file.

$fileName = c:\file.txt
$newFileName = c:\newfile.txt
$newFile = “”
Get-Content -Path $filename | ForEach-Object{$newFile += [string]::Join(“”,$_[0..149] + $_[154..777]) + “`r`n”}
$newfile > $newFileName

Powershell – Top Command

For those of you who love the top command in Linux…

 

function Get-Top{

#######################################

##Get-Top

##

##Written By: John Glasgow

#######################################

<#

.SYNTAX

Get-Top [-delay interval] [-pid pid_number]

 

.SYNOPSIS

Emulates the top command from Linux/Unix.

 

.EXAMPLE

To set delay of 5 seconds.

Get-Top -delay 5

 

.EXAMPLE

To watch a particular process.

Get-Top -pid 4408

#>

$delay = 2

$proc = -1

 

for($i = 0; $i -lt $args.Count; $i += 1){

if( $args[$i] -ilike “-d*” ){

$i++

$delay = $args[$i]

}

if( $args[$i] -ilike “-p*” ){

$i++

$proc = $args[$i]

}

if( $args[$i] -ilike “-q*” ){

$i++

$delay = 0

}

}

 

while ($true){

Clear-Host

if($proc -gt 0){Get-Process | Sort-Object -Descending cpu | Where-Object{ $_.Id -eq $proc } | Format-Table}

else{Get-Process | Sort-Object -Descending cpu | Select-Object -First 20 | Format-Table}

Start-Sleep -Seconds $delay

}

}

Set-Alias top Get-Top

PowerGUI – Remotely Determine if Powershell is Installed

Here is a Node Script to determine if Powershell is installed on a remote computer:

[System.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.VisualBasic’) | Out-Null
$name = [Microsoft.VisualBasic.Interaction]::Inputbox(“Enter the IP or Name of the server:”)
$pshell = Get-WmiObject Win32_QuickFixEngineering -ComputerName “$($name)” | Where-Object{$_.HotFixID -eq “kb968930”}
if ($pshell -eq $null){Write-Output “Powershell 2.0 is NOT installed.”}
else {Write-Output “Powershell 2.0 IS installed”}

If you found this useful, subscribe.

PowerGUI – Powershell Remote Installed Hotfixes & Patches

Here is a Node Script to get the installed patches or hotfixes on a remote computer:

[System.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.VisualBasic’) | Out-Null
$name = [Microsoft.VisualBasic.Interaction]::Inputbox(“Enter the IP or Name of the server:”)
Get-WmiObject Win32_QuickFixEngineering -ComputerName “$($name)” | Where-Object{$_.HotFixID -ne “File 1”} | Write-Output

I also have a system monitor to keep track of disk space and CPU/Memory Usage…Click here!

If you found this useful, subscribe.

Powershell Disk Space

If you found this useful, subscribe.

This is a newer, cleaner version of a previous post.

https://refactoringself.wordpress.com/2010/10/11/powergui-using-powershell-to-get-disk-space/

 

# Getting disk information
[System.Object[]]$disks = @()
$Private:wmiDisks = (Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3})

foreach ($Private:wmiDisk in $wmiDisks){
$Private:tmp = New-Object -TypeName System.Object
$tmp | Add-Member -Name DeviceID -Value $wmiDisk.DeviceID -MemberType NoteProperty
$tmp | Add-Member -Name FreeSpace -Value $([Math]::Truncate($wmiDisk.FreeSpace / 1GB)) -MemberType NoteProperty
$tmp | Add-Member -Name TotalSpace -Value $([Math]::Truncate($wmiDisk.Size / 1GB)) -MemberType NoteProperty
$disks += $tmp}

I also have made a monitoring system free for your use, here.

 

Powershell System Monitoring

In the next couple days I plan on releasing to you a script and database that you can use to get information about your servers and track them over time. What they do is relatively simple but should help many of you with some very common admin headaches!

Update

It is now here!

 

 

 

Technorati Code QQXYEUN7JHW2