Archive for the 'Scripts' Category

PowerShell Script: Zip up a folder and email it

Cool method for scripting attaching a file and emailing using Powershell.  The script also displays how to zip up a destination using Out-zip.

$sender = sender@host.com
$recipient = recipient@host.com
$server = mail.host.com
$targetFolder = c:\MyFolder
$file = c:\MyZipFile.zip
if ( [System.IO.File]::Exists($file) )
{
  remove-item -force $file
}

gi $targetFolder | out-zip $file $_
$subject = “Sending a File ” + [System.DateTime]::Now
$body = “I’m sending a file!”
$msg = new-object System.Net.Mail.MailMessage $sender, $recipient, $subject, $body
$attachment = new-object System.Net.Mail.Attachment $file
$msg.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $server
$client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$client.Send($msg)

Mike Hodnick : PowerShell: Zip up a folder and email it

Powershell Script : Generate rdp-files from AD

NOTE:  this script requires the Quest Active Directory cmdlets

#generate-rdpfiles.ps1

$input = Get-QADComputer -ErrorAction SilentlyContinue -SizeLimit 0 | Where-Object { $_ .operatingsystem -match “Server” }

$RDPRoot = ‘C:\RDP-Files’

if ( -not ( Test-Path -Path $RDPRoot )) {

    New-Item -Path $RDPRoot -ItemType Directory | Out-Null

}

$input | ForEach-Object {

    $path = “$RDPRoot\$($_.Name).rdp”

    $rdpfile = Test-Path -Path $path

    if ( $rdpFile -eq $true ) {

        Clear-Content -Path $path

    }

    Add-Content -Path $path -Force -Value @”

screen mode id:i:1

desktopwidth:i:1152

desktopheight:i:864

session bpp:i:16

winposstr:s:0,1,0,0,1032,795

full address:s:$($_.Name)

compression:i:1

keyboardhook:i:2

audiomode:i:2

redirectprinters:i:0

redirectcomports:i:0

redirectsmartcards:i:1

redirectclipboard:i:1

redirectposdevices:i:0

drivestoredirect:s:*

displayconnectionbar:i:1

autoreconnection enabled:i:1

authentication level:i:0

prompt for credentials:i:0

negotiate security layer:i:1

remoteapplicationmode:i:0

alternate shell:s:

shell working directory:s:

disable wallpaper:i:0

disable full window drag:i:0

allow desktop composition:i:1

allow font smoothing:i:1

disable menu anims:i:0

disable themes:i:0

disable cursor setting:i:0

bitmapcachepersistenable:i:1

gatewayhostname:s:

gatewayusagemethod:i:0

gatewaycredentialssource:i:4

gatewayprofileusagemethod:i:1

“@

}

PowerGUI - Administrative Powershell Console : Generate rdp-files from AD …

PowerShell Script: Get Listed Service Packs & Hotfixes

$strComputer = "."

