Powershell

#Copying a single source directory to multiple destinations

«c:\fso1″,»c:\fso2″,»c:\fso3» | % {Copy-Item c:\fso -Recurse -Destination $_}

Note  The % symbol is an alias for the Foreach-Object cmdlet.

 

#Creating zip archives and e-mailing them

The cool thing about using Windows PowerShell to automate creating .zip archives and emailing them is that it is easily scripted. In fact, it can easily be turned into a scheduled task if one wishes to take the next logical step.

The first thing to do is to create a .zip archive of the folder that contains the files that you want to archive. I like to create two variables: one for the source files and one for the destination that will hold the .zip archive of the files. I then use the Test-Path cmdlet to ensure the archive file is not already there, and if it is, I delete it. This prevents error messages. Here is the first three lines of my script:

$source = «C:\fso»
$destination = «C:\backup\FSO_Backup.zip»
If(Test-path $destination) {Remove-item $destination}

Now I need to add the assembly that contains the compression classes from .NET Framework 4.5. To do this, I use the Add-Type cmdlet, specify that it is an assembly, and provide the name System.IO.Compression.Filesystem to it. This command is shown here:

Add-Type -assembly «system.io.compression.filesystem»

The final command creates the .zip archive. It uses the CreateFromDirectory static method from the ZipFile class:

[io.compression.zipfile]::CreateFromDirectory($Source, $destination)

This section of the script is shown here:

$source = «C:\fso»
$destination = «C:\backup\FSO_Backup.zip»
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly «system.io.compression.filesystem»
[io.compression.zipfile]::CreateFromDirectory($Source, $destination)

Now I need to email the archive. To do this, I use the Send-MailMessage cmdlet. This cmdlet can do all sorts of stuff, but for our purposes, I need to add the To and From parameters, the attachment path, the subject, and the body message.

This is all pretty simple. I also need to specify the appropriate SMTP server for my mail application, and specify if I need to use credentials or SSL. It may take a bit of practice or research to get everything working perfectly. But when it is done, well, it is done. Here is the command I use:

Send-MailMessage -From «ScriptingGuys@Outlook.com» -To «ScriptingGuys@Outlook.com» -Attachments $destination -Subject «$(Split-Path $destination -Leaf)» -Body «File attached» -SmtpServer «smtp-mail.outlook.com» -UseSsl -Credential «ScriptingGUys@Outlook.com»

The last requirement is to clean up by deleting the previously created .zip archive. This is simple. I use a Remove-Item command that uses the $Destination variable:

Remove-Item $destination

The complete script is shown here:

$source = «C:\fso»
$destination = «C:\backup\FSO_Backup.zip»
If(Test-path $destination) {Remove-item $destination}
Add-Type -assembly «system.io.compression.filesystem»
[io.compression.zipfile]::CreateFromDirectory($Source, $destination)
Send-MailMessage -From «ScriptingGuys@Outlook.com» -To «ScriptingGuys@Outlook.com» -Attachments $destination -Subject «$(Split-Path $destination -Leaf)» -Body «File attached» -SmtpServer «smtp-mail.outlook.com» -UseSsl -Credential «ScriptingGUys@Outlook.com»
Remove-Item $destination

 

#Get AD account SID

Get-WmiObject win32_useraccount -ComputerName DC | where {$_.name -like «username»} | select caption,status,sid

 

#Get AD users in OU

Get-ADUser -LDAPFilter ‘(name=*)’ -SearchBase ‘OU=Sales,DC=Test,DC=local’ | select DistinguishedName,Enabled,GivenName,Name,ObjectClass,SamAccountName,SurnameUserPrincipalName | ConvertTo-Html | Out-File d:\temp\OU.html

 

 #Get MD5 Hash

String
$someString = «Hello World!»
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))
File
$someFilePath = «D:\Soft\Cisco\IOS\29xx\c2900-universalk9-mz.SPA.154-3.M2.bin»
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))

File with PSv4 and higher
Get-FileHash <filepath> -Algorithm MD5

 

 #Get OS registered in ActiveDirectory

Get-ADComputer -Filter * -Properties OperatingSystem | Select OperatingSystem -unique | Sort OperatingSystem

 

 #Get DHCP Reservations

Get-DhcpServerv4Reservation -ComputerName Server -ScopeID 192.168.0.0 | where {$_.Name -notlike «ws*» -and $_.Name -ne $null} | select IPAddress,ClientId,Description,Name | sort IPAddress | ConvertTo-Html | Out-File d:\temp\Srv_dhcp.html

Get-DhcpServerv4Lease -ComputerName Server -ScopeID 192.168.0.0 | where {$_.HostName -eq $null -and $_.ClientId -notlike «40-83-de*» -and $_.ClientId -notlike «00-23-68*»}

 

#Get printers from print server

Get-Printer -ComputerName server | select ComputerName,Name,DriverName,Location,ShareName,PortName | sort ShareName | ConvertTo-Html | Out-File d:\temp\printers_server.html

 

