Windows – Supportscript for needed IT infos

For my job its important to get fast informations from users.
Most of them are always the same.
What is your actual IP address, whats your Hostname, do you have local admin rights, which networkprinters are connected and so on.
To get these Information fast and without explain the user every time how to get these Informations, I build a script for it.
This script will be added via GPO to every user’s startmenu.
This should work on all clients with PowerShell 3 installed.
This is what I build with Powershell.
First I added some variables for the actual date:
$vdate = get-date -Format d
After that I added a varibale for the path of the logfile and check if the file exists and if it exists to telete it:
$FileName = "C:\Users\" + [Environment]::UserName + "\Desktop\" + [Environment]::UserName +"_" + $vdate + ".txt"
if (Test-Path $FileName) {
Remove-Item $FileName

If you use DELL devices in your company, it’s important to have the Serial (ServiceTag) and the Express Service Code.
To get the Express Service Code (will be calculated from the Service Tag Value) I added a function to my script:
Function Get-ExpressServiceCode {
Param
(
$ServiceTag = (Get-WMIObject -Class Win32_Bios).serialnumber
)
$Base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
$Length = $ServiceTag.Length
For ($CurrentChar = $Length; $CurrentChar -ge 0; $CurrentChar--) {
$Out = $Out + [int64](([Math]::Pow(36, ($CurrentChar - 1)))*($Base.IndexOf($ServiceTag[($Length - $CurrentChar)])))
}
$Out
}

Now I added the Powershell command to receive the Hostname and write it to the Logfile:
$CN = "01. Hostname: "
$CN += get-content env:computername
$CN >> $FileName

Next, I added a script to check the local active IPv4 addresses and check if one of these is an IP out of our VPN range (change xxx.xxx to your IP Range):
$ip=get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1}
$d = $ip.ipaddress[0]
$ip |foreach {
if($ip.VALUE -like "xxx.xxx*")
{ $d = $ip.VALUE}
}
$ip = "02. IP-Address: "
$ip += $d
$ip >> $FileName