$colItems = get-wmiobject -class "Win32_QuickFixEngineering" -namespace "root\CIMV2" `
-computername $strComputer

foreach ($objItem in $colItems) {
      write-host "Caption: " $objItem.Caption
      write-host "CS Name: " $objItem.CSName
      write-host "Description: " $objItem.Description
      write-host "Fix Comments: " $objItem.FixComments
      write-host "HotFix ID: " $objItem.HotFixID
      write-host "InstallationDate: " $objItem.InstallDate
      write-host "Installed By: " $objItem.InstalledBy
      write-host "Installed On: " $objItem.InstalledOn
      write-host "Name: " $objItem.Name
      write-host "Service Pack In Effect: " $objItem.ServicePackInEffect
      write-host "Status: " $objItem.Status
      write-host
}

PowerShell Script: Schedule Reboot of Server

$now=get-date

$MachineName=read-host "Please Enter Machine Name you wish to reboot :"

$When=read-host "Please enter time when you wish to reboot the server Later THAN ($now) :"

$results=$now.subtract($when)

#write-host $Results Results

$time2act=$now.Subtract($results)

#Write-host $time2act is time2act

$action=$time2act.subtract($now)

$Sec2Act= $action.totalseconds

$totalsecs="{0:N0}" -f $Sec2Act

$SecINint=[int]$totalsecs

write-host $testint

if($results -le 0)
{
write-host "done"
Write-host $MachineName "will Reboot in next " $SecINint Seconds
shutdown -s -m $machineName -t $SecINint
}
else {
write-host "Time entered has already past,please enter time later than " [$now] -Background "RED"
}

PowerShell Script: Get Last Reboot Time

$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "Machine Name"
$c.Cells.Item(1,2) = "IP Address"
$c.Cells.Item(1,3) = "MAC Address"
$c.Cells.Item(1,4) = "Last Boot Time"
$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$d.EntireColumn.AutoFit()
$m = 2
$x = get-content C:\Myworkplace\Clientlist.txt
foreach ($i in $x)
{$y = get-wmiobject Win32_NetworkAdapterConfiguration -computername $i -Filter "IPenabled = ‘True’"
foreach ($j in $y)
{$c.Cells.Item($m, 1) = $j.DNSHostName
$c.Cells.Item($m, 2) = $j.IPAddress
$c.Cells.Item($m, 3) = $j.MACAddress}
$date = new-object -com WbemScripting.SWbemDateTime
$z = get-wmiobject Win32_OperatingSystem -computername $i
foreach ($k in $z)
{$date.value = $k.lastBootupTime
If ($k.Version -eq "5.2.3790" )
{$c.Cells.Item($m, 4) = $Date.GetVarDate($True)}
Else
{$c.Cells.Item($m, 4) = $Date.GetVarDate($False)}
}
$m = $m + 1
}

Windows PowerShell : Show-WmiClass

Jeffrey Snover of Microsoft posted this script to provide a simple way to show WMI Classes within PowerShell.

Here is a script that I use to show WMI classes. I think you’ll find it useful. There is an example after the script:

##############################
# Show-WmiClass - Show WMI classes
# Author: Microsoft
# Version: 1.0
# NOTE: Notice that this is uses the verb SHOW vs GET. That is because it
# combines a Getter with a format. SHOW was added as a new “official
# verb to deal with just this case.
#############################
param(
$Name = “.”,
$NameSpace = “root\cimv2″,
[Switch]$Refresh=$false
)
# Getting a list of classes can be expensive and the list changes infrequently.
# This makes it a good candidate for caching.
$CacheDir = Join-path $env:Temp “WMIClasses”
$CacheFile = Join-Path $CacheDir ($Namespace.Replace(”\”,”-”) + “.csv”)
if (!(Test-Path $CacheDir))
{
$null = New-Item -Type Directory -Force $CacheDir
}
if (!(Test-Path $CacheFile) -Or $Refresh)
{
Get-WmiObject -List -Namespace:$Namespace |
Sort -Property Name |
Select -Property Name |
Export-csv -Path $CacheFile -Force
}
Import-csv -Path $CacheFile |
where {$_.Name -match $Name} |
Format-Wide -AutoSize
###### EOF ###########

Example

PS> show-wmiclass account
MSFT_NetBadAccount Win32_Account Win32_AccountSID
Win32_SystemAccount Win32_UserAccount
PS> show-wmiclass account -namespace root\cimv2\terminalservices
Win32_TSAccount
PS> show-wmiclass -namespace root\cimv2\terminalservices
__AbsoluteTimerInstruction __ACE
__AggregateEvent __ClassCreationEvent
__ClassDeletionEvent __ClassModificationEvent
__ClassOperationEvent __ClassProviderRegistration
__ConsumerFailureEvent __Event
__EventConsumer __EventConsumerProviderRegistration
__EventDroppedEvent __EventFilter
__EventGenerator __EventProviderRegistration
__EventQueueOverflowEvent __ExtendedStatus
__ExtrinsicEvent __FilterToConsumerBinding
__IndicationRelated __InstanceCreationEvent
__InstanceDeletionEvent __InstanceModificationEvent
__InstanceOperationEvent __InstanceProviderRegistration
__IntervalTimerInstruction __MethodInvocationEvent
__MethodProviderRegistration __NAMESPACE
__NamespaceCreationEvent __NamespaceDeletionEvent
__NamespaceModificationEvent __NamespaceOperationEvent
__NotifyStatus __NTLMUser9X
__ObjectProviderRegistration __PARAMETERS
__PropertyProviderRegistration __Provider
__ProviderRegistration __QOSFailureEvent
__SecurityDescriptor __SecurityRelatedClass
__SystemClass __SystemEvent
__SystemSecurity __thisNAMESPACE
__TimerEvent __TimerInstruction
__TimerNextFiring __Trustee
__Win32Provider CIM_ElementSetting
CIM_LogicalElement CIM_ManagedSystemElement
CIM_Setting Win32_Terminal
Win32_TerminalError Win32_TerminalServiceSetting
Win32_TerminalServiceSettingError Win32_TerminalServiceToSetting
Win32_TerminalSetting Win32_TerminalTerminalSetting
Win32_TSAccount Win32_TSClientSetting
Win32_TSEnvironmentSetting Win32_TSGeneralSetting
Win32_TSLogonSetting Win32_TSNetworkAdapterListSetting
Win32_TSNetworkAdapterSetting Win32_TSPermissionsSetting
Win32_TSRemoteControlSetting Win32_TSSessionDirectory
Win32_TSSessionDirectorySetting Win32_TSSessionSetting
PS>

Windows PowerShell : Show-WmiClass