#Get SQL product key

function Get-SQLserverKey {
## function to retrieve the license key of a SQL 2008 Server.
param ($targets = «.»)
$hklm = 2147483650
$regPath = «SOFTWARE\Microsoft\Microsoft SQL Server\100\Tools\Setup»
$regValue1 = «DigitalProductId»
$regValue2 = «PatchLevel»
$regValue3 = «Edition»
Foreach ($target in $targets) {
$productKey = $null
$win32os = $null
$wmi = [WMIClass]»\\$target\root\default:stdRegProv»
$data = $wmi.GetBinaryValue($hklm,$regPath,$regValue1)
[string]$SQLver = $wmi.GetstringValue($hklm,$regPath,$regValue2).svalue
[string]$SQLedition = $wmi.GetstringValue($hklm,$regPath,$regValue3).svalue
$binArray = ($data.uValue)[52..66]
$charsArray = «B»,»C»,»D»,»F»,»G»,»H»,»J»,»K»,»M»,»P»,»Q»,»R»,»T»,»V»,»W»,»X»,»Y»,»2″,»3″,»4″,»6″,»7″,»8″,»9″
## decrypt base24 encoded binary data
For ($i = 24; $i -ge 0; $i—) {
$k = 0
For ($j = 14; $j -ge 0; $j—) {
$k = $k * 256 -bxor $binArray[$j]
$binArray[$j] = [math]::truncate($k / 24)
$k = $k % 24
}
$productKey = $charsArray[$k] + $productKey
If (($i % 5 -eq 0) -and ($i -ne 0)) {
$productKey = «-» + $productKey
}
}
$win32os = Get-WmiObject Win32_OperatingSystem -computer $target
$obj = New-Object Object
$obj | Add-Member Noteproperty Computer -value $target
$obj | Add-Member Noteproperty OSCaption -value $win32os.Caption
$obj | Add-Member Noteproperty OSArch -value $win32os.OSArchitecture
$obj | Add-Member Noteproperty SQLver -value $SQLver
$obj | Add-Member Noteproperty SQLedition -value $SQLedition
$obj | Add-Member Noteproperty ProductKey -value $productkey
$obj
}
}
Get-SQLserverKey

 

#Ping few comps

$comps = «ws-1″,»ws-2″,»ws-3»
do {
ping $comps[0]
ping $comps[1]
ping $comps[2]
}
while ($comps -ne «qwe»)

 

#Send e-mail message

$CredUser = «me@mydom.com»
$CredPassword = «mypass!»

$EmailFrom = $CredUser
$EmailTo = $CredUser
$Subject = «Test mail Subject»
$Body = «Test Email Body»
$SMTPServer = «www.myemailvendor.biz»

$msg = new-object Net.Mail.MailMessage
$msg.From = $EmailFrom
$msg.to.Add($EmailTo)
$msg.Subject = $Subject

$msg.Body = $Body

$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 465)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($CredUser, $CredPassword)

$SMTPClient.Send($msg)
GMAIL
Входящие данные сообщения:
$From = «elimsmail@gmail.com»
$To = «test@gmail.com»
$SMTPServer = «smtp.gmail.com»
$SMTPPort = «587»
$Username = «elimsmail»
$Password = «yourpassword»
$subject = «hello»
$body = «bodytext»

Формируем сообщение в формате html:
$message = New-Object System.Net.Mail.MailMessage $From, $To
$message.Subject = $subject
$message.IsBodyHTML = $true
$message.Body = $body

Отправляем:
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$smtp.Send($message)

 

#Unzip files

To add the assembly, I use the Add-Type cmdlet and specify the –Assembly parameter. This command is shown here:

Add-Type -assembly «system.io.compression.filesystem»

The command to extract the zipped files to a folder is:

[io.compression.zipfile]::ExtractToDirectory($BackUpPath, $destination)

Here are a few things to keep in mind:

The first parameter I call ($BackUpPath) must point to a specific zipped file.
The second parameter (the one I call $destination) must point to a folder.
Both of these parameters are strings. Therefore, I cannot use a ziparchive object or a directoryinfo object as input types.
The extraction does not include the root folder.
My complete script is shown here:

$BackUpPath = «C:\backup\fso.zip»
$Destination = «C:\recovered»
Add-Type -assembly «system.io.compression.filesystem»
[io.compression.zipfile]::ExtractToDirectory($BackUpPath, $destination)

When I go to my C:\recovered folder, I see that all of the files from the fso.zip folder are now present.

 

#Verify syntax of path

Use the –IsValid parameter of the Test-Path cmdlet, for example:

PS C:\> $a = «c:\myfolder\nonexistentfile.txt»

PS C:\> Test-Path $a -IsValid

True

PS C:\> $b = «c:\my()(*&^%\afile.txt»

PS C:\> Test-Path $b -IsValid

False

Note  This command verifies if the syntax is correct for the provider, but it does not verify if the file exists.

Оставьте комментарий