Posts tagged ‘Powershell’

Mit Powershell die Bildschirmhelligkeit setzen

Die Helligkeit des Bildschirms lässt sich auch recht einfach per Powershell setzen

powershell (Get-WmiObject -Namespace root/WMI -Class WmiMonitorBrightnessMethods).WmiSetBrightness(1,50)

setzt die Helligkeit beispielsweise auf 50 Prozent.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Powershell: Dateien finden, die die 256-Zeichen-Pfadlänge sprengen

Sharepoint-Server haben ein Maximum von 256 Zeichen für Pfadangaben, Leerzeichen in Datei- und Ordnernamen werden dabei als „%20“ dargestellt, sodass für jedes Leerzeichen drei Zeichen „draufgehen“. Mit dem folgenden Powershell-Skript kann man die Dateien in einem Verzeichnis identifizieren, die das Limit vermutlich sprengen.

Die erzeugte CSV-Datei hat drei Spalten: Pfadlänge, Pfadlänge wenn Leerzeichen als „%20“ dargestellt werden, Pfad.

gci "K:\inputpath" | Select @{N="Path Length";E={$_.FullName.Length}}, @{N="URL Length";E={$_.FullName.replace(' ','+++').Length}}, 
Fullname | Export-Csv -NoTypeInformation -Delimiter ";" -Path "t:\ABC\filelaengen.csv"

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Hashes von Dateien erstellen mit Powershell

Verzeichnisse lassen sich recht einfach mit Powershell abgleichen, wenn man die Hashes aller enthaltenen Dateien vergleicht. Standardmäßig nutzt Powershell SHA256, dies lässt sich jedoch recht leicht ändern.

dir c:\ | get-filehash |  export-csv -notypeinformation -delimiter  ";" -path r:\files.csv 
 
PSDefaultParameterValues.add("Get-FileHash:Algorithm","MD5")

Die erzeugten Daten lassen sich dann leicht in Excel weiterverabeiten.

"Algorithm";"Hash";"Path"
"SHA256";"C883B5D2E16D22B09B176CA0786128F8064D47EDF26186B95845AA3678868496";"C:\msdia80.dll"

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Datei vom Sharepoint laden mittels Powershell

Hier ein Code-Schnipsel, zusammenkopiert aus Stackexchange-Antworten, mit dem man eine Datei vom Sharepoint laden kann. Wichtig war hier, dass die eventuell bereits lokal vorhandene Datei nicht mehr genutzt wird. Dazu wird sie gelöscht (man könnte noch prüfen, ob sie überhaupt vorhanden ist…). Der Sharepoint-Pfad wird innerhalb der Powershell als Laufwerk gemountet, das erlaubt dann die Nutzung einfacher Kopier-Befehle.

[String]$Ziel = "somelocalfile.txt"
 
Write-Host "Loesche die alte Datei"
Remove-Item -Path $Ziel
 
$FileExists = Test-Path $Ziel
If ($FileExists -eq $True) {
    Write-Host "Fehler: Datei noch vorhanden!"}
Else {
    Write-Host "OK: Alte Datei geloescht!"
}
 
Write-Host "Mounte Sharepoint als virtuelles Laufwerk..."
[String]$WebDAVShare = '\\some\unc\path\'
New-PSDrive -Name S -PSProvider FileSystem -Root $WebDAVShare
 
Write-Host "Kopiere ..."
Copy-Item "S:/someremotefile.xlsx" $Ziel
 
$FileExists = Test-Path $Ziel
 
If ($FileExists -eq $True) {
    Write-Host "OK: Neue Datei vorhanden!"}
Else {
    Write-Host "Fehler: Datei wurde nicht heruntergeladen!"
}
 
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Creating Powerpoint Decks with Powershell

A couple days ago I would have been happy to have an automated way of creating Powerpoint slides (Powerpoint was not my choice anyway) now I found one with the help of the Scripting Guy and StackOverflow. The following code just opens Powerpoint and adds a couple slides, each with a different layout. I am not sure (resp. too lazy to check) how many layouts there are but it must be more than 30.

Clear-Host
Add-type -AssemblyName office
$application = New-Object -ComObject powerpoint.application
$application.visible = [Microsoft.Office.Core.MsoTriState]::msoTrue
$presentation = $application.Presentations.add()
 
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 1) # title slide
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 2) # slide title and text
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 3)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 4)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 5)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 6)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 7)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 8)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 9)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 10)
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 11) # just slide title
$slide.Shapes.title.TextFrame.TextRange.Text = "This is the slide title"
$slide = $Presentation.Slides.Add($presentation.Slides.Count + 1, 12) # blank

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Finding truly empty folders with Powershell

The easiest approach to find empty folders with Powershell could be:

(gci C:\Scripts -r | ? {$_.PSIsContainer -eq $True}) | ? {$_.GetFiles().Count -eq 0} | select FullName

however this just finds the folders which have no files in them. To find truly empty folders – the one which also have no subfolders – use the following:

(gci C:\Scripts -r | ? {$_.PSIsContainer -eq $True}) | ?{$_.GetFileSystemInfos().Count -eq 0} | select FullName

Source: http://superuser.com/questions/321231/how-to-find-empty-directories-in-windows-using-a-powershell-script

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Using Powershell to create MD5 files

This entry is part 2 of 4 in the series MD 5 Calculation

Following up on an article a few days ago here’s a script that creates a MD5 file.

# Uwe Ziegenhagen, 12.11.2014
# Reference: http://onlinemd5.com/
 
