Off topic: Powershell to rename pictures

I’m trying hard to convert myself from VBScript to Powershell… so in the need of a powerfull filerenamer I wrote one in Powershell.

You need to download the Powershell Pack from http://code.msdn.microsoft.com/PowerShellPack

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#                                                                                           Rikard Ronnkvist / snowland.se
#  Will rename JPG and AVI files, uses EXIF-tag on JPG-images and filedate on AVI-files.
#
#  Files will be named:
#    \some path\YYYYMM\YYYYMMDD_HHMMSS_00.JPG
#               ^^^^^^ - Optional, if you have createSubdir set to True
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
$basePath = "F:\Pictures\Import dir"
$createSubdir = $True
$testMode = $False
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Download from:  http://code.msdn.microsoft.com/PowerShellPack
Import-Module PowerShellPack

# Add \* to use when searching
$searchPath = $basePath + "\*"

# Search for files
Write-Host "           Searching: " -ForegroundColor DarkGray -NoNewline
Write-Host $basePath -ForegroundColor Yellow

$allFiles  = Get-ChildItem -Path $searchPath -Include *.AVI,*.JPG -Exclude folder.jpg

Write-Host "               Found: " -ForegroundColor DarkGray -NoNewline
Write-Host $allFiles.Count -ForegroundColor Yellow -NoNewline
Write-Host " files" -ForegroundColor DarkGray

$fNum = 0
# Loop thru all files
foreach ($file in $allFiles )
{
	$fNum++
	# If it is an jpg use the exif-data, otherwise use date on file
	if ($file.Extension -eq ".JPG") {
		$imgInfo = $file | Get-Image | Get-ImageProperty
		$fileDate = $imgInfo.dt
	} else {
		$fileDate = $file.LastWriteTime
	}

	if ($createSubdir -eq $True) {
		# Set new filepath
		$fileDir = $basePath + "\" + $fileDate.ToString("yyyyMM")

		# Check directory
		if (!(Test-Path($fileDir))) {
			# Create a new subdirectory
			if ($testMode -ne $True) {
				$newDir = New-Item -Type directory -Path $fileDir
				Write-Host "            Creating: " -ForegroundColor DarkGray -NoNewline
				Write-Host $fileDir -ForegroundColor Red
			}
		}
	} else {
		# Use current directory
		$fileDir = $basePath
	}

	# Set new name to current to get "False" on first while
	$newPath = $file.Fullname

	$i = 0
	while (Test-Path $newPath) {
		# Set new filename
		$newPath = $fileDir + "\" + $fileDate.ToString("yyyyMMdd_HHmmss") + "_" + $i.ToString("00") + $file.Extension
		$i++
	}

	# Write som info
	Write-Host $fNum.ToString().PadLeft(4) -ForegroundColor DarkYellow -NoNewline
	Write-Host " / " -ForegroundColor DarkGray -NoNewline
	Write-Host $allFiles.Count.ToString().PadRight(4) -ForegroundColor Yellow -NoNewline
	Write-Host "   Moving: " -ForegroundColor DarkGray -NoNewline
	Write-Host $file.Name -ForegroundColor Cyan -NoNewline
	Write-Host " -> " -ForegroundColor DarkGray -NoNewline
	Write-Host $newPath -ForegroundColor Green

	# Move and rename the file
	if ($testMode -ne $True) {
		Move-Item $file.Fullname $newPath
	}
}

Ending up with something like this:

Oh, and you can add -Recurse on the Get-ChildItem row…


Problems with new-TestCasConnectivityUser.ps1

When we tried to run new-TestCasConnectivityUser.ps1 to create some mailboxes for the test-cmdlets we ran in to some strange problems.

Got an errormessage stating “CreateTestUser : Mailbox could not be created. Verify that OU ‘Users’ exists and that password meets complexity require”

The OU exist and the password is OK… strange. Googled and didn’t find anything that could relate to that problem. Then I started to disect/debug the powershell script…

Ended up with a command like:

$SecurePassword = Read-Host "Enter password" -AsSecureString
new-Mailbox -Name:ext_dummy -Alias:ext_dummy -UserPrincipalName:ext_dummy@domain.se -SamAccountName:ext_dummy -Password:$SecurePassword -Database:somestrangeguid -OrganizationalUnit:Users

When running that command it says that “Multiple organizational units match identity “Users”. Specify a unique value.”

OK, we have another OU in the hierarchy named “Users”…
Edited the script and changed the value of $OrganizationalUnit to another OU and did a new test with “get-mailboxServer | .\new-TestCasConnectivityUser.ps1″ and a few seconds later we have the users. :-)


PSOL: Read web page

If you need to output something from a webpage via Powershell, then .NET is a easy way to do it.

Write-Host ([String] (New-Object Net.WebClient).DownloadString('http://snowland.se/demo/'))

PSOL: Count files in SCCM-inboxes – Version 3

A bit more simple version of the last script… this time as a PowerShell oneliner.

Get-ChildItem \\MYSERVER\SMS_C01\inboxes -Recurse | Group-Object Directory | Where { $_.Count -gt 1 }  | Sort-Object Count -Descending | Format-Table Count, Name -AutoSize

Re-notify users of a alerts

This little powershell-script will update all alerts with resolutionstate “New” and an age of at least 24 hours… and with that done the users subscribing to that alert will get a new notification.

$UpdateAlerts = Get-Alert | where { $_.ResolutionState -eq 0 -and $_.LastModified -lt (get-date).AddHours(-24) }

foreach ($alert in $UpdateAlerts) { $alert.Update("Renotify operators of an untouched alert open for 24 hours") }

PSOL: Resolve informational alerts without repeatcount

To get rid of a large number of alerts in SCOM you can of course use PowerShell…

This script will take informational alerts without any repeats that are 24 hours old and simply resolve them with a small comment.

get-alert | where { $_.Severity -eq 0 -and $_.RepeatCount -eq 0 -and $_.ResolutionState -eq '0' -and $_.LastModified -lt (get-date).AddHours(-24)} | Resolve-Alert -comment "Alert resovled via script (24 hours old informational alert without repeatcount)" | Format-Table MonitoringObjectPath, Name, TimeRaised

(Change “$_.RepeatCount -eq 0″ to “$_.RepeatCount -lt 3″ to get alerts with less then 3 repeats)


PSOL: List size of all files matching a pattern

Just recently started to play around with PowerShell… so here is my first PSOL-post (PowerShell One Liner), expect more.

get-Childitem C:\ -recurse | where{$_.Extension -match "pst"} | Format-Table FullName, Length

MaintMode on a single class

Didnt know that this would work…

In a project that I’m working on the customer wanted me to create a Management Pack for a couple of services, the only problem was that they wanted to restart the services during the night.
My first solution was to create a group with the computer in it and run a PowerShell script to set the computer in to maintenance mode.

Then I tested to put my own class in that group and use the same script on the class instead.

Worked like a charm :-)

The script: systemcenterforum.org/maintenance-mode-scheduled-task-for-ops-mgr-2007/

Maintenance Mode


VBScript -> PowerShell

Scripting Guys har varit framme igen… den här gången har dom skrivit en guide om hur man konverterar “gamla” VBScript till PowerShell…

This guide is intended to help you “translate” VBScript scripts to Windows PowerShell scripts. However, this is not designed to be a word-for-word translation guide; for better or worse, things don’t quite work that way. Instead, consider this a reference as you begin writing Windows PowerShell scripts. After all, sooner or later you’re bound to run into a situation where you find yourself thinking, “OK, I need to use a Select Case statement here. I know how to do that in VBScript, but how do I do that in Windows PowerShell?” That’s where this guide can come in handy; it takes all the VBScript functions, statements, and operators and shows you, as much as possible, a Windows PowerShell equivalent.

Mer info: Technet Scriptcenter


Powershell – RTM

Idag på TechED anonserade Bob Muglia att Powershell släpps som RTM. :-)

 

http://bink.nu/Article8822.bink


« Previous PageNext Page »