Now I added a script that checks if the User which is logged on have local admin rights and write the result in the logfile:
$LA ="03. Local Adminrights: no"
if(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{$LA ="03. Local Adminrights: yes"}
$LA >> $FileName

Next step is to check the Vendor, the Model, ServiceTag and Express Service Code of your Client:
$vendor = "04. Vendor: "
$vendor += (Get-WMIObject -Class Win32_Bios).Manufacturer
$vendor >> $FileName
$vModel = "05. Model: "
$vModel += (Get-WmiObject -Class:Win32_ComputerSystem).Model
$vModel >> $FileName
$Service = "06. Service tag: "
$Service += (Get-WMIObject -Class Win32_Bios).serialnumber
$Service >> $FileName
$vESCode = "07. Express Service Code: "
$vESCode += (Get-ExpressServiceCode)
$vESCode >> $FileName

After that we add some code to get our actual BIOS Version:
$Bios = "08. Bios Version: "
$Bios += (Get-WMIObject -Class Win32_Bios).SMBIOSBIOSVersion
$Bios >> $FileName

The next Script will show the connected Printers including the Servername and the UNC Path of the Printer:
"09. connected network printers" >> $FileName
$Printer = Get-WMIObject -Class Win32_Printer| where {$_.Location.length -gt 1}
$Printer |foreach {
$prnName = "Name: "
$prnName += $_.ShareName
$prnName >> $FileName
$prnServer = "Printserver: "
$prnServer += $_.SystemName
$prnServer >> $FileName
$linkprn = "Link: "
$linkprn += $_.SystemName + "\" + $_.ShareName
$linkprn >> $FileName
" " >> $FileName
}

Now we have to theck the connected network shares:
"10. connected networkshares" >> $FileName
$vitns = Get-WmiObject -class "Win32_MappedLogicalDisk"
$vitns | foreach {
$vitnsnp = $_.Name + " " + $_.ProviderName
$vitnsnp >> $FileName
}
" " >> $FileName

The last script we add is a list of users and groups who are members of the local admin Group.
I added this one because I want to see all members too and a separate entry for the local user.
"11. members of local administrators group" >> $FileName
net localgroup administrators | where {$_ -AND $_ -notmatch "command completed successfully"} | select -skip 4 >> $FileName
$Delete = Get-Content $Filename
$del = "Der Befehl wurde erfolgreich ausgefhrt."
$Delete = $Delete | Where {$_ -ne $del}
$Delete | Out-File $FileName -Force

To Open the file, we just add the invoke-item command to the script:
Invoke-Item $FileName
Youre done.
The Result of this is good for our support.
Maybe you can use some of these scripts for yours 🙂

01. Hostname: NB0815
02. IP-Address: 10.xxx.xxx.xxx
03. Local Adminrights: yes
04. Vendor: Dell Inc.
05. Model: Latitude E7440
06. Service tag: xxxx
07. Express Service Code: 123456789
08. Bios Version: A10
09. connected network printers
Name: PRN1234
Printserver: \\SRV0001
Link: \\SRV0001\PRN1234
Name: PRN456
Printserver: \\SRV0001
Link: \\SRV0001\PRN456
10. connected networkshares
H: \\Domain.local\dfs$\Data
U: \\Domain.local\dfs$\home\username
11. members of local administrators group
Administrator
domain.local\Domain Admins
domain.local\SysAdmins

I think I will add some more options for this in the future.
Have fun with it…

Windows – Permission commands

Here are a few useful commands to setup Windows file permissions.
take ownership of a folder(including files and subfolders)
Takeown /f foldername /r /d y
reset permission of folder (including all files and subfolders) to inherit
Icacls folder /reset /T
disable inheritance for a folder
icacls Folder/inheritance:d
Set read permission for AD group on folder and subfolder
Icalcs Folder /grant domain\Groupname:(OI)(CI)RX /T
Set modify permission for AD group on folder and subfolder
Icalcs Folder /grant domain\Groupname:(OI)(CI)M /T
Set listing permission for AD group to this folder only
Icacls Folder /grant domain\group:(X,RD)
Remove Permission from Folder and subfolder
Icacls folder /remove domain\group

Windows – Powershell Command to remove/add Printers

To remove / add printers and their drivers in Microsoft Windows 8 / Windows Server 2012 via Powershell you can find here some examples of Powershell commands:
Remove Network printers:
(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Server\Printer")
Add Network printers:
(New-Object -ComObject WScript.Network).AddWindowsPrinterConnection("Server\Printer")
remove specific driver
Remove-PrinterDriver –Name "Microsoft XPS Document Writer v4"
This will remove exact the Microsoft XPS Document Writer v4 Driver.
If you want to remove all Drivers from Canon for example use this command:
Remove-PrinterDriver –Name "Canon"

Windows – delete Offline Folder Cache


In Windows 7 there is no user interface to delete Ofline Files cache (CSC cache).  The only way to delete cache is using registry key. Detail steps are given below.
Open Registry editor (Execute Regedit from Run window)
Traverse to the path path:HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesCscParameters 
If Parameters key does not exist under CSC you can create a new node with that name.
Now in the Parameters node create a new registry value with the name FormatDatabase of type REG_DWORD (i.e DWord 32-bit value)
Set the data in this new registry value to 1.
Close registry editor.
Reboot the machine

Windows – Powershell Commands

a
   Get-Acl                    Get permission settings for a file or registry key
   Set-Acl                    Set permissions
   Get-Alias            gal   Return alias names for Cmdlets
   Import-Alias        ipal   Import an alias list from a file
   New-Alias            nal   Create a new alias.
   Set-Alias            sal   Create or change an alias
   Get-AuthenticodeSignature  Get the signature object associated with a file
   Set-AuthenticodeSignature  Place a signature in a .ps1 script or other file
c
   Set-Location  cd/chdir/sl  Set the current working location
   Get-ChildItem   dir/ls/gci Get child items (contents of a folder or registry key)
   Get-Command          gcm   Retrieve basic information about a command
   Measure-Command            Measure running time
   Trace-Command              Trace an expression or command
   Add-Content           ac   Add to the content of the item
   Get-Content   cat/type/gc  Get content from item (specific location)
   Set-Content           sc   Set content in the item (specific location)
   Clear-Content        clc   Remove content from a file/item
   ConvertTo-Html             Convert the input into an HTML table
   ConvertFrom-SecureString   Convert a secure string into an encrypted standard string
   ConvertTo-SecureString     Convert an encrypted standard string into a secure string
   Clear-Host      clear/cls  Clear the screen
   Clear-Item           cli   Remove content from a variable or an alias
   Copy-Item     copy/cp/cpi  Copy an item from a namespace location
   Get-Credential             Get a security credential (username/password)
   Get-Culture                Get region information (language and keyboard layout)
d
   Get-ChildItem   dir/ls/gci Get child items (contents of a folder or registry key)
   Get-Date                   Get current date and time
   Set-Date                   Set system time on the host system
   Get-PSDrive          gdr   Get drive information (DriveInfo)
   New-PSDrive      mount/ndr Install a new drive on the machine
   Remove-PSDrive       rdr   Remove a provider/drive from its location
e
   Get-Eventlog               Get eventlog data
   Get-ExecutionPolicy        Get the execution policy for the shell
   Set-ExecutionPolicy        Change the execution policy (user preference)
   Export-Alias         epal  Export an alias list to a file
   Export-Clixml              Produce a clixml representation of powershell objects
   Export-Console             Export console configuration to a file
   Export-Csv          epcsv  Export to Comma Separated Values (spreadsheet)
   Invoke-Expression          Run a PowerShell expression
   Exit                       Exit Powershell
f
   ForEach-Object    foreach  Loop for each object in the pipeline
   ForEach                    Loop through values in the pipeline
   Format-Custom         fc   Format output using a customized view
   Format-List           fl   Format output as a list of properties, each on a new line
   Format-Table          ft   Format output as a table
   Format-Wide           fw   Format output as a table listing one property only
g
   Get-Item              gi   Get a file/registry object (or any other namespace object)
   Get-ChildItem   dir/ls/gci Get child items (contents of a folder or registry key)
h
   Get-Help            help   Open the help file
   Add-History                Add entries to the session history
   Get-History  history/h/ghy Get a listing of the session history
   Invoke-History     r/ihy   Invoke a previously executed Cmdlet
   Get-Host                   Get host information
   Clear-Host      clear/cls  Clear the screen
   Read-Host                  Read a line of input from the host console
   Write-Host                 Display objects through the host user interface
i
   if                         Conditionally perform a command
   Import-Clixml              Import a clixml file and rebuild the PS object
   Import-Csv         ipcsv   Take values from a CSV list and send objects down the pipeline.
   Get-Item              gi   Get a file object or get a registry (or other namespace) object
   Invoke-Item           ii   Invoke an executable or open a file (START)
   New-Item              ni   Create a new item in a namespace
   Remove-Item  rm/del/erase/rd/ri/rmdir   Remove an item
   Set-Item              si   Change the value of an item
   Clear-ItemProperty         Delete the value of a property
   Copy-ItemProperty          Copy a property along with its value
   Get-ItemProperty           Retrieve the properties of an object
   Move-ItemProperty          Move a property from one location to another
   New-ItemProperty           Set a new property of an item at a location
   Remove-ItemProperty        Delete the property and its value from an item
   Rename-ItemProperty        Rename a property of an item
   Set-ItemProperty           Set the value of a property
k
   Stop-Process    kill/spps  Stop a running process
l
   Get-Location    pwd / gl   Get and display the current location
   Pop-Location        popd   Set the current working location from the stack
   Push-Location      pushd   Push a location to the stack
   Set-Location  cd/chdir/sl  Set the current working location
m
   Add-Member                 Add a member to an instance of a PowerShell object
   Get-Member            gm   Enumerate the properties of an object
   Move-Item      move/mv/mi  Move an item from one location to another
o
   Compare-Object             Compare the properties of objects
   Group-Object       group   Group the objects that contain the same value for a common property
   Measure-Object             Measure the properties of an object
   New-Object                 Create a new .Net object
   Select-Object     select   Select properties of objects.
   Sort-Object         sort   Sort objects by property value
   Where-Object               Filter the objects passed along the command pipeline.
   Out-Default                Send output to default
   Out-File                   Send command output to a file
   Out-Host              oh   Send the pipelined output to the host
   Out-Null                   Send output to null
   Out-Printer           lp   Send the output to a printer
   Out-String                 Send objects to the host as strings
p
   Powershell                 Launch a powershell session
   Convert-Path        cvpa   Convert a ps path to a provider path
   Join-Path                  Combine a path and child-path
   Resolve-Path        rvpa   Resolves the wildcards in a path
   Split-Path                 Return part of a path
   Test-Path                  Return true if the path exists, otherwise return false
   Get-Pfxcertificate         Get pfx certificate information
   Pop-Location        popd   Set the current working location from the stack
   Push-Location      pushd   Push a location to the stack
   Get-Process       ps/gps   Get a list of processes on a machine
   Stop-Process    kill/spps  Stop a running process
   Clear-ItemProperty   clp   Remove the property value from a property
   Copy-ItemProperty    cpp   Copy a property along with it's value
   Get-ItemProperty      gp   Retrieve the properties of an object
   Move-ItemProperty     mp   Move a property from one location to another
   New-ItemProperty           Set a new property
   Remove-ItemProperty   rp   Remove a property and its value
   Rename-ItemProperty  rnp   Renames a property at its location
   Set-ItemProperty      sp   Set a property at the specified location to a specified value
   Get-PsProvider             Get information for the specified provider
   Set-PSdebug                Turn script debugging on or off
   Add-PsSnapIn               Add snap-ins to the console
   Get-PsSnapin               List PowerShell snap-ins on this computer
   Remove-PSSnapin            Remove PowerShell snap-ins from the console
r
   Read-Host                  Read a line of input from the host console
   Remove-Item  rm/del/erase/rd/ri/rmdir   Remove an item
   Rename-Item      ren/rni   Change the name of an existing item
   Rename-ItemProperty        Rename a property of an item
s
   Get-Service          gsv   Get a list of services
   New-Service                Create a new service
   Restart-Service            Stop and then restart a service
   Resume-Service             Resume a suspended service
   Set-Service                Change the start mode/properties of a service
   Sort-Object         sort   Sort objects by property value
   Start-Service       sasv   Start a stopped service
   Stop-Service        spsv   Stop a running service
   Suspend-Service            Suspend a running service
   Start-Sleep        sleep   Suspend shell, script, or runspace activity
   Select-String              Search through strings or files for patterns
t
   Tee-Object                 Send input objects to two places
   New-Timespan               Create a timespan object
   Trace-Command              Trace an expression or command
   Get-Tracesource            Get components that are instrumented for tracing.
   Set-Tracesource            Trace a PowerShell component
   Start-Transcript           Start a transcript of a command shell session
   Stop-Transcript            Stop the transcription process
u
   Get-Uiculture              Get the ui culture information
   Get-Unique            gu   Get the unique items in a collection
   Update-Formatdata          Update and append format data files
   Update-Typedata            Update the current extended type configuration
v
   Clear-Variable       clv   Remove the value from a variable
   Get-Variable          gv   Get a powershell variable
   New-Variable          nv   Create a new variable
   Remove-Variable       rv   Remove a variable and its value
   Set-Variable      set/sv   Set a variable and a value
w
   Where-Object       where   Filter input from the pipeline
   While (condition) {action} else {action}
   Get-WMIobject              Get WMI class information
   Write-Debug                Write a debug message to the host display
   Write-Error                Write an object to the error pipeline.
   Write-Output        echo   Write an object to the pipeline
   Write-Progress             Display a progress bar
   Write-Verbose              Write a string to the host's verbose display
   Write-Warning              Write a warning message
   #                          Comment / Remark

 

Windows – Komponenten per Befehl Starten


Hier eine Übersicht von Befehlen die die Windows Administration einfach machen.
Einfach Windows – Taste + “R” drĂŒcken und den Befehl eingeben und schon seit Ihr da, wo Ihr hinwollt.
System/Systemeinstellungen sysdm.cpl
Firewall wf.msc
Dienste services.msc
Systemsteuerung control
Taskmanager taskmgr
Remotedesktop mstsc
Aufgabenplanung taskschd.msc
MS-Dos Eingabeaufforderung cmd
DatentrĂ€gerbereinigung cleanmgr
Defragmentierung dfrgui
Snipping-Tool snippingtool
Write wordpad
Notepad notepad
Taschenrechner calc
Datum und Uhrzeit timedate.cpl
Gamecontroller joy.cpl
Regions- und Sprachoptionen intl.cpl
SoundÂŽs und AudiogerĂ€te mmsys.cpl
Sprach- ein und -ausgabe sapi.cpl
Telefon- und Modemoptionen telephon.cpl
Mauseigenschaften main.cpl
Internet Optionen inetcpl.cpl
Software / Programme & Funktionen appwiz.cpl
Anzeige Bildschirmauflösung desk.cpl
Energieoptionen powercfg.cpl
GerĂ€temanager (Windows 7) hdwwiz.cpl
Hardware-Assistent (Windows XP) hdwwiz.cpl
Mauseigenschaften main.cpl
Diese Befehle funktionieren ab Windows XP und auch allen Windows Server Betriebssystemen ab Windows Server 2003 einwandfrei.

Windows – Per Befehl den Verlauf vom Internet Explorer löschen


Es gibt einen sehr nĂŒtzlichen Befehl, um den Verlauf (History) des Internet Explorers per Shortcut bzw. per Befehl zu löschen. Ihr könnt den Befehl einfach in eine Desktop-VerknĂŒpfung einfĂŒgen oder direkt aus einem DOS-Fenster aufrufen und es werden daraufhin alle Verlaufsdaten (Browserverlauf) des Internet Explorers gelöscht.
Diese Funktion wird seit der Version 7 des Internet Explorers unterstĂŒtzt.
Der Befehl lautet:
rundll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Windows 7 – Installation via USB Stick


Zum Installieren von Windows 7 via USB Stick muss der USB Stick Bootbar gemacht werden.
Vorbereitungen:
Es wird ein Windows Computer mit Windows 7 oder Windows Vista benötigt.
Der USB Stick muss mindestens 4GB haben und an dem Computer angeschlossen sein.
Einlegen einer Windows 7 Installations DVD
Dies geht wie folgt:
1. Öffnen der Eingabeaufforderung:
Startmenu öffnen und im Suchfeld (nur Vista oder Win7) CMD eingeben und mit Enter bestĂ€tigen
ODER
Windowstaste + “R” gleichzeitig drĂŒcken und dann CMD eingeben und mit Enter bestĂ€tigen

2. In der Eingabeaufforderung DISKPART eingeben und mit Enter bestĂ€tigen

3. LIST Disk eingeben und mit Enter bestĂ€tigen
4. in der Übersicht den USB Stick raussuchen

Bei mir ist es DatentrĂ€ger 1 also DISK 1
5. select disk 1 (oder sel disk 1 fĂŒr Schreibfaule) eingeben und mit Enter bestĂ€tigen
6. nun alle Fettgedruckten Befehle nach und nach eingeben und jeweils mit Enter bestÀtigen (bitte bei der Eingabe der Befehle auf Gross- und Kleinschreibung achten)
CLEAN
CREATE PARTITION PRIMARY
SELECT PARTITION 1
ACTIVE
FORMAT FS=NTFS quick 
Die Formatierung dauert etwas…
ASSIGN
EXIT
7. Nun gibt man folgenden Befehl ein:
d: (Falls das DVD Laufwerk den Laufwerksbuchstaben D hat ansonsten abĂ€ndern)
cd boot
bootsect.exe /NT60 H:
 (hier auch wieder beachten das H: der Laufwerksbuchstabe des USB Sticks ist)
8. Kopieren des gesamten Inhalts der Windows 7 Installations DVD auf den USB Stick.
9. GerÀt via USB Stick booten und mit der Installation beginnen.

Windows 7 / Vista – PartitionsgrĂ¶ĂŸe Ă€ndern


Die Ă„nderung der PartitionsgrĂ¶ĂŸen der Festplatte war in der Vergangenheit immer ein riesen Problem und konnte eigentlich nur mit kostenpflichtigen Programmen durchgefĂŒhrt werden. Dies ist aber Gott sei Dank seit Windows Vista und Windows 7 vorbei. Wir möchten in diesem Beitrag darauf eingehen, wie Ihr mit Windows Boardmitteln Partitionen verkleinern bzw. vergrĂ¶ĂŸern könnt.
[info]
Absolut notwendig ist die DurchfĂŒhrung einer aktuellen Datensicherung, bevor Ihr Änderungen an den Partitionen vornehmt.
[/info]
Nachdem Ihr die Datensicherung durchgefĂŒhrt habt ruft Ihr bitte die Computerverwaltung auf, am einfachste mit Rechte Maustaste auf “Computer” und danach auf “Verwalten“.

Auf der linken Seite befindet sich die DatentrĂ€gerverwaltung. Diese zeit die aktuelle Verteilung der Partitionen der einzelnen Festplatten genau an.
Durch ein Rechtsklick auf die entsprechende Partition erscheint folgendes KontextmenĂŒ.

In diesem Fall kann dort nur “Volume verkleinern
” ausgewĂ€hlt werden, weil kein freier Speicherplatz vorhanden ist. Sollte aber dieser noch vorhanden sein, kann hierĂŒber aus das “Volume erweitern
” ausgewĂ€hlt werden.

Nachdem ich “Volume verkleinern” ausgewĂ€hlt habe errechnet das Betriebssystem (in diesem Fall Vista), um wieviel MB ich die Partition verkleinern kann. Vista lĂ€ĂŸt in diesem Fall nur ca. 42GB zu, da derzeit noch soviel freier Speicherplatz auf dem DatentrĂ€ger vorhanden ist und durch die Verkleinerung keine Daten verloren gehen dĂŒrfen.
Nachdem abschließend “Verkleinern” gedrĂŒckt wurde wird die Partition um den zu verkleinernden Speicherplatz verkleinert. Das VergrĂ¶ĂŸern von Volumes lĂ€uft genauso ab.

Windows – USB Stick Bootbar machen


1. Öffnen Sie die Eingabeaufforderung.
2. Geben Sie Folgendes ein:
diskpart
3. Geben Sie Folgendes an der Eingabeaufforderung DISKPART ein:
list partition
Notieren Sie sich die Partitionsnummer, die Sie als aktiv markieren möchten.
4. Geben Sie Folgendes an der Eingabeaufforderung DISKPART ein:
select partition XXX
WÀhlen Sie die Partition n aus, die Sie als aktiv markieren möchten.
5. Geben Sie Folgendes an der Eingabeaufforderung DISKPART ein:
active