### Step A: Get the name of the file
# http://blogs.technet.com/b/heyscriptingguy/archive/2009/09/01/hey-scripting-guy-september-1.aspx
Function Get-FileName($initialDirectory)
{  
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
} #end function Get-FileName
 
# *** Entry Point to Script ***
$file =  Get-FileName -initialDirectory "C:\"
# write-host "file: " $file
 
### Step B: Create a file handle from this string and calculate the MD5 sum
$filehandle = Get-ChildItem $file
 
write-host "Filename: " $filehandle.Name
 
# http://stackoverflow.com/questions/10521061/how-to-get-an-md5-checksum-in-powershell
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($filehandle))).ToLower().Replace("-","")
 
write-host "Calculated Hashsum: "  $hash
 
### Step C: Write the MD5 sum from the MD5 sum file matching the other filename
$hash | out-file -FilePath $($filehandle.DirectoryName + "\" + $filehandle.BaseName + ".md5")

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Using Powershell to calculate/compare MD5 hashes

This entry is part 1 of 4 in the series MD 5 Calculation

Here’s some code to a) calculate a MD5 hash for a given file and b) to compare the hash with a MD5 provided in an external file. The scripts expects the MD5 file to have the same name, but MD5 extension. Credit goes to the friendly souls providing the original code, I just copied and pasted everything together.

The comparison is just visual, both MD5 hashes — the calculated and the provided one — are printed on the screen, it’s easily to extend it for an automated comparison.

# Reference: http://onlinemd5.com/
 
### Step A: Get the name of the file
# http://blogs.technet.com/b/heyscriptingguy/archive/2009/09/01/hey-scripting-guy-september-1.aspx
Function Get-FileName($initialDirectory)
{  
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
 
 
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
} #end function Get-FileName
 
# *** Entry Point to Script ***
$file =  Get-FileName -initialDirectory "H:\MD5"
 
### Step B: Create a file handle from this string and calculate the MD5 sum
 
$filehandle = Get-ChildItem $file
 
# write-host "file: " $file
# write-host "DirectoryName: " $filehandle.DirectoryName
write-host "Name: " $filehandle.Name
# write-host "pure Name: " $filehandle.BaseName
 
# http://stackoverflow.com/questions/10521061/how-to-get-an-md5-checksum-in-powershell
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($filehandle))).ToLower().Replace("-","")
 
write-host "Calculated Hashsum: "  $hash
 
### Step C: Get the MD5 sum from the MD5 sum file matching the other filename
 
$md5handle =  Get-ChildItem $($filehandle.DirectoryName + "\" + $filehandle.BaseName + ".md5")
$md5sum = [IO.File]::ReadAllText($md5handle)
 
write-host "Provided MD5        " $md5sum

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Dateien verschieben mit Powershell

Ausgangssituation: Diverse Unterverzeichnisse mit Dateien, die alle ins darüberliegende Verzeichnis verschoben werden sollen. Mit dem Windows Explorer dauert es Stunden, selbst mit Total Commander dauert es zu lange. Gut, dass ein paar Zeilen Powershell das erledigen:

$path =  "D:\files\"
cd $path
 
$files = gci | ? {$_.PSisContainer -eq $true} 
 
foreach ($i in $files){
	Move-Item $i\*.* $path
}

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Mit Powershell das Active Directory abfragen

Die heutige Aufgabe in Sachen Powershell war, diverse Informationen zu ACLs (Access Controll Lists) aus dem AD auszulesen. Diverse Personen wie die Zertifizierer der Gruppe sind in Feldern wie „Mail“ und „Info“ abgelegt, diese sollen in eine Excel-Liste exportiert werden.

Die folgenden Artikel waren hilfreich, um den Code zusammenzubauen:

Nachtrag vom 09.01.2013: Der unten stehende Code hat nur 1000 Zeilen abgefragt, durch das Einfügen von $searcher.pagesize=1000 ist diese Grenze aufgehoben.

# Uwe Ziegenhagen, 21.12.2012
# Path for the CSV file to be written to
 
$outputpath = "d\groups.csv"
 
# some AD stuff
$root = [ADSI]''
# initialize the AD searcher
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
# which groups shall be returned
$searcher.filter = "(&(objectClass=group) (CN=some-group-name*))"
$searcher.pagesize=1000
 
# need to add the variables that shall appear in the result
$searcher.PropertiesToLoad.Add("cn");
 
$searcher.PropertiesToLoad.Add("description");
$searcher.PropertiesToLoad.Add("mail");
$searcher.PropertiesToLoad.Add("info");
 
# call the finder
$adfind = $searcher.findall()
 
# first line of the output file
"Group`tDescription`trole1`trole21`trole22`trole23"  | out-file $outputpath -Width 300
 
foreach ($i in $adfind ) {
   # get the properties from the search result
   $name = "" + $i.properties.item("cn")
   $description = "" + $i.properties.item("description")
   $role1 = "" + $i.properties.item("info")
 
   # some entries include garbage like 'contact:' instead of the pure name
   # to get rid of whitespace I then trim everything
   $role1= $role1.replace("contact:","").trim()
 
   $role2 = "" + $i.properties.item("mail")
   # there are up to 3 role2s, split this entry into different columns
   $role2 = $role2.replace(",","`t")
 
   # create line
   $line = $name + "`t" + $description + "`t" + $role1  + "`t" + $role2 
   # replace carriage-returns
   $line.replace("`n","");
   # write line to file
   $line | out-file -append $outputpath -Width 300
}

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website