full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/GithubGist/yzorg_8215221_raw_6fee7d7a8df7cfd80fe64297c583f2d162ad840f_profile_basic.ps1
|
yzorg_8215221_raw_6fee7d7a8df7cfd80fe64297c583f2d162ad840f_profile_basic.ps1
|
Write-Host "START [$($MyInvocation.MyCommand.Name)] $(get-date -f yyyyMMdd.HHmmss.ff)"
# cd to the first directory in the path that contains a program, script, or file
filter gowhere { where.exe $args | select -first 1 | Split-Path -Parent | cd }
sal w where.exe # powershell pre-defines where to be 'SQL-like' where for filtering sets or streams,
sal which where.exe # *nix-friendly
Write-Host "END [$($MyInvocation.MyCommand.Name)] $(get-date -f yyyyMMdd.HHmmss.ff)"
return
# $PSScriptRoot
|
PowerShellCorpus/GithubGist/psudmant_7031044_raw_7be1c65d5bd664c082686411d423d61030c1d880_gistfile1.ps1
|
psudmant_7031044_raw_7be1c65d5bd664c082686411d423d61030c1d880_gistfile1.ps1
|
# set this to your head node hostname (run hostname)
HEAD_NODE_NAME=master
if [ `hostname` = $HEAD_NODE_NAME ]; then
NODES=`qconf -sel | grep -v $HEAD_NODE_NAME`
for NODE in $NODES; do
SCRIPT_PATH=$(dirname `which $0`)
qsub -l h=$NODE $SCRIPT_PATH
done
else
# YOUR COMMANDS YOU WANT TO EXECUTE HERE
fi
|
PowerShellCorpus/GithubGist/pkirch_507ae99421c3cf1eba94_raw_e1e63650250147ddf6ceb81148937c692a9f2fa0_SetAzureSubscriptionCert.ps1
|
pkirch_507ae99421c3cf1eba94_raw_e1e63650250147ddf6ceb81148937c692a9f2fa0_SetAzureSubscriptionCert.ps1
|
# Get certificate from personal certificate store.
$cert = Get-Item Cert:\CurrentUser\My\096E6A67C50C4BCED9E27D51013CA92272F73FCD
# Add Azure subscription parameter set including name, ID, and certificate.
Set-AzureSubscription -SubscriptionName "Azure MSDN - pkirchner" -SubscriptionId c6244819-a8d6-4279-b492-4a47f4301c54 -Certificate $cert
# No output
|
PowerShellCorpus/GithubGist/Scuzzbopper_7656383_raw_1c1e9d7a5440014e55e6c094670d39730f4bbe4b_gistfile1.ps1
|
Scuzzbopper_7656383_raw_1c1e9d7a5440014e55e6c094670d39730f4bbe4b_gistfile1.ps1
|
for /r %%i in (*.mov) do "C:\Program Files\Handbrake\HandBrakeCLI.exe" -i "%%i" -t 1 -o "D:\%%~ni.mp4" -f mp4 --strict-anamorphic -e x264 -b 3500 -2 -T --vfr -a 1 -E faac -B 128 -6 dpl2 -R 44.1 -D 0 --gain=0 --audio-copy-mask none --audio-fallback ffac3 -x ref=6:weightp=1:rc-lookahead=10:b-adapt=2:bframes=6:me=umh:subq=9:merange=32
|
PowerShellCorpus/GithubGist/ctrlbold_790abdc6fb4d010f8dda_raw_626bb3674a9c17981a0343e63bd6e5ac62f1dde4_Get-LocateCE.ps1
|
ctrlbold_790abdc6fb4d010f8dda_raw_626bb3674a9c17981a0343e63bd6e5ac62f1dde4_Get-LocateCE.ps1
|
if ($PSScriptRoot) { $location = $PSScriptRoot } else { $location = (Get-Location).Path }
$dll = "$location\System.Data.SqlServerCe.dll"
# look into SQLiteDataAdapter
if ($GetDll) {
$wc = New-Object System.Net.WebClient
$url = "https://netnerds.net/System.Data.SqlServerCe.dll"
$wc.DownloadFile($url,$dll)
}
# make it write to a temp db then replace
if (!(Test-Path $dll)) { throw "System.Data.SqlServerCe.dll not found. You can isntall SQL Server CE, or automatically download the DLL using -GetDll" }
[void][Reflection.Assembly]::LoadFile($dll)
$database = "$location\locate.sdf"
$connectionString = "Data Source=$database;"
if (!(Test-Path $database)) {
# Create database
$engine = New-Object System.Data.SqlServerCe.SqlCeEngine $connectionString
$engine.CreateDatabase()
$engine.Dispose()
$connection = New-Object System.Data.SqlServerCe.SqlCeConnection $connectionString
$connection.Open()
$command = New-Object System.Data.SqlServerCe.SqlCeCommand
$command.Connection = $connection
# Create table, check if primary key is automatically unique
$table = "CREATE TABLE [Files] ([Name] nvarchar(450) PRIMARY KEY)"
$command.CommandText = $table
[void]$command.ExecuteNonQuery()
$command.Dispose()
$connection.Close()
$connection.Dispose()
}
#########################################################################################
$connection = New-Object System.Data.SqlServerCe.SqlCeConnection $connectionString
$connection.Open()
$command = New-Object System.Data.SqlServerCe.SqlCeCommand
$command.Connection = $connection
# delete table
$command.CommandText = "DROP TABLE [Files]"
[void]$command.ExecuteNonQuery()
$command.CommandText = "CREATE TABLE [Files] ([Name] nvarchar(450) PRIMARY KEY)"
[void]$command.ExecuteNonQuery()
$transaction = $connection.BeginTransaction()
Function Get-Filenames ($path) {
Set-Variable -ErrorAction SilentlyContinue -Name files
# Get Directories
try
{
$files = [IO.Directory]::GetFiles($path)
[System.IO.DirectoryInfo]$directoryInfo = New-Object IO.DirectoryInfo($path)
$folders = $directoryInfo.GetDirectories() | Where-Object {$_.Name -ne "`$Recycle.Bin" -and $folder -ne "System Volume Information" }
} catch { $folders = @()}
foreach($filename in $files)
{
$filename = $filename.replace('\\','\')
$filename = $filename.replace("'","''")
$command.CommandText = "insert into files values ('$filename')"
[void]$command.ExecuteNonQuery()
}
# Create list of non-indexed directories
$exculde = @($env:APPDATA)
$exclude += $env:LOCALAPPDATA
$exclude += $env:ProgramData
$exclude += $env:TMP
$exclude += $env:TEMP
try {
foreach($folder in $folders)
{
if ($exclude -notcontains "$path$folder") { Get-Filenames("$path\$folder")}
}
} catch {}
Remove-Variable -ErrorAction SilentlyContinue -Name files
}
Measure-command { Get-Filenames("C:\") }
$transaction.Commit()
$command.Dispose()
$connection.Close()
$connection.Dispose()
<#
$connection = New-Object System.Data.SqlServerCe.SqlCeConnection $connectionString
$connection.Open()
$command = New-Object System.Data.SqlServerCe.SqlCeCommand
$command.Connection = $connection
Measure-Command {
$file = "SqlServerCe"
$sql = "select name from files where name like '%$file%'"
$command.CommandText = $sql
$datatable = New-Object System.Data.DataTable
$datatable.load($command.ExecuteReader())
}
$command.Dispose()
$connection.Close()
$connection.Dispose()
#>
|
PowerShellCorpus/GithubGist/michl86_6130656_raw_caf37a27fa91e6c1144e499aadfa58d1e17c216a_GetDiskDriveOfFolder.ps1
|
michl86_6130656_raw_caf37a27fa91e6c1144e499aadfa58d1e17c216a_GetDiskDriveOfFolder.ps1
|
function GetDiskDriveOfFolder
{
Param (
[string]$path=$(throw("You must specify a filename to get the diskdrive information of."))
)
$diskdrive = gwmi win32_diskdrive
foreach($drive in $diskdrive){
$partitions = gwmi -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($drive.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"
foreach($part in $partitions) {
$vols = gwmi -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($part.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"
foreach($vol in $vols) {
if($path -Like "$($vol.name)*") {
return $drive
}
}
}
}
}
GetDiskDriveOfFolder E:\temp | select Model, SerialNumber
|
PowerShellCorpus/GithubGist/mlinnell_8201937_raw_2f0a8c92ab6b3bfdd814c0962c6e355c43f36c35_Create-WebConfigTransform.ps1
|
mlinnell_8201937_raw_2f0a8c92ab6b3bfdd814c0962c6e355c43f36c35_Create-WebConfigTransform.ps1
|
<#
.SYNOPSIS
Create a configuration transformation
.DESCRIPTION
This script runs an ASP.NET configuration transformation, given a source
configuration and transformation file. MSBuild.exe is assumed to be in
the path, and Visual Studio 2012 should be installed. Modify the path to
Microsoft.Web.Publishing.Tasks.dll if a different version of Visual Studio
is installed. From https://gist.github.com/mpicker0/5680072/.
.PARAMETER SourceFile
The source file to use for transformations
.PARAMETER TransformFile
The transformations to apply to the source file
.PARAMETER OutputFile
Where to write the resulting output
.EXAMPLE
Create-WebConfigTransform -SourceFile C:\path\to\project\Web.config -TransformFile C:\path\to\project\Web.Debug.config -OutputFile c:\temp\transformed.xml
.LINK
http://msdn.microsoft.com/en-us/library/dd465326.aspx
#>
param(
[Parameter(Mandatory=$true)]
[string]$SourceFile,
[Parameter(Mandatory=$true)]
[string]$TransformFile,
[Parameter(Mandatory=$true)]
[string]$OutputFile
)
# Find MSBuild so we can use it to do the transform
$dotNetVersion = "4.0"
$regKey = "HKLM:\software\Microsoft\MSBuild\ToolsVersions\$dotNetVersion"
$regProperty = "MSBuildToolsPath"
$msbuildExe = join-path -path (Get-ItemProperty $regKey).$regProperty -childpath "msbuild.exe"
# set up output filenames
$WorkDir = Join-Path ${env:temp} "work-${PID}"
$SourceWork = Join-Path $WorkDir (Split-Path $SourceFile -Leaf)
$TransformWork = Join-Path $WorkDir (Split-Path $TransformFile -Leaf)
$OutputWork = Join-Path $WorkDir (Split-Path $OutputFile -Leaf)
# create a working directory and copy files into place
New-Item -Path ${WorkDir} -Type Directory
Copy-Item $SourceFile $WorkDir
Copy-Item $TransformFile $WorkDir
# write the project build file
$BuildXml = @"
<Project ToolsVersion="4.0" DefaultTargets="TransformWebConfig" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="TransformXml"
AssemblyFile="`$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
<Target Name="TransformWebConfig">
<TransformXml Source="${SourceWork}"
Transform="${TransformWork}"
Destination="${OutputWork}"
StackTrace="true" />
</Target>
</Project>
"@
$BuildXmlWork = Join-Path $WorkDir "build.xml"
$BuildXml | Out-File $BuildXmlWork
# call msbuild
&$msbuildExe $BuildXmlWork
# copy the output to the desired location
Copy-Item $OutputWork $OutputFile
# clean up
Remove-Item $WorkDir -Recurse -Force
|
PowerShellCorpus/GithubGist/mscharley_32c387264b5ae24a4522_raw_ce2c2c37c19d3991b616c7d983e9fd7c89bbac37_skype.ps1
|
mscharley_32c387264b5ae24a4522_raw_ce2c2c37c19d3991b616c7d983e9fd7c89bbac37_skype.ps1
|
$skypePath = (Get-ItemProperty -Path hkcu:\SOFTWARE\Skype\Phone).SkypePath
if (!(Test-Path $skypePath -pathType leaf)) {
Write-Host "Unable to find Skype for Desktop. Is it installed correctly?"
pause
exit 1
}
$dataPath = "$($env:localappdata)\SkypePortable"
$instanceCount = 2
for ($i = 1; $i -le $instanceCount; $i++) {
$instanceData = "$($dataPath)\Skype.$($i)"
if (!(Test-Path $instanceData -pathType container)) {
Write-Host "Creating: $instanceData"
New-Item $instanceData -force -itemtype directory
}
Write-Host "Running Skype instance $i. Data directory: $instanceData"
& $skypePath /datapath:"$($instanceData)" /removable /secondary
sleep 5
}
$null
|
PowerShellCorpus/GithubGist/jchadwick_1082558_raw_5ae7b268c2ccefdb45bdb3c0e7f2aeb46dfe3903_Upgrade-Package.ps1
|
jchadwick_1082558_raw_5ae7b268c2ccefdb45bdb3c0e7f2aeb46dfe3903_Upgrade-Package.ps1
|
###########################################################
#
# Script to upgrade all NuGet packages in solution to latest version
# https://gist.github.com/1082558
#
# USAGE
# Place this file (Upgrade-Packages.ps1) to your solution folder.
# From Package Manager Console execute
#
# .\Upgrade-Packages.ps1 -PackageFilter:Castle.*
# or
# .\Upgrade-Packages.ps1 Castle.*
# or just
# .\Upgrade-Packages.ps1
# to upgrade all NuGet packages in the solution
#
##########################################################
param($PackageFilter = "*")
$packageManager = $host.PrivateData.packageManagerFactory.CreatePackageManager()
foreach ($project in Get-Project -all) {
$fileSystem = New-Object NuGet.PhysicalFileSystem($project.Properties.Item("FullPath").Value)
$repo = New-Object NuGet.PackageReferenceRepository($fileSystem, $packageManager.LocalRepository)
foreach ($package in $repo.GetPackages() | ? {$_.Id -like $PackageFilter}) {
Update-Package $package.Id -Project:$project.Name
}
}
|
PowerShellCorpus/GithubGist/taesiri_9648811_raw_2d437328f02d36c977f0ad02c94438e89099efd9_gistfile1.ps1
|
taesiri_9648811_raw_2d437328f02d36c977f0ad02c94438e89099efd9_gistfile1.ps1
|
write-host("Ad-Hoc Creator")
write-host("Please enter an SSID") -foreground "green"
$network_name = Read-Host
write-host("Please enter a Password") -foreground "green"
$network_pass = Read-Host
write-host "Stopping current hosted network ..." -foreground "yellow"
netsh wlan stop hostednetwork
write-host "Creating new network ..."-foreground "green"
netsh wlan set hostednetwork mode=allow ssid=$network_name key=$network_pass
write-host("Starting network ...") -foreground "green"
netsh wlan start hostednetwork
|
PowerShellCorpus/GithubGist/thorade_e4dec248c95d49d40fcd_raw_b25d6ef4535b415ceb058ccf8d2b8f37dab5d92a_findFileExtensions.ps1
|
thorade_e4dec248c95d49d40fcd_raw_b25d6ef4535b415ceb058ccf8d2b8f37dab5d92a_findFileExtensions.ps1
|
# This PowerShell Script will recursively scan all files in the given $scanDir
# and print a list of all file extensions it finds
#
# get current directory
$curPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$curDir = Split-Path -Leaf -Path $curPath
$scanDir = "BuildingSystems"
$scanPath = $curPath + "\" + $scanDir
$outFile = $scanPath + "\fileExtensions.txt"
# print the list of file extensions
Get-ChildItem $scanPath -recurse | Select-Object Extension | Sort-Object Extension | Get-Unique -asString | Out-File $outFile
#Read-Host "Press Enter to close"
|
PowerShellCorpus/GithubGist/alexisnomine_9408777_raw_06f285aaaf0c9415203b27a97832e574c84b49fb_DocxToPdf.ps1
|
alexisnomine_9408777_raw_06f285aaaf0c9415203b27a97832e574c84b49fb_DocxToPdf.ps1
|
Param(
[Parameter(Mandatory=$True)]
[string]$FilePath
)
$Files = Get-ChildItem "$FilePath\*.docx"
$Word = New-Object -ComObject Word.Application
Foreach ($File in $Files) {
# open a Word document, filename from the directory
$Doc = $Word.Documents.Open($File.FullName)
# Swap out DOCX with PDF in the Filename
$Name=($Doc.FullName).Replace("docx","pdf")
# Save this File as a PDF in Word 2010/2013
$Doc.SaveAs([ref] $Name, [ref] 17)
$Doc.Close()
}
|
PowerShellCorpus/GithubGist/pjmagee_11374776_raw_7502b7fb822a2d69082b508cb699df02ed0a060c_gistfile1.ps1
|
pjmagee_11374776_raw_7502b7fb822a2d69082b508cb699df02ed0a060c_gistfile1.ps1
|
# Restore a Database backup to the given database name
# providing the SQL .bak file to use.
# Author: Patrick Magee
# TODO: Load password from external source.
Import-Module sqlps -Verbose
$databaseName = "SQL_DATABASE_NAME" # Local UAT Database Backup Name
$backupFile = "SQL_BACKUP_FILE.bak" # The file
$sqlInstance = "SQL_INSTANCE_NAME"
$username = "SQL_USERNAME"
$password = "SQL_PASSWORD"
$securePassword = $password | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePassword
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$sqlServer = New-Object Microsoft.SqlServer.Management.Smo.Server $env:COMPUTERNAME
$sqlServer.KillAllProcesses($databaseName)
$sqlQuery = "USE [master]; ALTER DATABASE [$databaseName] SET OFFLINE WITH ROLLBACK IMMEDIATE; ALTER DATABASE [$databaseName] SET ONLINE"
Invoke-Sqlcmd -Username $username -Password $password `
-ServerInstance $serverInstance `
-Query $sqlQuery `
write "Restoring $databaseName with backup: $backupFile "
write $credential
$serverInstance = "$env:COMPUTERNAME\$sqlInstance"
Restore-SqlDatabase -ServerInstance $serverInstance `
-Database $databaseName `
-BackupFile $backupFile `
-Credential $credential `
-Confirm
write "Done restoring $databaseName."
|
PowerShellCorpus/GithubGist/ao-zkn_67d0b6d831be22efc996_raw_c7d6a8d983929942456b00376ec4552eac96ef28_Write-Log.ps1
|
ao-zkn_67d0b6d831be22efc996_raw_c7d6a8d983929942456b00376ec4552eac96ef28_Write-Log.ps1
|
# ------------------------------------------------------------------
# デバッグログをファイルに出力する
# 関数名:Write-DebugLog
# 引数 :Value ログとして出力する文字列
# 戻り値:なし
# ------------------------------------------------------------------
function Write-DebugLog([String]$VALUE){
if($LogLevel-le 0){
Out-LogFile -LogFilePath $LogFilePath -Value $Value -LogType 0 -LogEncoding $LogEncoding
}
}
# ------------------------------------------------------------------
# 情報ログをファイルに出力する
# 関数名:Write-InfoLog
# 引数 :Value ログとして出力する文字列
# 戻り値:なし
# ------------------------------------------------------------------
function Write-InfoLog([String]$VALUE){
if($LogLevel -le 1){
Out-LogFile -LogFilePath $LogFilePath -Value $Value -LogType 1 -LogEncoding $LogEncoding
}
}
# ------------------------------------------------------------------
# 警告ログをファイルに出力する
# 関数名:Write-WarnLog
# 引数 :Value ログとして出力する文字列
# 戻り値:なし
# ------------------------------------------------------------------
function Write-WarnLog([String]$VALUE){
if($LogLevel -le 2){
Out-LogFile -LogFilePath $LogFilePath -Value $Value -LogType 2 -LogEncoding $LogEncoding
}
}
# ------------------------------------------------------------------
# エラーログをファイルに出力する
# 関数名:Write-ErrorLog
# 引数 :Value ログとして出力する文字列
# 戻り値:なし
# ------------------------------------------------------------------
function Write-ErrorLog([String]$VALUE){
if($LogLevel -le 3){
Out-LogFile -LogFilePath $LogFilePath -Value $Value -LogType 3 -LogEncoding $LogEncoding
}
}
|
PowerShellCorpus/GithubGist/edeustace_2700126_raw_b21cf0119424d44acfc0882c2562ec9ed552f440_download_zip.ps1
|
edeustace_2700126_raw_b21cf0119424d44acfc0882c2562ec9ed552f440_download_zip.ps1
|
# copy items
# if you have a zip here: http://myserver.com/my.zip and it contains myFile.txt and myFolder/myOtherFile.txt
# you can call this script like so:
# .\download_zip.ps1 http://myserver.com/my.zip "myFile.txt|c:\myFileDestination\myFileHere.txt" "myFolder/myOtherFile.txt|c:\myOtherDestination\myOtherFile.txt"
#
"download script -----------------------------------------"
"------"
"Downloads from the given url, unzips it then for each string arg, copies the file to the destination"
"params : zip.url 'name|destination[, name|destination...]'"
$index = 0
$url = $args[0]
"url: $url"
$pwd = "$(get-location)"
if( !(test-path "$pwd\download") )
{
mkdir -p "$pwd\download"
}
if( !(test-path "$pwd\download\expanded") )
{
mkdir -p "$pwd\download\expanded"
}
$save_path = "$pwd\download\mobius.zip"
$expand_path = "$pwd\download\expanded"
"Downloading [$url]`n"
$client = new-object System.Net.WebClient
$client.DownloadFile( $url, $save_path )
"Download complete.."
$shell_app=new-object -com shell.application
"Unzipping`n"
$zip_file = $shell_app.namespace($save_path)
$destination = $shell_app.namespace($expand_path)
#0x14 forces an overwrite
$destination.Copyhere($zip_file.items(), 0x14)
foreach( $arg in $args ){
if( $index -ne 0 )
{
$split = $arg.split("|")
$file_to_copy = $split[0]
$destination = $split[1]
$destination -match "(.*)\\(.*)"
$final_folder = $matches[1]
$final_name = $matches[2]
if( $file_to_copy -match "(.*)\\(.*)" )
{
$filename_to_rename = $matches[2]
}
else
{
$filename_to_rename = $file_to_copy
}
""
"$file_to_copy ->>>- $destination"
"final_folder: $final_folder"
"final_name: $final_name"
"file_to_copy: $file_to_copy"
"file_to_rename: $filename_to_rename"
Copy-Item "$expand_path\$file_to_copy" "$final_folder" -force
Move-Item "$final_folder\$filename_to_rename" "$final_folder\$final_name" -force
}
$index++
}
|
PowerShellCorpus/GithubGist/astaykov_02540f3e0d9e19a016ee_raw_3d3e452edfa771f5ffc7d5f163a6fa62dc5b9f54_AzureResetVMAdminPassword.ps1
|
astaykov_02540f3e0d9e19a016ee_raw_3d3e452edfa771f5ffc7d5f163a6fa62dc5b9f54_AzureResetVMAdminPassword.ps1
|
$cred = Get-Credential -UserName "user@domain.com" -Message "Enter your OrgID to manage Azure"
Add-AzureAccount -Credential $cred
Select-AzureSubscription -SubscriptionName "<Put actual subscription name here>"
$adminCredentials = Get-Credential -Message "Enter new Admin credentials"
$VM = Get-AzureVM -Name "<put azure VM name here>" -ServiceName "<put service name (subdomain) here>"
If ($VM.VM.ProvisionGuestAgent) {
Set-AzureVMAccessExtension -VM $VM `
-UserName $adminCredentials.UserName `
-Password $adminCredentials.GetNetworkCredential().Password `
-ReferenceName "VMAccessAgent" |
Update-AzureVM
Restart-AzureVM -ServiceName $VM.ServiceName -Name $VM.Name
}
|
PowerShellCorpus/GithubGist/chrisobriensp_7796641_raw_8ad58d1e4762d2e3923b8f06f3d18f275d5b33da_PS_SPO_ListSiteCollections.ps1
|
chrisobriensp_7796641_raw_8ad58d1e4762d2e3923b8f06f3d18f275d5b33da_PS_SPO_ListSiteCollections.ps1
|
. .\PS_SPO_TopOfScript.ps1
Get-SPOSite -Limit All
|
PowerShellCorpus/GithubGist/inoues_9654742_raw_266daf47b9b6662f98cfb8b9c13d0fcf99605696_ping_chek.ps1
|
inoues_9654742_raw_266daf47b9b6662f98cfb8b9c13d0fcf99605696_ping_chek.ps1
|
# 対象機器のIPアドレスを格納した配列
# 名前とIPは同じ順番で入れてね
[String[]]$addressAp = @('localhost')
[String[]]$userName = @('OWN')
#ファイル名の指定
[string]$HtmlFileName = [Environment]::GetFolderPath('Desktop') + '\pingResult.html'
# HTMLファイルの上部
[string]$htmlhead = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>pingResult</title>
</head>
<body>
<table border=4 width=400 align=center>
<caption>【pingResult】</caption>
<tr bgcolor="#cccccc">
<th>server</th>
<th>status</th>
</tr>
"@
# HTMLファイルの下部
[string]$htmlbottom = @"
</body>
</html>
"@
[string]$ResultStr = ''
$ResultStr += $htmlhead
# 実行結果を確認します。
for($i = 0; $i -lt $addressAp.Count; $i++) {
# Pingを実行します。
$pingAlive = @(Test-Connection -ComputerName $addressAp[$i] -Quiet)
$ResultStr += '<tr>'
$ResultStr += '<td align=left>' + $userName[$i] + '</td>'
# Ping成功の場合
if ($pingAlive -eq $True) {
$ResultStr += '<td>Living</td>'
} else {
# Ping失敗の場合
$ResultStr += '<td bgcolor="#ff0000">Dead!</td>'
}
# 行を閉じる
$ResultStr += '</tr>'
}
#テーブルを閉じる
$ResultStr += '</table>'
#実行日付取得
$ResultStr += (Get-Date -format g )
# HTMLを閉じる
$ResultStr += $htmlbottom
#実行結果をファイルに出力
Write-Output $ResultStr | Out-file $HtmlFileName
|
PowerShellCorpus/GithubGist/seperman_7924128_raw_e4567b3b3dc54352513334266f9f1edf395e85a2_New-CommandWrapper.ps1
|
seperman_7924128_raw_e4567b3b3dc54352513334266f9f1edf395e85a2_New-CommandWrapper.ps1
|
##############################################################################
##
## New-CommandWrapper
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Adds parameters and functionality to existing cmdlets and functions.
.EXAMPLE
New-CommandWrapper Get-Process `
-AddParameter @{
SortBy = {
$newPipeline = {
__ORIGINAL_COMMAND__ | Sort-Object -Property $SortBy
}
}
}
This example adds a 'SortBy' parameter to Get-Process. It accomplishes
this by adding a Sort-Object command to the pipeline.
.EXAMPLE
$parameterAttributes = @'
[Parameter(Mandatory = $true)]
[ValidateRange(50,75)]
[Int]
'@
New-CommandWrapper Clear-Host `
-AddParameter @{
@{
Name = 'MyMandatoryInt';
Attributes = $parameterAttributes
} = {
Write-Host $MyMandatoryInt
Read-Host "Press ENTER"
}
}
This example adds a new mandatory 'MyMandatoryInt' parameter to
Clear-Host. This parameter is also validated to fall within the range
of 50 to 75. It doesn't alter the pipeline, but does display some
information on the screen before processing the original pipeline.
#>
param(
## The name of the command to extend
[Parameter(Mandatory = $true)]
$Name,
## Script to invoke before the command begins
[ScriptBlock] $Begin,
## Script to invoke for each input element
[ScriptBlock] $Process,
## Script to invoke at the end of the command
[ScriptBlock] $End,
## Parameters to add, and their functionality.
##
## The Key of the hashtable can be either a simple parameter name,
## or a more advanced parameter description.
##
## If you want to add additional parameter validation (such as a
## parameter type,) then the key can itself be a hashtable with the keys
## 'Name' and 'Attributes'. 'Attributes' is the text you would use when
## defining this parameter as part of a function.
##
## The Value of each hashtable entry is a scriptblock to invoke
## when this parameter is selected. To customize the pipeline,
## assign a new scriptblock to the $newPipeline variable. Use the
## special text, __ORIGINAL_COMMAND__, to represent the original
## command. The $targetParameters variable represents a hashtable
## containing the parameters that will be passed to the original
## command.
[HashTable] $AddParameter
)
Set-StrictMode -Version Latest
## Store the target command we are wrapping, and its command type
$target = $Name
$commandType = "Cmdlet"
## If a function already exists with this name (perhaps it's already been
## wrapped,) rename the other function and chain to its new name.
if(Test-Path function:\$Name)
{
$target = "$Name" + "-" + [Guid]::NewGuid().ToString().Replace("-","")
Rename-Item function:\GLOBAL:$Name GLOBAL:$target
$commandType = "Function"
}
## The template we use for generating a command proxy
$proxy = @'
__CMDLET_BINDING_ATTRIBUTE__
param(
__PARAMETERS__
)
begin
{
try {
__CUSTOM_BEGIN__
## Access the REAL Foreach-Object command, so that command
## wrappers do not interfere with this script
$foreachObject = $executionContext.InvokeCommand.GetCmdlet(
"Microsoft.PowerShell.Core\Foreach-Object")
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(
'__COMMAND_NAME__',
[System.Management.Automation.CommandTypes]::__COMMAND_TYPE__)
## TargetParameters represents the hashtable of parameters that
## we will pass along to the wrapped command
$targetParameters = @{}
$PSBoundParameters.GetEnumerator() |
& $foreachObject {
if($command.Parameters.ContainsKey($_.Key))
{
$targetParameters.Add($_.Key, $_.Value)
}
}
## finalPipeline represents the pipeline we wil ultimately run
$newPipeline = { & $wrappedCmd @targetParameters }
$finalPipeline = $newPipeline.ToString()
__CUSTOM_PARAMETER_PROCESSING__
$steppablePipeline = [ScriptBlock]::Create(
$finalPipeline).GetSteppablePipeline()
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
__CUSTOM_PROCESS__
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
__CUSTOM_END__
$steppablePipeline.End()
} catch {
throw
}
}
dynamicparam
{
## Access the REAL Get-Command, Foreach-Object, and Where-Object
## commands, so that command wrappers do not interfere with this script
$getCommand = $executionContext.InvokeCommand.GetCmdlet(
"Microsoft.PowerShell.Core\Get-Command")
$foreachObject = $executionContext.InvokeCommand.GetCmdlet(
"Microsoft.PowerShell.Core\Foreach-Object")
$whereObject = $executionContext.InvokeCommand.GetCmdlet(
"Microsoft.PowerShell.Core\Where-Object")
## Find the parameters of the original command, and remove everything
## else from the bound parameter list so we hide parameters the wrapped
## command does not recognize.
$command = & $getCommand __COMMAND_NAME__ -Type __COMMAND_TYPE__
$targetParameters = @{}
$PSBoundParameters.GetEnumerator() |
& $foreachObject {
if($command.Parameters.ContainsKey($_.Key))
{
$targetParameters.Add($_.Key, $_.Value)
}
}
## Get the argumment list as it would be passed to the target command
$argList = @($targetParameters.GetEnumerator() |
Foreach-Object { "-$($_.Key)"; $_.Value })
## Get the dynamic parameters of the wrapped command, based on the
## arguments to this command
$command = $null
try
{
$command = & $getCommand __COMMAND_NAME__ -Type __COMMAND_TYPE__ `
-ArgumentList $argList
}
catch
{
}
$dynamicParams = @($command.Parameters.GetEnumerator() |
& $whereObject { $_.Value.IsDynamic })
## For each of the dynamic parameters, add them to the dynamic
## parameters that we return.
if ($dynamicParams.Length -gt 0)
{
$paramDictionary = `
New-Object Management.Automation.RuntimeDefinedParameterDictionary
foreach ($param in $dynamicParams)
{
$param = $param.Value
$arguments = $param.Name, $param.ParameterType, $param.Attributes
$newParameter = `
New-Object Management.Automation.RuntimeDefinedParameter `
$arguments
$paramDictionary.Add($param.Name, $newParameter)
}
return $paramDictionary
}
}
<#
.ForwardHelpTargetName __COMMAND_NAME__
.ForwardHelpCategory __COMMAND_TYPE__
#>
'@
## Get the information about the original command
$originalCommand = Get-Command $target
$metaData = New-Object System.Management.Automation.CommandMetaData `
$originalCommand
$proxyCommandType = [System.Management.Automation.ProxyCommand]
## Generate the cmdlet binding attribute, and replace information
## about the target
$proxy = $proxy.Replace("__CMDLET_BINDING_ATTRIBUTE__",
$proxyCommandType::GetCmdletBindingAttribute($metaData))
$proxy = $proxy.Replace("__COMMAND_NAME__", $target)
$proxy = $proxy.Replace("__COMMAND_TYPE__", $commandType)
## Stores new text we'll be putting in the param() block
$newParamBlockCode = ""
## Stores new text we'll be putting in the begin block
## (mostly due to parameter processing)
$beginAdditions = ""
## If the user wants to add a parameter
$currentParameter = $originalCommand.Parameters.Count
if($AddParameter)
{
foreach($parameter in $AddParameter.Keys)
{
## Get the code associated with this parameter
$parameterCode = $AddParameter[$parameter]
## If it's an advanced parameter declaration, the hashtable
## holds the validation and / or type restrictions
if($parameter -is [Hashtable])
{
## Add their attributes and other information to
## the variable holding the parameter block additions
if($currentParameter -gt 0)
{
$newParamBlockCode += ","
}
$newParamBlockCode += "`n`n " +
$parameter.Attributes + "`n" +
' $' + $parameter.Name
$parameter = $parameter.Name
}
else
{
## If this is a simple parameter name, add it to the list of
## parameters. The proxy generation APIs will take care of
## adding it to the param() block.
$newParameter =
New-Object System.Management.Automation.ParameterMetadata `
$parameter
$metaData.Parameters.Add($parameter, $newParameter)
}
$parameterCode = $parameterCode.ToString()
## Create the template code that invokes their parameter code if
## the parameter is selected.
$templateCode = @"
if(`$PSBoundParameters['$parameter'])
{
$parameterCode
## Replace the __ORIGINAL_COMMAND__ tag with the code
## that represents the original command
`$alteredPipeline = `$newPipeline.ToString()
`$finalPipeline = `$alteredPipeline.Replace(
'__ORIGINAL_COMMAND__', `$finalPipeline)
}
"@
## Add the template code to the list of changes we're making
## to the begin() section.
$beginAdditions += $templateCode
$currentParameter++
}
}
## Generate the param() block
$parameters = $proxyCommandType::GetParamBlock($metaData)
if($newParamBlockCode) { $parameters += $newParamBlockCode }
$proxy = $proxy.Replace('__PARAMETERS__', $parameters)
## Update the begin, process, and end sections
$proxy = $proxy.Replace('__CUSTOM_BEGIN__', $Begin)
$proxy = $proxy.Replace('__CUSTOM_PARAMETER_PROCESSING__', $beginAdditions)
$proxy = $proxy.Replace('__CUSTOM_PROCESS__', $Process)
$proxy = $proxy.Replace('__CUSTOM_END__', $End)
## Save the function wrapper
Write-Verbose $proxy
Set-Content function:\GLOBAL:$NAME $proxy
## If we were wrapping a cmdlet, hide it so that it doesn't conflict with
## Get-Help and Get-Command
if($commandType -eq "Cmdlet")
{
$originalCommand.Visibility = "Private"
}
|
PowerShellCorpus/GithubGist/ADABman_5178646_raw_9a9cb7ba7b4421478f9fa48e7463e1c0cd626ce5_gistfile1.ps1
|
ADABman_5178646_raw_9a9cb7ba7b4421478f9fa48e7463e1c0cd626ce5_gistfile1.ps1
|
exit
# -------------------------------------------------------
# - 3 NODE HV Failover Cluster with Starwind Native SAN -
# - QOS, BW Management, VLAN -
# - By Brian Millar (adabman at gmail.com) -
# -------------------------------------------------------
# !!! This script is not designed to be run directly. !!!
# !!! This is only a collection of powershell bits to run on each node. !!!
# 3 Servers each with 4 x Onboard 1Gbps Nics, 1 x DualPort 10Gbps Nic
# Diagram Online At: http://www.gliffy.com/go/publish/4404348/
# Code Online At: https://gist.github.com/ADABman/5178646
# Loosly based on information gathered from these sites and others:
# http://www.aidanfinn.com/?p=12609
# http://www.server-log.com/blog/2012/9/10/set-up-a-converged-network-for-windows-server-2012-hyper-v-f.html
# http://www.hyper-v.nu/archives/marcve/2013/01/lbfo-hyper-v-switch-qos-and-actual-performance-part-1/
# http://www.remilner.co.uk/?p=240
# http://marckean.wordpress.com/2012/09/26/windows-server-2012-hyper-v-server-command-line-configuration-2/
# QOS Guidelines:
# http://technet.microsoft.com/en-us/library/jj735302.aspx
# -Keep the sum of the weights near or under 100
# -By weight, which is an integer in the range between 1 and 100
# -Assign a relatively large weight to critical workloads even if they don’t require that percentage of bandwidth
# -Gap the weight assignment to differentiate the level of service to be provided
# -Ensure that traffic that is not specifically filtered out is also accounted for with a weight assignment.
# PowerConnect 2824 Switches, Set port #s for VLAN 10 and 11 to "T". Jumbo Frames currently enabled on switch, not needed.
# -------------------------------------------------------
# -- COMMON CONFIG FOR ALL NODES: --
Add-WindowsFeature Hyper-V,Failover-Clustering,MultiPath-IO –IncludeManagementTools -restart
# Broadcom 10GB Eth drivers at http://www.broadcom.com/support/ethernet_nic/netxtremeii10.php
Get-NetAdapter
Rename-NetAdapter -name "xx" -NewName "OnboardNic1"
Rename-NetAdapter -name "xx" -NewName "10GB-Port0"
New-NetLbfoTeam "ConvergedNetTeam" –TeamMembers "OnboardNic1,OnboardNic2,OnboardNic3,OnboardNic4" `
–TeamNicName "ConvergedNetTeam" -LoadBalancingAlgorithm HyperVPort -TeamingMode SwitchIndependent
New-VMSwitch "ConvergedNetSwitch" -MinimumBandwidthMode weight -NetAdapterName "ConvergedNetTeam" -AllowManagementOS 0
Set-VMSwitch "ConvergedNetSwitch" -DefaultFlowMinimumBandwidthWeight 10
New-VMSwitch "ConvergedStorageNetSwitch1" -MinimumBandwidthMode weight -NetAdapterName "10GB-Port0" -AllowManagementOS 0
Set-VMSwitch "ConvergedStorageNetSwitch1" -DefaultFlowMinimumBandwidthWeight 10
New-VMSwitch "ConvergedStorageNetSwitch2" -MinimumBandwidthMode weight -NetAdapterName "10GB-Port1" -AllowManagementOS 0
Set-VMSwitch "ConvergedStorageNetSwitch2" -DefaultFlowMinimumBandwidthWeight 10
# ADD vNICs
Add-VMNetworkAdapter -ManagementOS -Name "Management" -SwitchName "ConvergedNetSwitch"
Add-VMNetworkAdapter -ManagementOS -Name "Cluster" -SwitchName "ConvergedNetSwitch"
Add-VMNetworkAdapter -ManagementOS -Name "LiveMigration" -SwitchName "ConvergedNetSwitch"
Add-VMNetworkAdapter -ManagementOS -Name "iSCSI1" -SwitchName "ConvergedStorageNetSwitch1"
Add-VMNetworkAdapter -ManagementOS -Name "iSCSI2" -SwitchName "ConvergedStorageNetSwitch2"
Add-VMNetworkAdapter -ManagementOS -Name "SWSync1" -SwitchName "ConvergedStorageNetSwitch1"
Add-VMNetworkAdapter -ManagementOS -Name "SWSync2" -SwitchName "ConvergedStorageNetSwitch2"
#Set Up QOS (Needs Tweaking) - can also be used here: –MaximumBandwidth 1000000000
Set-VMNetworkAdapter -ManagementOS -Name "Management" -MinimumBandwidthWeight 15 -MaximumBandwidth
Set-VMNetworkAdapter -ManagementOS -Name "Cluster" -MinimumBandwidthWeight 35
Set-VMNetworkAdapter -ManagementOS -Name "LiveMigration" -MinimumBandwidthWeight 50
Set-VMNetworkAdapter -ManagementOS -Name "iSCSI1" -MinimumBandwidthWeight 33
Set-VMNetworkAdapter -ManagementOS -Name "iSCSI2" -MinimumBandwidthWeight 33
Set-VMNetworkAdapter -ManagementOS -Name "SWSync1" -MinimumBandwidthWeight 66
Set-VMNetworkAdapter -ManagementOS -Name "SWSync2" -MinimumBandwidthWeight 66
# $Get-VMNetworkAdapter -all -Name * | fl
# Disable ALL vNIC Bindings On iSCSI and SWSync Interfaces
Get-NetAdapter | ? {$_.Name -like "*iSCSI*"} | Disable-NetAdapterBinding -AllBindings
Get-NetAdapter | ? {$_.Name -like "*SWSync*"} | Disable-NetAdapterBinding -AllBindings
# Add IPV4 Binding
Get-NetAdapter | ? {$_.Name -like "*iSCSI*"} | Enable-NetAdapterBinding -ComponentID ms_tcpip
Get-NetAdapter | ? {$_.Name -like "*SWSync*"} | Enable-NetAdapterBinding -ComponentID ms_tcpip
#disable IPv6
Set-NetAdapterBinding -Name "vethernet (Management)" -ComponentID ms_tcpip6 -Enabled $false
Set-NetAdapterBinding -Name "vethernet (Cluster)" -ComponentID ms_tcpip6 -Enabled $false
Set-NetAdapterBinding -Name "vethernet (LiveMigration)" -ComponentID ms_tcpip6 -Enabled $false
#Set-NetAdapterBinding -Name "vethernet (iSCSI1)" -ComponentID ms_tcpip6 -Enabled $false
#Set-NetAdapterBinding -Name "vethernet (iSCSI2)" -ComponentID ms_tcpip6 -Enabled $false
#Set-NetAdapterBinding -Name "vethernet (SWSync1)" -ComponentID ms_tcpip6 -Enabled $false
#Set-NetAdapterBinding -Name "vethernet (SWSync2)" -ComponentID ms_tcpip6 -Enabled $false
# We Only Need Management vNIC Registering With DNS
#Get-DnsClient | ? {$_.InterfaceAlias -like "*Management*"} | Set-DnsClient -RegisterThisConnectionsAddress:$false
Get-DnsClient | ? {$_.InterfaceAlias -like "*Cluster*"} | Set-DnsClient -RegisterThisConnectionsAddress:$false
Get-DnsClient | ? {$_.InterfaceAlias -like "*LiveMigration*"} | Set-DnsClient -RegisterThisConnectionsAddress:$false
Get-DnsClient | ? {$_.InterfaceAlias -like "*iSCSI*"} | Set-DnsClient -RegisterThisConnectionsAddress:$false
Get-DnsClient | ? {$_.InterfaceAlias -like "*SWSync*"} | Set-DnsClient -RegisterThisConnectionsAddress:$false
# Disable NETBIOS On iSCSI and SWSync Interfaces
$adapter=(gwmi -query "select * from win32_networkadapter where netconnectionid= 'vethernet (iSCSI1)'").deviceid
([wmi]"\\.\root\cimv2:Win32_NetworkAdapterConfiguration.Index=$adapter").SetTcpipNetbios(2)
$adapter=(gwmi -query "select * from win32_networkadapter where netconnectionid= 'vethernet (iSCSI2)'").deviceid
([wmi]"\\.\root\cimv2:Win32_NetworkAdapterConfiguration.Index=$adapter").SetTcpipNetbios(2)
$adapter=(gwmi -query "select * from win32_networkadapter where netconnectionid= 'vethernet (SWSync1)'").deviceid
([wmi]"\\.\root\cimv2:Win32_NetworkAdapterConfiguration.Index=$adapter").SetTcpipNetbios(2)
$adapter=(gwmi -query "select * from win32_networkadapter where netconnectionid= 'vethernet (SWSync2)'").deviceid
([wmi]"\\.\root\cimv2:Win32_NetworkAdapterConfiguration.Index=$adapter").SetTcpipNetbios(2)
#Enable Jumbo Frames
Set-NetAdapterAdvancedProperty -Name “vethernet (iSCSI1)” -RegistryKeyword “*JumboPacket” -Registryvalue 9014
Set-NetAdapterAdvancedProperty -Name “vethernet (iSCSI2)” -RegistryKeyword “*JumboPacket” -Registryvalue 9014
Set-NetAdapterAdvancedProperty -Name “vethernet (SWSync1)” -RegistryKeyword “*JumboPacket” -Registryvalue 9014
Set-NetAdapterAdvancedProperty -Name “vethernet (SWSync2)” -RegistryKeyword “*JumboPacket” -Registryvalue 9014
Set-NetAdapterAdvancedProperty -name "10GB-Port0" -RegistryKeyword “*JumboPacket” -Registryvalue 9014
Set-NetAdapterAdvancedProperty -name "10GB-Port1" -RegistryKeyword “*JumboPacket” -Registryvalue 9014
#Node 3 OnboardNics dont support jumbo frames (SHAZBOT!)
#Set-NetAdapterAdvancedProperty -Name “vethernet (Cluster)” -RegistryKeyword “*JumboPacket” -Registryvalue 9014
#Set-NetAdapterAdvancedProperty -Name “vethernet (LiveMigration)” -RegistryKeyword “*JumboPacket” -Registryvalue 9014
#Set-NetAdapterAdvancedProperty -name "OnboardNic1" -RegistryKeyword “*JumboPacket” -Registryvalue 9014
#Set-NetAdapterAdvancedProperty -name "OnboardNic2" -RegistryKeyword “*JumboPacket” -Registryvalue 9014
#Set-NetAdapterAdvancedProperty -name "OnboardNic3" -RegistryKeyword “*JumboPacket” -Registryvalue 9014
#Set-NetAdapterAdvancedProperty -name "OnboardNic4" -RegistryKeyword “*JumboPacket” -Registryvalue 9014
# --- END OF COMMON CONFIG ---
# NODE 1:
# Dell OpenManage
Rename-Computer HV-CCIS-Node1 -Restart
Set-DnsClientServerAddress -InterfaceAlias "vEthernet (Management)" -ServerAddresses "192.168.250.2,192.168.250.3"
New-NetIPAddress -InterfaceAlias "vEthernet (Management)" -IPAddress 192.168.250.101 -PrefixLength 24 -DefaultGateway 192.168.250.1
New-NetIPAddress -InterfaceAlias "vEthernet (Cluster)" -IPAddress 172.16.10.101 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (LiveMigration)" -IPAddress 172.16.11.101 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (iSCSI1)" -IPAddress 172.16.20.101 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (iSCSI2)" -IPAddress 172.16.21.101 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (SWSync1)" -IPAddress 172.16.30.101 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (SWSync2)" -IPAddress 172.16.31.101 -PrefixLength 24
#Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "Management" –Access –VlanId 100
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "Cluster" –Access –VlanId 10
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "LiveMigration" –Access –VlanId 11
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "iSCSI1" –Access –VlanId 20
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "iSCSI2" –Access –VlanId 21
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "SWSync1" –Access –VlanId 30
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "SWSync2" –Access –VlanId 31
# NODE 2:
# Dell OpenManage
Rename-Computer HV-CCIS-Node2 -Restart
Set-DnsClientServerAddress -InterfaceAlias "vEthernet (Management)" -ServerAddresses "192.168.250.2,192.168.250.3"
New-NetIPAddress -InterfaceAlias "vEthernet (Management)" -IPAddress 192.168.250.102 -PrefixLength 24 -DefaultGateway 192.168.250.1
New-NetIPAddress -InterfaceAlias "vEthernet (Cluster)" -IPAddress 172.16.10.102 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (LiveMigration)" -IPAddress 172.16.11.102 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (iSCSI1)" -IPAddress 172.16.21.102 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (iSCSI2)" -IPAddress 172.16.22.102 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (SWSync1)" -IPAddress 172.16.31.102 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (SWSync2)" -IPAddress 172.16.32.102 -PrefixLength 24
#Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "Management" –Access –VlanId 100
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "Cluster" –Access –VlanId 10
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "LiveMigration" –Access –VlanId 11
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "iSCSI1" –Access –VlanId 21
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "iSCSI2" –Access –VlanId 22
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "SWSync1" –Access –VlanId 31
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "SWSync2" –Access –VlanId 32
# NODE 3:
# Adaptec Storage Manager
Rename-Computer HV-CCIS-Node3 -Restart
Set-DnsClientServerAddress -InterfaceAlias "vEthernet (Management)" -ServerAddresses "192.168.250.2,192.168.250.3"
New-NetIPAddress -InterfaceAlias "vEthernet (Management)" -IPAddress 192.168.250.103 -PrefixLength 24 -DefaultGateway 192.168.250.1
New-NetIPAddress -InterfaceAlias "vEthernet (Cluster)" -IPAddress 172.16.10.103 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (LiveMigration)" -IPAddress 172.16.11.103 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (iSCSI1)" -IPAddress 172.16.22.103 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (iSCSI2)" -IPAddress 172.16.20.103 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (SWSync1)" -IPAddress 172.16.32.103 -PrefixLength 24
New-NetIPAddress -InterfaceAlias "vEthernet (SWSync2)" -IPAddress 172.16.30.103 -PrefixLength 24
#Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "Management" –Access –VlanId 100
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "Cluster" –Access –VlanId 10
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "LiveMigration" –Access –VlanId 11
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "iSCSI1" –Access –VlanId 22
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "iSCSI2" –Access –VlanId 20
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "SWSync1" –Access –VlanId 32
Set-VMNetworkAdapterVlan –ManagementOS –VMNetworkAdapterName "SWSync2" –Access –VlanId 30
# --- MORE COMMON CONFIG: ---
# Do Windows Updates, Setup Firewall, Remote Desktop, etc...
add-Computer -DomainName ccis.local -Credential ccis.local\brian -Restart
Set-Service MSISCSI -StartUpType Automatic
Start-Service MSISCSI
Enable-MSDSMAutomaticClaim –BusType ISCSI
Set-MSDSMGlobalDefaultLoadBalancePolicy –Policy RR
Set-MPIOSetting –NewDiskTimeOut 60
# Install Starwind Native SAN
# Edit C:\Program Files\StarWind Software\StarWind\StarWind.cfg
# Find the string "<!--<iScsiDiscoveryListInterfaces value="1"/> -->" and uncomment it, restart service
# (should look as follows: <iScsiDiscoveryListInterfaces value="1"/>).
# Set password on management interface
Restart-Computer -Force
# Create HA Target(s)...
# Node1
New-ISCSITargetPortal -TargetPortalAddress 127.0.0.1
New-ISCSITargetPortal -TargetPortalAddress 172.16.20.103
New-ISCSITargetPortal -TargetPortalAddress 172.16.21.102
# Node2
New-ISCSITargetPortal -TargetPortalAddress 127.0.0.1
New-ISCSITargetPortal -TargetPortalAddress 172.16.21.101
New-ISCSITargetPortal -TargetPortalAddress 172.16.22.103
# Node3
New-ISCSITargetPortal -TargetPortalAddress 127.0.0.1
New-ISCSITargetPortal -TargetPortalAddress 172.16.22.102
New-ISCSITargetPortal -TargetPortalAddress 172.16.20.101
# --- MORE COMMON CONFIG: ---
# BUGGY COMMAND!! .. Do Manually in GUI!! (Witness, Then Storage1, Then Storage2)
# Get-IscsiTarget | Select NodeAddress | Connect-IscsiTarget -IsMultipathEnabled:$true -IsPersistent:$true
# On Node1: Initialise Disks, Bring Disks Online, Format Disks...
# On Node2, Node3 .. Bring Disks Online Q,R,S = Witness, Storage1, Storage2
# Get-Disk
#Initialize-Disk -Number 2 -PartitionStyle MBR
#Initialize-Disk -Number 3 -PartitionStyle MBR
#Initialize-Disk -Number 4 -PartitionStyle MBR
#Set-Disk
#New-Partition -DiskNumber 3 -UseMaximumSize -AssignDriveLetter:$False
#Get-Partition –DiskNumber 3 | Format-Volume
Test-Cluster -Node hv-ccis-node1,hv-ccis-node2,hv-ccis-node3 -Verbose
New-Cluster -Name Cluster-CCIS -StaticAddress 192.168.250.100 -Node hv-ccis-node1,hv-ccis-node2,hv-ccis-node3 -Verbose
# Rename cluster networks...
(Get-ClusterNetwork | where-object {$_.Address -eq "192.168.250.0"}).Name = "Management"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.10.0"}).Name = "Cluster"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.11.0"}).Name = "LiveMigration"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.20.0"}).Name = "iSCSI 1-3"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.21.0"}).Name = "iSCSI 1-2"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.22.0"}).Name = "iSCSI 2-3"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.30.0"}).Name = "SWSync 1-3"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.31.0"}).Name = "SWSync 1-2"
(Get-ClusterNetwork | where-object {$_.Address -eq "172.16.32.0"}).Name = "SWSync 2-3"
# set live migration and cluster networks in failover cluster manager
# set binding,metrics (?)
# Add Disks tTo CSV
# AD Constrained Delegation
# DONE :)
# ------------------------
# Node1:
# Raid-1 C: 135 GB OS
# Raid-5 E: 1350 GB Starwind Files
# Node2:
# Raid-1 C: 135 GB OS
# Raid-5 E: 1350 GB Starwind Files
# Raid-0 ?: 540 GB Scratch Area
# Node3:
# Raid-10 C: 135 GB (LUN1) OS
# Raid-10 E: 1600 GB (LUN1) Starwind Files
# Raid-10 F: 2000 GB (LUN2) DeDuped Backup Storage
# HA (NODE3 marked as non optimized for ALUA)
# ha-witness 1GB 128MB Cache Write-Back
# ha-storage1 500GB 1024MB Cache Write-Back
# ha-storage2 250GB 1024MB Cache Write-Back
# Disable ODX when using SW iSCSI SAN (set value to 1 to disable):
# Set-ItemProperty hklm:\system\currentcontrolset\control\filesystem -Name "FilterSupportedFeaturesMode" -Value 1
# Get-ItemProperty hklm:\system\currentcontrolset\control\filesystem -Name "FilterSupportedFeaturesMode"
# Apply CSV hotfix(!): http://support.microsoft.com/?id=2813630
|
PowerShellCorpus/GithubGist/sureshnath_90174d7506f4332ae4b6_raw_07bf9c46fa09240fd5ff96b6f816359f658b71bd_powershell.ps1
|
sureshnath_90174d7506f4332ae4b6_raw_07bf9c46fa09240fd5ff96b6f816359f658b71bd_powershell.ps1
|
#create directory if not exists
$TARGETDIR = "c:\Temp\test\1\2"
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
#get basename of url
$URL = "http://stackoverflow.com/questions/4546567/get-last-element-of-pipeline-in-powershell"
$NAME = $URL.Split('/') | Select-Object -Last 1
echo $NAME
|
PowerShellCorpus/GithubGist/tsubik_34d2d80e90a924fc718c_raw_b6cc5100323823b82564decb6189b98e2bc2f48c_AddMigration.ps1
|
tsubik_34d2d80e90a924fc718c_raw_b6cc5100323823b82564decb6189b98e2bc2f48c_AddMigration.ps1
|
#Author: Tomasz Subik http://tsubik.com
#Date: 2014-05-27
#License: MIT
Param(
[parameter(Mandatory=$false)]
[alias("n")]
$name = [System.Guid]::NewGuid().ToString(),
[parameter(Mandatory=$false)]
[alias("p")]
$project = "DefaultProjectName",
[parameter(Mandatory=$false)]
[alias("of")]
[switch]$onlyfile = $false
)
Write-Host '######## Generating migration script ##############'
$Project = ($dte.Solution.Projects | where {$_.Name -eq $project})
$ProjItems = $Project.ProjectItems
$ProjDir = [System.IO.Path]::GetDirectoryName($Project.FullName)
$ProjMigrationsUpItems = ((($ProjItems | where {$_.Name -eq "Scripts"}).ProjectItems | where {$_.Name -eq "Migrations"}).ProjectItems | where {$_.Name -eq "up"}).ProjectItems
if(!$onlyfile){
Write-Host "Opening schema compare..."
$scmpFileName = $ProjDir + "\ProjToDbMigrations.scmp"
$dte.ExecuteCommand("File.OpenFile",$scmpFileName )
Write-Host "Comparing items..."
$dte.ExecuteCommand("SQL.SSDTSchemaCompareCompare")
$done = $false
do{
try
{
$dte.ExecuteCommand("SQL.SSDTSchemaCompareGenerateScript")
$done = $true
}
catch
{
#uncomment to se
#$error[0]
Start-Sleep -s 2
}
}
until($done)
Write-Host "Generating comparison script..."
#wait unit generating script finish
do{
Start-Sleep -s 1
}
until($dte.ActiveDocument.FullName.Contains('publish.sql'))
Write-Host "Comparison script generated"
}
$migrationDir = $ProjDir +"\Scripts\Migrations\up"
$scriptFileName = $migrationDir +"\" + [System.DateTime]::Now.ToString("yyyyMMddhhmmss")+"_"+$name+".sql"
if(!$onlyfile)
{
$dte.ActiveDocument.Save($scriptFileName)
}
else{
New-Item $scriptFileName -type file
}
Write-Host "File saved as " + $scriptFileName
$addedScriptProjectItem = $ProjMigrationsUpItems.AddFromFile($scriptFileName)
#0 build action none
$addedScriptProjectItem.Properties.Item("BuildAction").Value = "0"
$dte.ExecuteCommand("File.OpenFile","ProjToDbMigrations.scmp")
$dte.ExecuteCommand("File.Close")
Write-Host '######## Generating migration script ends ##############'
|
PowerShellCorpus/GithubGist/pavelbinar_6640084_raw_914649679a73d4ded888071a3374d45a02c703d3_gistfile1.ps1
|
pavelbinar_6640084_raw_914649679a73d4ded888071a3374d45a02c703d3_gistfile1.ps1
|
# run command and log out and log in
sudo rm -ri ~/.Trash
|
PowerShellCorpus/GithubGist/mhinze_1885377_raw_ae09ab09f2eb01b90d7484d2b536b9909730dd5c_exposeiis.ps1
|
mhinze_1885377_raw_ae09ab09f2eb01b90d7484d2b536b9909730dd5c_exposeiis.ps1
|
function global:ExposeIIS()
{
$config = [xml] ( get-content $env:IIS_USER_HOME/config/applicationhost.config )
# Add in new bindings for computer name
foreach($site in $config.configuration."system.applicationHost".sites.site)
{
foreach($bindings in $site.bindings)
{
# no need to add another binding for machine name if its exists
$hasOneAlready = $false
foreach($existingBinding in $bindings.binding)
{
if($existingBinding.bindingInformation -match $env:computername)
{
$hasOneAlready = $true
}
}
if(!$hasOneAlready)
{
foreach($binding in $bindings.binding)
{
if($binding.bindingInformation -match "localhost")
{
# make new IISExpress binding for local machine name
$namebinding = $binding.Clone()
$namebinding.bindingInformation = $namebinding.bindingInformation.Replace("localhost", $env:computername)
$bindings.AppendChild($namebinding)
# make new IISExpress binding for fully qualified local machine name
$namebinding = $binding.Clone()
$namebinding.bindingInformation = $namebinding.bindingInformation.Replace("localhost", $env:computername + ".company.com")
$bindings.AppendChild($namebinding)
# run netsh to add new binding url
$url = $namebinding.bindingInformation -replace "\*?:([^:]*):([^:]*)", 'http://$2:$1/'
$expression = "netsh http add urlacl url=" + $url + " user=everyone"
invoke-expression $expression
$url = $namebinding.bindingInformation -replace "\*?:([^:]*):([^:]*)", 'http://$2.company.com:$1/'
$expression = "netsh http add urlacl url=" + $url + " user=everyone"
invoke-expression $expression
#TODO: This should be transactional somehow
# Right now failing netsh doesn't stop the bindings from being created
}
}
}
}
}
# TODO: Maybe don't save if there was an error? Have to think about it
$config.Save("$env:IIS_USER_HOME/config/applicationhost.config")
}
function global:SealIIS()
{
$config = [xml] ( get-content $env:IIS_USER_HOME/config/applicationhost.config )
# strip bindings for computer name
foreach($site in $config.configuration."system.applicationHost".sites.site)
{
foreach($bindings in $site.bindings)
{
$i = $bindings.binding.length
for($i-le0;$i--)
{
if($bindings.binding[$i].bindingInformation -match $env:computername)
{
# run netsh to remove binding url
$url = $bindings.binding[$i].bindingInformation -replace "\*?:([^:]*):([^:]*)", 'http://$2:$1/'
$expression = "netsh http delete urlacl url=" + $url
invoke-expression $expression
$url = $bindings.binding[$i].bindingInformation -replace "\*?:([^:]*):([^:]*)", 'http://$2.company.com:$1/'
$expression = "netsh http delete urlacl url=" + $url
invoke-expression $expression
# remove binding from IISExpress
$bindings.RemoveChild($bindings.binding[$i])
#TODO: This should be transactional somehow
# Right now failing netsh doesn't stop the bindings from being removed
}
}
}
}
# TODO: Maybe don't save if there was an error? Have to think about it
$config.Save("$env:IIS_USER_HOME/config/applicationhost.config")
}
|
PowerShellCorpus/GithubGist/dfinke_6951741_raw_58043f68b93f510b353adee20e36113aeec9a554_ExtractSVN.ps1
|
dfinke_6951741_raw_58043f68b93f510b353adee20e36113aeec9a554_ExtractSVN.ps1
|
$svninfo = @{}
svn help |
?{$_ -match "^ "} |
%{($_.trim() -split " ")[0]} |
%{
$command = $_
if(!$svninfo.ContainsKey($command)) {
$svninfo.$command=@{SingleHyphen=@();DoubleHyphen=@()}
}
svn help $_ |
?{$_ -match "^\s+-"} |
%{
$_.Trim() | % {
$parameter = (($_ -split ":")[0] -split ' ')[0]
if($parameter.StartsWith("--")) {
$svninfo.$command.DoubleHyphen+=$parameter -replace '--', ''
} else {
$svninfo.$command.SingleHyphen+=$parameter -replace '-', ''
}
}
}
}
$svninfo
|
PowerShellCorpus/GithubGist/oazabir_8e3187b5756b25b52393_raw_8be1198279e07364c8f72891294a5904df97133f_gistfile1.ps1
|
oazabir_8e3187b5756b25b52393_raw_8be1198279e07364c8f72891294a5904df97133f_gistfile1.ps1
|
# Build, anonymize config, deploy, zip, commit, push in one shot
param (
[string]$solution = "OracleDashboard.sln",
[string]$zipname = "OracleDashboard.zip",
[string]$compressor = "c:\Program Files\7-Zip\7z.exe",
[string]$folder = "OracleDashboard",
[string]$deployPath = "..\Binary",
[string]$commitFrom = "..",
[Parameter(Mandatory=$true)][string]$comment
)
# If visual studio has the solution open, close VS, as we can't delete obj folder while it is open
$windowTitle = $solution.Replace(".sln", "")
$vsProcess = get-process | where {$_.mainwindowtitle -match $windowTitle -and $_.ProcessName -eq "devenv"}
if ($vsProcess.Length -gt 0) {
Write-Host "Visual Studio has this solution open. Closing..."
$vsProcess | ForEach-Object { $_.CloseMainWindow(); }
Sleep 5
Read-Host "Press ENTER to proceed if Visual Studio is closed"
$vsProcess = get-process | where {$_.mainwindowtitle -match $windowTitle -and $_.ProcessName -eq "devenv"}
if ($vsProcess.Length -gt 0) {
Write-Host "Visual Studio still has the solution open. Aborting."
Return
}
}
Push-Location
if (Test-Path $zipname) { rm $zipname; }
# Clean up deploy folder
rm $deployPath\*.* -Force -Recurse
# Build new version
msbuild /verbosity:minimal $solution
# Delete obj
if (Test-Path $folder\obj) { rm $folder\obj -Force -Recurse }
# backup the web.config and remove sensitive entries before pushing to git, eg connectionString
[string]$filename = gi $folder\web.config
[string]$backup = [System.IO.File]::ReadAllText($filename)
$xml = [xml]$backup
$xml.PreserveWhitespace = $true
foreach($n in $xml.configuration.connectionStrings.add)
{
$n.ParentNode.RemoveChild($n);
}
# Anonymize any sensitive appSettings entry
foreach($n in $xml.configuration.appSettings.add)
{
switch($n.key)
{
"Password" { $n.value = "Password" }
}
}
# Remove authorization blocks
$xml.configuration.'system.web'.authorization.RemoveAll()
$xml.Save($filename)
# verify if web.config still contains any sensitive info
[string]$config = gc $folder\web.config
if ( ($config -match 'connectionString="\w+') -or ($config -match 'users="\w+') ) {
Write-Host "Configuration file is not cleaned."
# Restore web.config
[System.IO.File]::WriteAllText($filename, $backup)
Exit
}
# Compress the solution folder and copy to deploy folder
cmd /c $compressor a -tzip $zipname $folder -r
cmd /c copy $zipname $deployPath /Y
cmd /c del $zipname
# Commit and push to GitHub
cd $commitFrom
git pull
git add -A *.*
git commit -a -m $comment
git push
Pop-Location
# Restore web.config
[System.IO.File]::WriteAllText($filename, $backup)
|
PowerShellCorpus/GithubGist/aaronpowell_1064060_raw_cb7101937dfd90400221d3288882a735d2d40bc6_Delete-Assemblies.ps1
|
aaronpowell_1064060_raw_cb7101937dfd90400221d3288882a735d2d40bc6_Delete-Assemblies.ps1
|
Get-ChildItem src -recurse -include *.dll | foreach ($_) {
if($_.fullname.Contains("bin\")) {
remove-item $_.fullname
}
}
|
PowerShellCorpus/GithubGist/xcud_4710032_raw_42870620eaf8727c97d4efb62fe387117a855a24_Get-NetworkStatistics.ps1
|
xcud_4710032_raw_42870620eaf8727c97d4efb62fe387117a855a24_Get-NetworkStatistics.ps1
|
<#
.Synopsis
PowerShellized netstat. Building on Shay Levy's work
Shay Levy's Blog => http://blogs.microsoft.co.il/blogs/scriptfanatic/
.Example
PS> Get-NetworkStatistics skype | ft -AutoSize
Protocol LocalAddress LocalPort RemoteAddress RemotePort State ProcessName PID
-------- ------------ --------- ------------- ---------- ----- ----------- ---
TCP 0.0.0.0 443 0.0.0.0 0 LISTENING Skype 4608
TCP 0.0.0.0 56448 0.0.0.0 0 LISTENING Skype 4608
TCP 10.1.0.13 49255 157.55.235.162 40010 ESTABLISHED Skype 4608
TCP 10.1.0.13 49257 193.120.199.13 12350 ESTABLISHED Skype 4608
TCP 10.1.0.13 49258 65.54.48.131 443 ESTABLISHED Skype 4608
UDP 0.0.0.0 443 * * Skype 4608
UDP 0.0.0.0 56448 * * Skype 4608
UDP 127.0.0.1 56357 * * Skype 4608
UDP 127.0.0.1 62782 * * Skype 4608
.Example
PS> Get-NetworkStatistics -Port 80
Protocol : TCP
LocalAddress : 0.0.0.0
LocalPort : 80
RemoteAddress : 0.0.0.0
RemotePort : 0
State : LISTENING
ProcessName : System
PID : 4
Protocol : TCP
LocalAddress : 10.1.0.13
LocalPort : 50293
RemoteAddress : 69.59.197.29
RemotePort : 80
State : ESTABLISHED
ProcessName : chrome
PID : 3416
#>
function Get-NetworkStatistics
{
param(
[string]$ProcessName,
[net.ipaddress]$Address,
[int]$Port = -1,
[int]$ProcessId = -1
)
$properties = 'Protocol','LocalAddress','LocalPort',
'RemoteAddress','RemotePort','State','ProcessName','PID'
$netstatEntries = netstat -ano | Select-String -Pattern '\s+(TCP|UDP)'
foreach($_ in $netstatEntries) {
$item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::')
{
($localAddress, $localPort) = Split-AddressPort($item[1])
($remoteAddress, $remotePort) = Split-AddressPort($item[2])
$netProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
# apply ProcessName filter
if(![string]::IsNullOrEmpty($ProcessName) -and
[string]::Compare($ProcessName, $netProcessName, $true) -ne 0) {
continue
}
# apply Port filter
if($Port -ne -1 -and $localPort -ne $Port -and $remotePort -ne $Port) {
continue
}
# apply Address filter
if($Address -ne $null -and $localAddress -ne $Address -and $remoteAddress -ne $Address) {
continue
}
# apply PID filter
$netPID = $item[-1]
if($ProcessId -ne -1 -and $ProcessId -ne $netPID) {
continue
}
New-Object PSObject -Property @{
PID = $netPID
ProcessName = $netProcessName
Protocol = $item[0]
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress = $remoteAddress
RemotePort = $remotePort
State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
} | Select-Object -Property $properties
}
}
}
<#
.Synopsis
Splits an ipaddress string from 'netstat' into its respective address/port parts.
.Example
PS> Split-AddressPort [fe80::4442:f854:4707:3c0f%15]:1900
fe80::4442:f854:4707:3c0f%15
1900
#>
function Split-AddressPort([string]$ipaddressAsString) {
$ipaddress = $ipaddressAsString -as [ipaddress]
if ($ipaddress.AddressFamily -eq 'InterNetworkV6')
{
$retvalAddress = $ipaddress.IPAddressToString
$retvalPort = $ipaddressAsString.split('\]:')[-1]
}
else
{
$retvalAddress = $ipaddressAsString.split(':')[0]
$retvalPort = $ipaddressAsString.split(':')[-1]
}
return @($retvalAddress, $retvalPort);
}
|
PowerShellCorpus/GithubGist/piers7_6374578_raw_ba3ce85f97d198b8244623aeeaba2e31e0e2d135_gistfile1.ps1
|
piers7_6374578_raw_ba3ce85f97d198b8244623aeeaba2e31e0e2d135_gistfile1.ps1
|
<#
.Synopsis
Adds/sets environment variables on the local machine for common build dependencies
#>
$ErrorActionPreference = 'stop';
$programFiles32 = $env:ProgramFiles
if (Test-Path environment::"ProgramFiles(x86)") { $programFiles32 = (gi "Env:ProgramFiles(x86)").Value };
# Accumulate the variables that we will be creating
$environmentVars = @{}
# Sniff PowerShell versions
foreach($version in (dir 'REGISTRY::\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell' |
Select-Object -ExpandProperty:PSChildName |
? { $_ -match '^[\d\.]+$'}
)){
$environmentVars["PowerShellV$version"] = $true;
}
# Sniff things based on paths
# (registry keys, file system, anything really)
# 'Property' is optional
$pathChecks = @(
@{
# Sniff out local SQL versions installed
Name = 'SqlSMO';
Path = 'REGISTRY::\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\SharedManagementObjects\CurrentVersion';
Property = 'Version';
}
,@{
Name = 'Ssis2012Runtime';
Path = 'REGISTRY::\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\110\SSIS\Setup\DTSPath';
Property = '(Default)';
}
,@{
Name = 'Sql2012Tools';
Path = 'REGISTRY::\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\110\Tools\ClientSetup';
Property = 'Path';
}
,@{
Path = "$programFiles32\MSBuild\Microsoft\VisualStudio\v10.0\SSDT";
Name = 'VS2010_SsdtTargets';
}
,@{
Path = "$programFiles32\MSBuild\Microsoft\VisualStudio\v11.0\SSDT";
Name = 'VS2012_SsdtTargets';
}
)
foreach($check in $pathChecks){
if(Test-Path $check.Path){
if($check.Property){
$value = (Get-ItemProperty -Path:$check.Path -Name:$check.Property)."$($check.Property)";
}else{
$value = $true;
}
$environmentVars[$check.Name] = $value;
}
}
# Finally, setup environment variables to match
# These are set as system-wide, so will affect all new processed spawned
# ...and this one (this agent)
foreach($key in $environmentVars.GetEnumerator()){
Write-Host ("Set {0}={1}" -f $key.Name,$key.Value)
[System.Environment]::SetEnvironmentVariable($key.Name,$key.Value,'Machine')
}
|
PowerShellCorpus/GithubGist/ajkerrigan_9394792_raw_14023527bc729379b9f9cb323bc59a3045628d9c_FreshPGitSymlink.ps1
|
ajkerrigan_9394792_raw_14023527bc729379b9f9cb323bc59a3045628d9c_FreshPGitSymlink.ps1
|
# Anytime GitHub for Windows updates itself, the PortableGit pathname changes.
# Powershell and GitHub for Windows handle this just fine, but explicit links
# to the PortableGit installation will fail (for instance, Git binary paths
# in Sublime Text packages). This little bit of code in a Powershell profile
# will ensure that a symbolic link always points to the most recent PortableGit
# installation.
$linkDir = 'c:\util\pgit'
# Get-ReparsePoint requires the Powershell Community Extensions (Pscx) module.
$currentSymlinkTarget = (Get-ReparsePoint $linkDir).Target
# Since GitHub for Windows installs PortableGit into a path with a trailing
# GUID, just find the most recent PortableGit directory.
$latestGitDir = (ls $env:LOCALAPPDATA\GitHub\PortableGit_* |
Sort-Object -Property LastWriteTime -Descending)[0].FullName
# If the most recent PortableGit path doesn't match our existing symlink target,
# kill the old link and create a new one.
if ($currentSymlinkTarget -ne $latestGitDir) {
"Updating PortableGit symlink '$linkDir' to '$latestGitDir'..."
cmd /c "rmdir `"$linkDir`""
cmd /c "mklink /d `"$linkDir`" `"$latestGitDir`""
}
|
PowerShellCorpus/GithubGist/cointoss1973_115b1f3793bba6afeec9_raw_11efac964b09e38b4502a3ef8a5e120a30291b8e_FizzBuzz.ps1
|
cointoss1973_115b1f3793bba6afeec9_raw_11efac964b09e38b4502a3ef8a5e120a30291b8e_FizzBuzz.ps1
|
#
# FizzBuzz.ps1
#
Function Get-FizzBuzz($num)
{
$Fizz = $num % 3
$Buzz = $num % 5
if ($Fizz -eq 0 -and $Buzz -eq 0) {
return "Fizz Buzz"
} elseif ( $Fizz -eq 0) {
return "Fizz"
} elseif ( $Buzz -eq 0) {
return "Buzz"
}
return $num
}
@(1..100) | % { Get-FizzBuzz $_ | Write-Host }
|
PowerShellCorpus/GithubGist/mbergal_7574cc35eccb3b6fb762_raw_b908332044e19dfb4a633a3e9303545d4741c145_capture.ps1
|
mbergal_7574cc35eccb3b6fb762_raw_b908332044e19dfb4a633a3e9303545d4741c145_capture.ps1
|
$clipboardImage = [System.Windows.Forms.Clipboard]::GetImage()
$saveDirectory = 'c:\temp\captured'
if ( $clipboardImage -ne $null )
{
$existingImages = @()
$existingImages = ls 'c:\temp\captured'
if ( $existingImages.Length -eq 0 )
{
$nextNumber = 1
}
else
{
$names = $existingImages | %{ [int]::Parse( [System.IO.Path]::GetFileNameWithoutExtension( $_ ) ) }
$lastNumber = $names | Sort-Object | Select-Object -Last 1
$nextNumber = $lastNumber + 1
}
$fileName = Join-Path $saveDirectory ( '' + $nextNumber + '.png' )
Set-Content $fileName 'content'
Write-Host $fileName
[System.Windows.Forms.Clipboard]::SetText( @"
{expand:title=see more}
!$nextNumber.png|thumbnail!
{expand}
"@ )
}
else
{
Write-Host "No image in clipboard."
}
|
PowerShellCorpus/GithubGist/FrankDeGroot_6683854_raw_e5b6bfcf75a2307cdbb4ed2e9650a2770aa3f93d_comparelogs.ps1
|
FrankDeGroot_6683854_raw_e5b6bfcf75a2307cdbb4ed2e9650a2770aa3f93d_comparelogs.ps1
|
filter Get-LastChildItem { Join-Path $_ (gci $_ -Name | sort | select -Last 1) }
$Outs = 'C:\(ProductName)\Branch\99 - bin\Deliverables\Name\Log\Compile\Compile_result.xml',
"$('\\portal\DailyBuildResult\ProductName\Branch' | Get-LastChildItem | Get-LastChildItem)\CIName\Compile\compile.log" | % {
([xml](gc $_)).results.message |
where {$_.type -eq 'warning'} |
sort -CaseSensitive '#text' |
% {"<message>$($_.'#text')</message>"} |
Out-File ($Out = [IO.Path]::GetTempFileName())
$Out
}
start -Wait 'C:\Tools\DiffMerge\sgdm.exe' $Outs
ri $Outs
|
PowerShellCorpus/GithubGist/pedromvgomes_5541933_raw_da55247db69ef1ac2030ecc9641c8ca9cb97cbad_import-jmeterResults.ps1
|
pedromvgomes_5541933_raw_da55247db69ef1ac2030ecc9641c8ca9cb97cbad_import-jmeterResults.ps1
|
# This PowerShell scripts loads the JMeter results (XML) into a given database table
Param (
$provider,
$connectionString,
$tableName,
$inputFile,
$tag
)
Cls
Write-Host 'JMeter XML Results Importer 1.0'
if ($provider -eq $null -or $connectionString -eq $null -or $tableName -eq $null -or $input -eq $null) {
Write-Host
Write-Host 'Syntax Error' -foregroundcolor Red
Write-Host 'USAGE: import-testresults.ps1 -provider <provider name> -connectionString <connection string> -tableName <table name> -input <file name>.' -foregroundcolor Red
}
# check if input file exists
Write-Progress -id 1 -activity "Importing data" -status "Opening input file" -percentComplete -1
$flag = (Test-Path $inputFile -PathType Leaf)
If (!($flag)) {
Write-Host
Write-Host 'Input file not found.' -foregroundcolor Red
exit
}
Write-Progress -id 1 -activity "Importing data" -status "Opening database connection" -percentComplete -1;
$providerFactory = [System.Data.Common.DbProviderFactories]::GetFactory($provider);
$dbConnection = $providerFactory.CreateConnection()
$dbConnection.ConnectionString = $connectionString
$dbConnection.Open()
$selectCommand = $providerFactory.CreateCommand()
$selectCommand.CommandText = "SELECT RowID, ResultsTag, StartTime, ThreadName, Label, SampleTime, StatusCode, StatusMessage, Bytes, Latency FROM {0}" -f $tableName
$selectCommand.Connection = $dbConnection
$adapter = $providerFactory.CreateDataAdapter()
$adapter.SelectCommand = $selectCommand
$cmdBuilder = $providerFactory.CreateCommandBuilder()
$cmdBuilder.DataAdapter = $adapter
# Get the insert command
$adapter.InsertCommand = $cmdBuilder.GetInsertCommand()
$dataTable = New-Object System.Data.DataTable
$adapter.FillSchema($dataTable, [System.Data.SchemaType]::Mapped);
$dateKindUTC = [System.DateTimeKind]::Utc
$timeStampStart = New-Object -TypeName System.DateTime 1970, 1, 1, 0, 0, 0, 0, $dateKindUTC
#$transaction = $dbConnection.BeginTransaction();
#$adapter.InsertCommand.Transaction = $transaction
$stream = [System.IO.File]::OpenRead($inputFile);
$reader = New-Object System.Xml.XmlTextReader $stream
Write-Progress -id 1 -activity "Importing data" -status "Database data insert" -percentComplete 50
try {
while ($reader.Read()) {
if ($reader.NodeType -eq [System.Xml.XmlNodeType]::Element -and ($reader.LocalName -eq "sample" -or $reader.LocalName -eq "httpSample")) {
$newRow = $dataTable.NewRow()
$newRow.Item("RowID") = [guid]::NewGuid().ToString("N")
$newRow.Item("ResultsTag") = $tag
$newRow.Item("StartTime") = $timeStampStart.AddMilliseconds([long]$reader.GetAttribute("ts"))
$newRow.Item("ThreadName") = $reader.GetAttribute("tn")
$newRow.Item("Label") = $reader.GetAttribute("lb")
$newRow.Item("SampleTime") = [int]$reader.GetAttribute("t")
$newRow.Item("StatusCode") = $reader.GetAttribute("rc")
$newRow.Item("StatusMessage") = $reader.GetAttribute("rm")
$newRow.Item("Bytes") = [int]$reader.GetAttribute("by")
$newRow.Item("Latency") = [int]$reader.GetAttribute("lt")
$dataTable.Rows.Add($newRow)
}
if ($dataTable.Rows.Count -eq 100) {
$insertedRows = $adapter.Update($dataTable)
# free memory
$dataTable.Rows.Clear()
$dataTable.AcceptChanges()
}
$percentComplete = $stream.Position * 100 / $stream.Length
Write-Progress -id 1 -activity "Importing data" -status "Database data insert" -percentComplete $percentComplete
}
$insertedRows = $adapter.Update($dataTable)
#$transaction.Commit()
Write-Progress -id 1 -activity "Importing data" -status "Database data insert" -Completed
}
catch {
#$transaction.Rollback()
write-host ("Exception of type {0} thrown" -f $_.Exception.GetType().FullName) -foregroundcolor Red
write-host $_.Exception.Message -foregroundcolor Red
exit
}
finally {
$stream.Dispose()
$adapter.Dispose()
$dbConnection.Close()
$dbConnection.Dispose()
}
|
PowerShellCorpus/GithubGist/williamjacksn_7266828_raw_e546d17c7d63898210cbabef021f232725227453_email-daily-calendar.ps1
|
williamjacksn_7266828_raw_e546d17c7d63898210cbabef021f232725227453_email-daily-calendar.ps1
|
[CmdletBinding()]
Param(
[Parameter(Mandatory = $True, Position = 1)]
[string]$config_file
)
$config = Get-Content $config_file -Raw | ConvertFrom-Json
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
$exch_ver = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2
$exch_serv = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($exch_ver)
$creds = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($config.credentials.email, $config.credentials.password)
$exch_serv.Credentials = $creds
## Code From http://poshcode.org/624
## Create a compilation environment
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$compiler = $provider.CreateCompiler()
$params = New-Object System.CodeDom.Compiler.CompilerParameters
$params.GenerateExecutable = $False
$params.GenerateInMemory = $True
$params.IncludeDebugInformation = $False
$params.ReferencedAssemblies.Add("System.DLL") | Out-Null
$ta_source=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy
{
public class TrustAll : System.Net.ICertificatePolicy
{
public TrustAll() {}
public bool CheckValidationResult(System.Net.ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
System.Net.WebRequest req, int problem)
{
return true;
}
}
}
'@
$ta_results = $provider.CompileAssemblyFromSource($params, $ta_source)
$ta_assembly = $ta_results.CompiledAssembly
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$trust_all = $ta_assembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy = $trust_all
## end code from http://poshcode.org/624
Try
{
$exch_serv.AutodiscoverUrl($config.credentials.email, {$True})
}
Catch
{
$creds = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($config.credentials.eid, $config.credentials.password, $config.credentials.domain)
$exch_serv.Credentials = $creds
$exch_serv.AutodiscoverUrl($config.credentials.email, {$True})
}
$name_resolutions = $exch_serv.ResolveName($config.from, [Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::DirectoryOnly, $True)
$display_name = $name_resolutions[0].Contact.DisplayName
$email_subject = "Calendar for " + $display_name + " [" + [System.DateTime]::Now.ToLongDateString() + "]"
$email_body = "----------" + [System.Environment]::NewLine + [System.Environment]::NewLine
$fid = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar, $config.from)
$cf = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($exch_serv, $fid)
$cv_today = New-Object Microsoft.Exchange.WebServices.Data.CalendarView([System.DateTime]::Today.AddHours(1), [System.DateTime]::Today.AddHours(23))
$appts_today = $cf.FindAppointments($cv_today)
foreach ($appt in $appts_today)
{
$email_body = $email_body + $appt.Subject + [System.Environment]::NewLine
$email_body = $email_body + "Start: " + $appt.Start + [System.Environment]::NewLine
$email_body = $email_body + "End: " + $appt.End + [System.Environment]::NewLine + [System.Environment]::NewLine
$email_body = $email_body + "----------" + [System.Environment]::NewLine + [System.Environment]::NewLine
}
$email = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($exch_serv)
foreach ($email_to in $config.to)
{
$email.ToRecipients.Add($email_to)
}
foreach ($email_bcc in $config.bcc)
{
$email.BccRecipients.Add($email_bcc)
}
$email.Subject = $email_subject
$email.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody([Microsoft.Exchange.WebServices.Data.BodyType]::Text, $email_body)
$email.Send()
|
PowerShellCorpus/GithubGist/MDendura_7c7c2f8fd7fb3cd51012_raw_b3ff841a4a208ce21702ca856f61b90ba899954b_SurfaceWin10.ps1
|
MDendura_7c7c2f8fd7fb3cd51012_raw_b3ff841a4a208ce21702ca856f61b90ba899954b_SurfaceWin10.ps1
|
#Found from here: http://answers.microsoft.com/en-us/insider/forum/insider_wintp-insider_install/windows-10-on-surface-pro-3/47b58abc-81e1-4dc9-9647-fdcfc7276299
#and here: https://twitter.com/adamucf/status/517478280014753792
#to fix some Surface issues on Windows 10 Technical Preview
$code = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Win8 {
[ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IApplicationActivationManager
{
IntPtr ActivateApplication([In] String appUserModelId, [In] String arguments, [In] UInt32 options, [Out] out UInt32 processId);
}
[ComImport, Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C")]//Application Activation Manager
public class ApplicationActivationManager : IApplicationActivationManager
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)/*, PreserveSig*/]
public extern IntPtr ActivateApplication([In] String appUserModelId, [In] String arguments, [In] UInt32 options, [Out] out UInt32 processId);
}
}
"@
add-type -TypeDefinition $code
$appman = new-object Win8.ApplicationActivationManager
$appman.ActivateApplication("DefaultBrowser_NOPUBLISHERID!Microsoft.InternetExplorer.Default",$null,0,[ref]0)
|
PowerShellCorpus/GithubGist/JamesTryand_4118342_raw_44e4aeb6579fb4028ccb4b44f003c5c0fdc4beff_Get-GroupMailAddresses.ps1
|
JamesTryand_4118342_raw_44e4aeb6579fb4028ccb4b44f003c5c0fdc4beff_Get-GroupMailAddresses.ps1
|
function Get-GroupMailAddresses {
PARAM([string[]]$GroupName)
BEGIN {
$DSGroupNameBasis = { PARAM([string]$Name) PROCESS { "(&(groupType=-2147483646)(name=$Name))" } }
}
PROCESS {
(new-object DirectoryServices.DirectorySearcher( & $DSGroupNameBasis -Name $GroupName )).
FindAll().
Properties['member'] |
% {
([ADSI]"LDAP://$_").mail
}
}
END { }
}
|
PowerShellCorpus/GithubGist/lantrix_62450df9ab94e68d7992_raw_47d6218c61af1487fff52f555f73ecdd956b35e6_create_striped_volume.ps1
|
lantrix_62450df9ab94e68d7992_raw_47d6218c61af1487fff52f555f73ecdd956b35e6_create_striped_volume.ps1
|
#
# Create Striped Volume set from (Available) Raw Disks
#
#settings
$letter = "E" #Drive Letter
$allocation = 65536 #Blocksize in Bytes
$label = "My Disk Label" #drive label
#Get started
$disks = get-disk |where partitionstyle -eq 'raw'
if ($disks.Count -lt 2) {throw "Not Enough RAW disks"}
#Prepare diskpart Script for each disk
foreach ($disk in $disks) {
Initialize-Disk -PartitionStyle MBR -Number $disk.Number #Bring Online and Initialize
$a = "select disk $($disk.Number)"+[char][int](13)+[char][int](10); #Select Disk
$a += "attributes disk clear readonly noerr "+[char][int](13)+[char][int](10); #set attributes
$a += "convert dynamic noerr "+[char][int](13)+[char][int](10); #convert to dynamic
$a += "exit"+[char][int](13)+[char][int](10);
$a | Set-Content c:\diskpartA_$($disk.Number).txt -Encoding ASCII
}
#Execute script for each disk
foreach ($disk in $disks) {
& Diskpart /s c:\diskpartA_$($disk.Number).txt
Remove-Item c:\diskpartA_$($disk.Number).txt
}
#Prepare striped Volume
$striped = "create volume stripe disk="
foreach ($disk in $disks) {
#join volumes together for strip set
$striped = $striped + $disk.Number + ","
}
$striped = $striped -replace ".$" #remove last ,
$striped = $striped +[char][int](13)+[char][int](10); #add CR/LF
$striped += "format fs=NTFS unit=$allocation label=`"$label`" quick "+[char][int](13)+[char][int](10); #Format Vol
$striped += "assign letter=$letter "+[char][int](13)+[char][int](10); #Assign Drive Letter
$striped += "exit"+[char][int](13)+[char][int](10);
$striped | Set-Content c:\diskpartB.txt -Encoding ASCII
#Execute striped Volume
& Diskpart /s c:\diskpartB.txt
Remove-Item c:\diskpartB.txt
|
PowerShellCorpus/GithubGist/sneal_eeb52e859186ba44163d_raw_f2d90d497c8e77883fa2d54565d8ee4cbfde252c_install-vmware-tools.ps1
|
sneal_eeb52e859186ba44163d_raw_f2d90d497c8e77883fa2d54565d8ee4cbfde252c_install-vmware-tools.ps1
|
$version = '9.6.1'
# from /Applications/VMware Fusion.app/Contents/Library/isoimages/windows.iso
$iso_name = 'vmware_fusion_tools_windows_6.0.3.iso'
$download_url = "http://host.example.com/$iso_name"
(New-Object System.Net.WebClient).DownloadFile($download_url, "c:\windows\temp\$iso_name")
&c:\7-zip\7z.exe x "c:\windows\temp\$iso_name" -oc:\windows\temp\vmware -aoa | Out-Host
&c:\windows\temp\vmware\setup.exe /S /v`"/qn REBOOT=R`" | Out-Host
exit 0
|
PowerShellCorpus/GithubGist/ot-joe-ocampo_3948174_raw_ca8fcdcf83c87f87015589f45876da2b6c1df77f_profile.ps1
|
ot-joe-ocampo_3948174_raw_ca8fcdcf83c87f87015589f45876da2b6c1df77f_profile.ps1
|
# Configure Path
$GitInstallDir = 'C:\Program Files (x86)\Git'
$NotepadPlusDir = 'C:\Program Files (x86)\Notepad++\'
$Env:Path = "$NotepadPlusDir;$GitInstallDir\bin;$Env:Path"
if(!$Env:HOME) { $Env:HOME = "$Env:HOMEDRIVE$Env:HOMEPATH" }
if(!$Env:HOME) { $Env:HOME = $Env:USERPROFILE }
$Env:PLINK_PROTOCOL = 'ssh'
# If Posh-Git environment is defined, load it.
if (test-path env:posh_git) {
. $env:posh_git
}
function Load-Scripts {
$myscript_path = 'C:\code\psScripts\*.ps1'
$children = Get-ChildItem $myscript_path
foreach ($pshfile in $children)
{
. $pshfile
Write-Host "$pshfile loaded"
}
}
function init{
Write-Host 'Loading User Scripts'
Load-Scripts
# Change to code directory
cd \code
# Load NodeJS to Environment
"C:\Program Files\nodejs\nodejsvars.bat"
# Setup aliases
New-Alias np Notepad++
}
# Initalize Env
init
|
PowerShellCorpus/GithubGist/wpsmith_8d4acea64423543da32e_raw_0057345c81061c9ffb6bd1eaf52aaf063c4fbf54_upload-spfile.ps1
|
wpsmith_8d4acea64423543da32e_raw_0057345c81061c9ffb6bd1eaf52aaf063c4fbf54_upload-spfile.ps1
|
[CmdletBinding()]
Param(
# SharePoint Document Library Name, e.g., "Site Documents"
[Parameter(Mandatory=$True)]
[string]$docLibrary,
# Path to the local file, "C:\Documents\" # Include trailing slash
[Parameter(Mandatory=$True)]
[string]$filePath,
# File name, e.g., myfile.txt
[Parameter(Mandatory=$True)]
[string]$fileName
)
$spFolder = $spWeb.GetFolder($docLibrary)
$spFileCollection = $spFolder.Files
$file = Get-ChildItem $filePath + $fileName
$spFileCollection.Add("$($docLibrary)/$($fileName)",$file.OpenRead(),$false)
Get-ChildItem C:\Documents -filter “*.docx” | ForEach { $spFileCollection.Add("$($docLibrary)/$($_.Name)",$_.OpenRead(),$true)}
|
PowerShellCorpus/GithubGist/tugberkugurlu_4223730_raw_822fff60c13ad7e6edb560e5c388788fdd5e5b50_Deploy.ps1
|
tugberkugurlu_4223730_raw_822fff60c13ad7e6edb560e5c388788fdd5e5b50_Deploy.ps1
|
param(
$subscriptionId = $env:PINGYOURPACKAGE_AZURE_SUBSCRIPTION_ID,
$certificateThumbprint = $env:PINGYOURPACKAGE_MANAGEMENT_CERTIFICATE_THUMBPRINT,
$serviceName = $env:PINGYOURPACKAGE_AZURE_SERVICE_NAME,
$storageServiceName = $env:PINGYOURPACKAGE_AZURE_STORAGE_ACCOUNT_NAME,
$sqlAzureConnectionString = $env:PINGYOURPACKAGE_SQL_AZURE_CONNECTION_STRING,
$sslCertificateThumbprint = $env:PINGYOURPACKAGE_SSL_CERTIFICATE_THUMBPRINT,
$remoteDesktopAccountExpiration = $env:PINGYOURPACKAGE_REMOTE_DESKTOP_ACCOUNT_EXPIRATION,
$remoteDesktopCertificateThumbprint = $env:PINGYOURPACKAGE_REMOTE_DESKTOP_CERTIFICATE_THUMBPRINT,
$remoteDesktopPassword = $env:PINGYOURPACKAGE_REMOTE_DESKTOP_PASSWORD,
$remoteDesktopUsername = $env:PINGYOURPACKAGE_REMOTE_DESKTOP_USERNAME,
$commitSha,
$commitBranch
)
# Import Common Stuff
$ScriptRoot = (Split-Path -parent $MyInvocation.MyCommand.Definition)
. $ScriptRoot\_Common.ps1
# Validate Sutff
require-param -value $subscriptionId -paramName "subscriptionId"
require-param -value $certificateThumbprint -paramName "certificateThumbprint"
require-param -value $serviceName -paramName "apiServiceName"
require-param -value $storageServiceName -paramName "storageServiceName"
require-param -value $sqlAzureConnectionString -paramName "sqlAzureConnectionString"
require-param -value $remoteDesktopAccountExpiration -paramName "remoteDesktopAccountExpiration"
require-param -value $remoteDesktopCertificateThumbprint -paramName "remoteDesktopCertificateThumbprint"
require-param -value $remoteDesktopPassword -paramName "remoteDesktopPassword"
require-param -value $remoteDesktopUsername -paramName "remoteDesktopUsername"
require-module -name "WAPPSCmdlets"
# Helper Functions
function set-connectionstring {
param($path, $name, $value)
$settings = [xml](get-content $path)
$setting = $settings.configuration.connectionStrings.add | where { $_.name -eq $name }
$setting.connectionString = "$value"
$setting.providerName = "System.Data.SqlClient"
$resolvedPath = resolve-path($path)
$settings.save($resolvedPath)
}
function set-appsetting {
param($path, $name, $value)
$settings = [xml](get-content $path)
$setting = $settings.configuration.appSettings.selectsinglenode("add[@key='" + $name + "']")
$setting.value = $value.toString()
$resolvedPath = resolve-path($path)
$settings.save($resolvedPath)
}
function set-releasemode {
param($path)
$xml = [xml](get-content $path)
$compilation = $xml.configuration."system.web".compilation
$compilation.debug = "false"
$resolvedPath = resolve-path($path)
$xml.save($resolvedPath)
}
function encrypt-envelope ($unprotectedContent, $cert) {
[System.Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
$utf8content = [Text.Encoding]::UTF8.GetBytes($unprotectedContent)
$content = New-Object Security.Cryptography.Pkcs.ContentInfo -argumentList (,$utf8content)
$env = New-Object Security.Cryptography.Pkcs.EnvelopedCms $content
$recpient = (New-Object System.Security.Cryptography.Pkcs.CmsRecipient($cert))
$env.Encrypt($recpient)
$base64string = [Convert]::ToBase64String($env.Encode())
return $base64string
}
function set-configurationsetting {
param($path, $name, $value)
$xml = [xml](get-content $path)
$setting = $xml.serviceconfiguration.role.configurationsettings.setting | where { $_.name -eq $name }
$setting.value = "$value"
$resolvedPath = resolve-path($path)
$xml.save($resolvedPath)
}
function set-certificatethumbprint {
param($path, $name, $value)
$xml = [xml](get-content $path)
$certificate = $xml.serviceconfiguration.role.Certificates.Certificate | where { $_.name -eq $name }
$certificate.thumbprint = "$value"
$resolvedPath = resolve-path($path)
$xml.save($resolvedPath)
}
function await-operation($operationId) {
$status = Get-OperationStatus -SubscriptionId $subscriptionId -Certificate $certificate -OperationId $operationId
while ([string]::Equals($status, "InProgress")) {
sleep -Seconds 1
$status = Get-OperationStatus -SubscriptionId $subscriptionId -Certificate $certificate -OperationId $operationId
}
return $status
}
function await-status($status) {
$deployment = Get-Deployment -ServiceName $serviceName -Slot Staging -Certificate $certificate -SubscriptionId $subscriptionId
while (-not([string]::Equals($deployment.status, $status))) {
sleep -Seconds 1
$deployment = Get-Deployment -ServiceName $serviceName -Slot Staging -Certificate $certificate -SubscriptionId $subscriptionId
}
}
function await-start() {
$deployment = Get-Deployment -ServiceName $serviceName -Slot Staging -Certificate $certificate -SubscriptionId $subscriptionId
$roleInstances = Get-RoleInstanceStatus -ServiceName $serviceName -RoleInstanceList $deployment.RoleInstanceList -Certificate $certificate -SubscriptionId $subscriptionId
$roleInstancesThatAreNotReady = $roleInstances.RoleInstances | where-object { $_.InstanceStatus -ne "Ready" }
while ($roleInstancesThatAreNotReady.Count -gt 0) {
sleep -Seconds 1
$deployment = Get-Deployment -ServiceName $serviceName -Slot Staging -Certificate $certificate -SubscriptionId $subscriptionId
$roleInstances = Get-RoleInstanceStatus -ServiceName $serviceName -RoleInstanceList $deployment.RoleInstanceList -Certificate $certificate -SubscriptionId $subscriptionId
$roleInstancesThatAreNotReady = $roleInstances.RoleInstances | where-object { $_.InstanceStatus -ne "Ready" }
}
$deployment = Get-Deployment -ServiceName $serviceName -Slot Staging -Certificate $certificate -SubscriptionId $subscriptionId
while (-not([string]::Equals($deployment.status, "Running"))) {
sleep -Seconds 1
$deployment = Get-Deployment -ServiceName $serviceName -Slot Staging -Certificate $certificate -SubscriptionId $subscriptionId
}
}
$scriptPath = split-path $MyInvocation.MyCommand.Path
$rootPath = resolve-path(join-path $scriptPath "..")
$csdefFile = join-path $scriptPath "PingYourPackage.csdef"
$artifactsPath = join-path $rootPath "artifacts"
$webAppsPath = join-path $artifactsPath "_PublishedWebsites"
$apiAppPath = join-path $webAppsPath "PingYourPackage.API.WebHost"
$webClientAppPath = join-path $webAppsPath "PingYourPackage.WebClient"
$apiAppWebConfigPath = join-path $apiAppPath "Web.config"
$apiAppWebConfigBakPath = join-path $apiAppPath "Web.config.bak"
$webClientAppWebConfigPath = join-path $webClientAppPath "Web.config"
$webClientAppWebConfigBakPath = join-path $webClientAppPath "Web.config.bak"
$rolePropertiesPath = join-path $scriptPath "PingYourPackage.RoleProperties.txt"
$cscfgPath = join-path $scriptPath "PingYourPackage.cscfg"
$cscfgBakPath = join-path $scriptPath "PingYourPackage.cscfg.bak"
$cspkgFolder = join-path $rootPath "_AzurePackage"
$cspkgFile = join-path $cspkgFolder "PingYourPackage.cspkg"
$apiAppBinPath = join-path $apiAppPath "bin"
$webClientAppBinPath = join-path $webClientAppPath "bin"
$gitPath = join-path (programfiles-dir) "Git\bin\git.exe"
"Building deployment name from date"
$deploymentLabel = "$((get-date).ToString("MMM dd @ HHmm"))"
$deploymentName = "$((get-date).ToString("yyyyMMddHHmmss"))-auto"
"Deployment name has been built: $deploymentName"
if ($commitSha -eq $null) {
"Retrieving the commiy SHA"
$commitSha = (& "$gitPath" rev-parse HEAD)
"Commit SHA has been retrieved: $commitSha"
}
if ($commitBranch -eq $null) {
"Retrieving the commit branch"
$commitBranch = (& "$gitPath" name-rev --name-only HEAD)
"Commit branch has been retrieved: $commitBranch"
}
cp $apiAppWebConfigPath $apiAppWebConfigBakPath
cp $webClientAppWebConfigPath $webClientAppWebConfigBakPath
cp $cscfgPath $cscfgBakPath
set-connectionstring -path $apiAppWebConfigPath -name "PingYourPackage" -value $sqlAzureConnectionString
set-appsetting $apiAppWebConfigPath "PingYourPackage:CommitSha" $commitSha
set-appsetting $webClientAppWebConfigPath "PingYourPackage:CommitSha" $commitSha
set-appsetting $apiAppWebConfigPath "PingYourPackage:CommitBranch" $commitBranch
set-appsetting $webClientAppWebConfigPath "PingYourPackage:CommitBranch" $commitBranch
set-appsetting $apiAppWebConfigPath "PingYourPackage:DeploymentName" $deploymentName
set-appsetting $webClientAppWebConfigPath "PingYourPackage:DeploymentName" $deploymentName
set-releasemode $apiAppWebConfigPath
set-releasemode $webClientAppWebConfigPath
set-certificatethumbprint -path $cscfgPath -name "Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" -value $remoteDesktopCertificateThumbprint
set-configurationsetting -path $cscfgPath -name "Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountExpiration" -value $remoteDesktopAccountExpiration
set-configurationsetting -path $cscfgPath -name "Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountEncryptedPassword" -value (encrypt-envelope $remoteDesktopPassword (get-item cert:\CurrentUser\My\$remoteDesktopCertificateThumbprint))
set-configurationsetting -path $cscfgPath -name "Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountUsername" -value $remoteDesktopUsername
if ((test-path $cspkgFolder) -eq $false) {
mkdir $cspkgFolder | out-null
} else {
remove-item $cspkgFolder\* -Recurse
}
& 'C:\Program Files\Windows Azure SDK\v1.6\bin\cspack.exe' "$csdefFile" /out:"$cspkgFile" /role:"PingYourPackage;$webAppsPath" /sites:"PingYourPackage;PingYourPackage.API;$apiAppPath;PingYourPackage.WebClient;$webClientAppPath" /rolePropertiesFile:"PingYourPackage;$rolePropertiesPath"
cp $cscfgPath $cspkgFolder
cp $apiAppWebConfigBakPath $apiAppWebConfigPath
cp $webClientAppWebConfigBakPath $webClientAppWebConfigPath
cp $cscfgBakPath $cscfgPath
print-success("Azure package and configuration dropped to $cspkgFolder.")
write-host ""
"Getting Azure management certificate $certificateThumbprint"
$certificate = (Get-Item cert:\CurrentUser\My\$certificateThumbprint)
"Locating Azure package and configuration"
$readyCspkgFile = join-path $cspkgFolder "PingYourPackage.cspkg"
$readyCscfgFile = join-path $cspkgFolder "PingYourPackage.cscfg"
"Checking for existing staging deployment on $serviceName"
$deployment = Get-Deployment -ServiceName $serviceName -Slot Staging -Certificate $certificate -SubscriptionId $subscriptionId
if ($deployment -ne $null -and $deployment.Name -ne $null) {
"Deleting existing staging deployment $($deployment.Name) on $serviceName"
$operationId = (remove-deployment -subscriptionId $subscriptionId -certificate $certificate -slot Staging -serviceName $serviceName ).operationId
await-operation($operationId)
}
"Creating new staging deployment $deploymentName on $serviceName"
$operationId = (new-deployment -subscriptionId $subscriptionId -certificate $certificate -ServiceName $serviceName -storageServiceName $storageServiceName -slot Staging -Package $readyCspkgFile -Configuration $readyCscfgFile -Name $deploymentName -Label $deploymentLabel).operationId
await-operation($operationId)
await-status("Suspended")
"Starting staging deployment $deploymentName on $serviceName"
$operationId = (set-deploymentstatus -subscriptionId $subscriptionId -serviceName $serviceName -slot Staging -status Running -certificate $certificate).operationId
await-operation($operationId)
await-start
"Moving staging deployment $deploymentName to productionon on $serviceName"
$operationId = (move-deployment -subscriptionId $subscriptionId -serviceName $serviceName -certificate $certificate -name $deploymentName).operationId
await-operation($operationId)
print-success("Deployment $deploymentName on $serviceName has been completed")
"Deleting staging deployment $deploymentName on $serviceName"
$operationId = (remove-deployment -subscriptionId $subscriptionId -certificate $certificate -slot Staging -serviceName $serviceName ).operationId
await-operation($operationId)
Exit 0
|
PowerShellCorpus/GithubGist/jokcofbut_990d0ddc837ca724953a_raw_65f1a95fa0cca964458972ed80d01d663b198034_Yo.ps1
|
jokcofbut_990d0ddc837ca724953a_raw_65f1a95fa0cca964458972ed80d01d663b198034_Yo.ps1
|
param([string] $expression)
Invoke-Expression $expression
$url = "http://api.justyo.co/yoall/"
$body = @{ api_token = "YOUR-KEY" }
Invoke-RestMethod -Method Post -Uri $url -Body $body
|
PowerShellCorpus/GithubGist/ser1zw_4366363_raw_1f1262b5eb618dce2c2213f540aa38e1ab035925_send.ps1
|
ser1zw_4366363_raw_1f1262b5eb618dce2c2213f540aa38e1ab035925_send.ps1
|
################################################################################
# Send E-mail from eml file in PowerShell
# Tested on PowerShell 2.0
#
# Usage:
# 1. Configure the variables defined in Main()
# $server = "localhost"
# $port = "25"
# $mailfrom = "from@example.com"
# $rcptto = "to@example.com"
# $filename = "test.eml"
#
# 2. Run the script in PowerShell
#
# See http://www.leeholmes.com/blog/2009/10/28/scripting-network-tcp-connections-in-powershell/
################################################################################
$encoding = New-Object System.Text.AsciiEncoding
Function SendCommand($stream, $writer, $command) {
# Send command
foreach ($line in $command) {
$writer.WriteLine($line)
}
$writer.Flush()
Start-Sleep -m 100
# Get response
$buff = New-Object System.Byte[] 4096
$output = ""
while ($True) {
$size = $stream.Read($buff, 0, $buff.Length)
if ($size -gt 0) {
$output += $encoding.GetString($buff, 0, $size)
}
if (($size -lt $buff.Length) -or ($size -le 0)) {
break
}
}
if ([int]::Parse($output[0]) -gt 3) {
throw $output
}
$output
}
Function SendMessage($server, $port, $mailfrom, $rcptto, $filename) {
try {
$socket = New-Object System.Net.Sockets.TcpClient($server, $port)
$stream = $socket.GetStream()
$stream.ReadTimeout = 1000
$writer = New-Object System.IO.StreamWriter $stream
$endOfMessage = "`r`n."
SendCommand $stream $writer ("EHLO " + $server)
SendCommand $stream $writer ("MAIL FROM: <" + $mailfrom + ">")
SendCommand $stream $writer ("RCPT TO: <" + $rcptto + ">")
SendCommand $stream $writer "DATA"
$content = (Get-Content $filename) -join "`r`n"
SendCommand $stream $writer ($content + $endOfMessage)
SendCommand $stream $writer "QUIT"
}
catch [Exception] {
Write-Host $Error[0]
}
finally {
if ($writer -ne $Null) {
$writer.Close()
}
if ($socket -ne $Null) {
$socket.Close()
}
}
}
Function Main() {
$server = "localhost"
$port = "25"
$mailfrom = "from@example.com"
$rcptto = "to@example.com"
$filename = "test.eml"
SendMessage $server $port $mailfrom $rcptto $filename
}
Main | Out-Null
|
PowerShellCorpus/GithubGist/RhysC_848255_raw_1f24facc6cfd696d9232101f462a5d1feb81a04f_MachineAudit.ps1
|
RhysC_848255_raw_1f24facc6cfd696d9232101f462a5d1feb81a04f_MachineAudit.ps1
|
#Audit script
$auditFile = "audit.txt"
$computername = "." #i.e local machine
"Computer name $computername" > $auditFile
"Computer details:" >> $auditFile
get-wmiobject Win32_ComputerSystem -computername $computername |
select Name, Manufacturer, Model,`
NumberOfProcessors, TotalPhysicalMemory, `
Domain, CurrentTimeZone, DayLightInEffect |
Format-List|
Out-File $auditFile -Append
#os details
"OS details:" >> $auditFile
get-wmiobject Win32_OperatingSystem -computername $computername |
select Caption, ServicePackMajorVersion, ServicePackMinorVersion |
Format-List|
Out-File $auditFile -Append
#CLR versions
".Net details:" >> $auditFile
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP" | Get-ItemProperty|
Format-List|
Out-File $auditFile -Append
#powershell version
"PowerShell version:" >> $auditFile
$Host.Version >> $auditFile
#silverlight version
"`r`nSilverlight version:" >> $auditFile
(get-itemproperty HKLM:\SOFTWARE\Microsoft\Silverlight Version).Version >> $auditFile
#Environment variables
"`r`nEnvironment variables:" >> $auditFile
[Environment]::GetEnvironmentVariables()|
Format-List|
Out-File $auditFile -Append
|
PowerShellCorpus/GithubGist/andreagx_9067720_raw_72aac39842f388a6c2bfb8d4b2a0e56534d2c1c6_OWA_Sigature.ps1
|
andreagx_9067720_raw_72aac39842f388a6c2bfb8d4b2a0e56534d2c1c6_OWA_Sigature.ps1
|
# OWA Signature import by Andrea Gallazzi www.andreagallazzi.com
#var old is text to remove
$old = 'src=".+?_file/image001.gif"'
#var $new = the text you want to replace
$new = 'src="http://www.mypublicwebsite.com/image001.gif"'
#change the Get-ChildItem to a folder or your choice
Get-ChildItem C:\Signatures\*.htm | Where {$_ -IS [IO.FileInfo]} |
% {
(Get-Content $_.FullName) -replace $old, $new | Set-Content $_.FullName
Write-Host "----- WORKING ----------"
Write-Host "Processed: " + $_.FullName
}
#REMOVE DONE
# Import OWA Signatures in EMS
$mailboxes = Get-Mailbox
$mailboxes| foreach {$file= "C:\Signatures\" + ($_.alias) + ".htm"; Set-MailboxMessageConfiguration -identity $_.alias -AutoAddSignature $True -SignatureHtml "$(Get-Content -Path $file -ReadCount 0)"}
|
PowerShellCorpus/GithubGist/jacobludriks_a9fa14f95038e3b41952_raw_0a256826a1a44b951f345ddc8ad538672c178a5d_send-nexmosms.ps1
|
jacobludriks_a9fa14f95038e3b41952_raw_0a256826a1a44b951f345ddc8ad538672c178a5d_send-nexmosms.ps1
|
Function Send-NexmoSMS {
Param(
[Parameter(Mandatory=$true)]
[string]$APIKey,
[Parameter(Mandatory=$true)]
[string]$APISecret,
[Parameter(Mandatory=$true)]
[string]$From,
[Parameter(Mandatory=$true)]
[string]$To,
[Parameter(Mandatory=$true)]
[string]$Text
)
if (!($to -match '\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$')) {
Write-Warning "Phone number is not valid. Please use international format (ie. +61400400400)"
exit
}
if (($text | measure -character).characters -gt 3200) {
Write-Warning "Message has to be less than 3200 characters"
exit
}
$body = @{
api_key = $APIKey
api_secret = $APISecret
from = $from
type = "text"
to = $to
text = $text
}
$sendsms = Invoke-RestMethod -Uri https://rest.nexmo.com/sms/json -ContentType "application/x-www-form-urlencoded" -Body $body -Method POST
switch ($sendsms.messages.status) {
0 { return "Success" }
1 { return "Throttled" }
2 { return "Missing params" }
3 { return "Invalid params" }
4 { return "Invalid credentials" }
5 { return "Internal error" }
6 { return "Invalid message" }
7 { return "Number barred" }
8 { return "Partner account barred" }
9 { return "Partner quota exceeded" }
11 { return "Account not enabled for REST" }
12 { return "Message too long" }
13 { return "Communication failed" }
14 { return "Invalid signature" }
15 { return "Invalid sender address" }
16 { return "Invalid TTL" }
19 { return "Facility not allowed" }
20 { return "Invalid message class" }
default { return "Unspecified error, check Nexmo console" }
}
}
|
PowerShellCorpus/GithubGist/algu_4128319_raw_4300c845f3f2d922efd45b2e27e034416f09feb5_extensionAttribute_migration.ps1
|
algu_4128319_raw_4300c845f3f2d922efd45b2e27e034416f09feb5_extensionAttribute_migration.ps1
|
# AD extensionAttribute migration between different forests
#
# Aleksey Gupa at 22/11/2012 00:38
#
# 1. read all users from $SearchOU (for example $SearchOU ="test.local/Country/BE/"
# 2. get their extensionAttribute5
# 3. if extensionAttribute is a network path to some picture
# (like "\\NAS5GE003\images\picture001.jpg" exist,
# then replace this path to the new one "\\NAS1BE001\HiddenShare$\images\picture001.jpg"
#
# Aleksey Gupa at 22/11/2012 00:38
#
# Add required snapin and module
Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
$SearchOU = "test.local/Country/BE"
$CSVLog = ".\Users1.csv"
$Users_with_attr5 = Get-QADUser -SearchRoot $SearchOU -SearchAttributes @{extensionAttribute5='*'} -SizeLimit 0
foreach ($User_with_attr5 in $Users_with_attr5) {
$Ext5attr = $User_with_attr5.extensionAttribute5
#if extensionAttribute5 is a network path...
if ($Ext5attr -match "(?<oldpath>[\w.$\\]+)[\\](?<picturename>[\w.]+)$") {
#change existing path to smth different \\NAS1BE001\HiddenShare$\images\ with the same filename
$newpath = "\\NAS1BE001\HiddenShare$\images\" + $Matches.picturename
$User_with_attr5 | Set-QADUser -objectAttributes @{extensionAttribute5=$newpath}
$Name = $User_with_attr5.name
$LogonName = $User_with_attr5.logonname
Write-Output "$Name, $LogonName, $Ext5attr, $newpath" >> $CSVLog
}
}
#Getting amount of proccessed objects:
$Users_with_attr5 | Measure-Object
|
PowerShellCorpus/GithubGist/phantomtypist_7391669aad234a773a23_raw_57cbc164a4d7a61d9fa86bc70afb8fa61d022653_Boxstarter-03-Software-Development.ps1
|
phantomtypist_7391669aad234a773a23_raw_57cbc164a4d7a61d9fa86bc70afb8fa61d022653_Boxstarter-03-Software-Development.ps1
|
# http://boxstarter.org/package/url?
# Source Control
cinst git.install
cinst msysgit
cinst poshgit
cinst git-credential-winstore -Version 1.2.0.0
cinst gitextensions
cinst tortoisegit
cinst tortoisehg
cinst githubforwindows
if (Test-PendingReboot) { Invoke-Reboot }
# Sql Server
cinst SqlServer2012Express
if (Test-PendingReboot) { Invoke-Reboot }
# Development stuff
cinst vcredist2005
cinst vcredist2008
cinst vcredist2010
if (Test-PendingReboot) { Invoke-Reboot }
cinst webpi
if (Test-PendingReboot) { Invoke-Reboot }
cinst VisualStudio2012Ultimate
if (Test-PendingReboot) { Invoke-Reboot }
cinst VisualStudio2013Ultimate
if (Test-PendingReboot) { Invoke-Reboot }
cinst ruby
cinst python
cinst python -Version 2.7.6
cinst arduinoide
cinst arduinoidegalileo
cinst gtksharp
cinst NuGet.CommandLine
cinst nodejs.install
cinst ScriptCs
cinst PhantomJS
cinst beyondcompare
cinst SourceTree
cinst linqpad4
cinst freecad
cinst eagle
cinst fiddler4
cinst notepadplusplus.install
cinst sublimetext2
cinst winscp
cinst dotPeek
cinst mongodb
cinst nunit
cinst XUnit
cinst ilmerge
cinst typescript
cinst papercut
#cinst smtp4dev
cinst SQLite
cinst redis
cinst mono
cinst monodevelop
cinst rabbitmq
cinst typescript.vs
if (Test-PendingReboot) { Invoke-Reboot }
# VS related extras
cinst resharper -Version 8.2.0.2160 # I don't currently have a R# v.8 license.
Install-ChocolateyVsixPackage PowerShellTools http://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597/file/112013/6/PowerShellTools.vsix
Install-ChocolateyVsixPackage WebEssentials2013 http://visualstudiogallery.msdn.microsoft.com/56633663-6799-41d7-9df7-0f2a504ca361/file/105627/31/WebEssentials2013.vsix
Install-ChocolateyVsixPackage T4Toolbox http://visualstudiogallery.msdn.microsoft.com/791817a4-eb9a-4000-9c85-972cc60fd5aa/file/116854/1/T4Toolbox.12.vsix
# Fix SSH-Agent error by adding the bin directory to the `Path` environment variable
$env:PSModulePath = $env:PSModulePath + ";C:\Program Files (x86)\Git\bin"
|
PowerShellCorpus/GithubGist/seafoox_4348d37828208c86713d_raw_5fb0bc6d8cdf57981f8e4d52809c414e68c70daa_gistfile1.ps1
|
seafoox_4348d37828208c86713d_raw_5fb0bc6d8cdf57981f8e4d52809c414e68c70daa_gistfile1.ps1
|
# Open terminal and type
defaults write com.google.Chrome.plist AppleEnableSwipeNavigateWithScrolls -bool FALSE
# For mavericks
defaults write com.google.Chrome AppleEnableSwipeNavigateWithScrolls -bool FALSE
|
PowerShellCorpus/GithubGist/Retro2707_7295270_raw_cacfb4f6cca129851fbedb9392d2ed4cd26f96e7_get-info.ps1
|
Retro2707_7295270_raw_cacfb4f6cca129851fbedb9392d2ed4cd26f96e7_get-info.ps1
|
<#
.SYNOPSIS
Retrieves info from one or more computers.
.PARAMETER computername
The computer name(s) to retrieve the info from.
.PARAMETER logfile
The path and filename of a text file where failed computers will be logged. Defaults to c:\retries.txt.
.EXAMPLE
Get-ADComputer –filter * | Select @{label='computername';expression={$_.name}} | Get-Info
.EXAMPLE
Get-Info –computername SERVER2,SERVER3
.EXAMPLE
"localhost" | Get-Info
.EXAMPLE
Get-Info –computername (Get-Content names.txt)
.EXAMPLE
Get-Content names.txt | Get-Info
#>
Function Get-Info {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
[string[]]$computername,
[string]$logfile = 'c:\retries.txt'
)
BEGIN {
Remove-Item $logfile –erroraction silentlycontinue
}
PROCESS {
Foreach ($computer in $computername) {
$continue = $true
try {
$os = Get-WmiObject –class Win32_OperatingSystem –computername $computer –erroraction Stop
} catch {
$continue = $false
$computer | Out-File $logfile
}
if ($continue) {
$bios = Get-WmiObject –class Win32_BIOS –computername $computer
$obj = New-Object –typename PSObject
$obj | Add-Member –membertype NoteProperty –name ComputerName –value ($computer) –passthru |
Add-Member –membertype NoteProperty –name OSVersion –value ($os.caption) –passthru |
Add-Member –membertype NoteProperty –name OSBuild -value ($os.buildnumber) –passthru |
Add-Member –membertype NoteProperty –name BIOSSerial –value ($bios.serialnumber) –passthru |
Add-Member –membertype NoteProperty –name SPVersion –value ($os.servicepackmajorversion)
Write-Output $obj
}
}
}
}
Get-Info -computername $env:COMPUTERNAME
|
PowerShellCorpus/GithubGist/talatham_5765965_raw_ce070afb78e4ff1c98c3d058bb9c62f0b9aec19e_openfile.ps1
|
talatham_5765965_raw_ce070afb78e4ff1c98c3d058bb9c62f0b9aec19e_openfile.ps1
|
# ---------- FUNCTION -------------
Function Get-FileName
# Open file dialog box and select a file to import
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.filter = "Text Files (*.txt)| *.txt" # Set the file types visible to dialog
# Alternate filters include:
# "CSV files (*.csv) | *.csv"
$OpenFileDialog.initialDirectory = "c:\"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
# --------- USAGE ---------------
$filename = Get-FileName
$filecontents = Get-Content $filename
foreach ($line in $filecontents)
....
|
PowerShellCorpus/GithubGist/sempervictus_6076104_raw_7d3fd7272cd613e4a27aaf0e357fe2cf353d624a_gistfile1.ps1
|
sempervictus_6076104_raw_7d3fd7272cd613e4a27aaf0e357fe2cf353d624a_gistfile1.ps1
|
[Environment]::SetEnvironmentVariable("PshStub", "#{code}", "User")
Invoke-Expression $($([Text.Encoding]::Unicode.GetString([Environment]::GetEnvironmentVariable("PshStub","User")))
|
PowerShellCorpus/GithubGist/theagreeablecow_2780747_raw_dc5e643ce111a358f1534f1a336aed521834c4b1_setupnewuser.ps1
|
theagreeablecow_2780747_raw_dc5e643ce111a358f1534f1a336aed521834c4b1_setupnewuser.ps1
|
# This script will set up AD, User Directories, Exchange and Lync, using basic data retrived from a CSV file
# Requires the Active Directory module for Windows Powershell and appropriate credentials
# CSV file with corresponding header and user(s) info:
# Office,UserName,FirstName,LastName,Initial,Department,Role,Title,SetupSameAs,Manager,MailboxAccess,Extension,Mobile
#LOAD POWERSHELL SESSIONS
#------------------------
$exchangeserver = "exchange1.domain.com"
$Lyncserver = "lync1.domain.com.au"
$DC = "dc1.domain.com.au"
$AdminEmail = "administrator@domain.com.au"
$ScriptUser = $env:username
$usercredential= get-credential -credential domain\AdminUser
cls
write-host -foregroundcolor Green "Loading modules for AD, Exchange and Lync..."
$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$exchangeserver/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PsSession $exchangesession
$lyncsession = new-pssession -connectionuri https://$Lyncserver/ocspowershell -credential $usercredential
Import-PSSession $lyncsession
import-module ActiveDirectory
#VARIABLES
#---------
#Get Script User's Name
$ScriptUserDetails = Get-ADUser $ScriptUser -Server $DC -properties givenName | select-object givenName
$ScriptUserName = $ScriptUserDetails.givenName
#Email Communications
$EmailCC1 = "user1@domain.com.au"
$EmailCC2 = "user2@domain.com.au"
#LOAD USER DATA FROM CSV
#-----------------------
$InputPath = "\\domain.com.au\Scripts\Data\"
$InputFile = $InputPath + "NewUserInfo.csv"
Invoke-Item $inputFile
cls
write-host -foregroundcolor Green "Update user details and save CSV file. Press any key to continue"
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
#DEFINE VARIABLES
#----------------
$inputFile = Import-CSV $inputFile
foreach($line in $inputFile)
{
#Retrieve user details from CSV file
$office = $line.Office
$username = $line.UserName
$firstname = $line.FirstName
$lastname = $line.LastName
$initial = $line.Initial
$department = $line.Department
$Role = $line.Role
$title = $line.Title
$SetupSameAs = $line.SetupSameAs
$manager = $line.Manager
$MailboxAccess = $line.MailboxAccess
$Extension = $line.Extension
$Extension = $Extension.substring($Extension.length -3, 3)
$Mobile = $line.Mobile
$info = ""
cls
#Prompt for any missing details
if ($username -eq "") {$username = read-host -prompt "Please Enter Unique Username"}
if ($office -eq "") {$office = read-host -prompt "Please Enter Office for"}
if ($initial -eq "") {$initial = read-host -prompt "Please Enter Unique User Initials"}
if ($department -eq "") {$department = read-host -prompt "Please Enter Department"}
if ($Role -eq "") {$Role = read-host -prompt "Please Enter Role"}
if ($title -eq "") {$title = read-host -prompt "Please Enter Title"}
if ($SetupSameAs -eq "") {$SetupSameAs = read-host -prompt "Please Enter SetupSameAs"}
if ($manager -eq "") {$manager = read-host -prompt "Please Enter thier Manager's Username"}
if ($Extension -eq "") {$Extension = read-host -prompt "Please Enter 3 Digit Phone Extension"}
#if ($Mobile -eq "") {$Mobile = read-host -prompt "Please Enter Mobile in (+61) 405 123 123 format"}
#Get 'SetupSameAs' Details
$SameAsDetails = Get-ADUser $SetupSameAs -Server $DC -properties Office,DisplayName,sAMAccountName | select-object Office,DisplayName,sAMAccountName
$SameAsOffice = $SameAsDetails.Office
$SameAsDisplayName = $SameAsDetails.DisplayName
#Get Script User's Details
$ScriptUserDetails = Get-ADUser $ScriptUser -Server $DC -properties mail | select-object mail
$ScriptUserMail = $ScriptUserDetails.mail
#Define Fixed Variables
$umpolicy="UMDial Default Policy"
$userou="OU=USERS,DC=domain,DC=com,DC=au"
$companyname="My Company"
$mailboxdatabase="MailDB1"
$sipdomain="domain.com.au"
$Country = "Australia"
$DisplayName = $firstname +" " +$lastname
$SharepointPage = "http://intranet/my/Person.aspx?accountname=domain\" +$username
$HomePath = "\\fileserver\home$\" +$username
$LogFile = $InputPath+"SetupLog_" +$username +".txt"
#Define Generated and Localised Variables
$Name=$Firstname+" "+$Lastname
$accountpassword = read-host -assecurestring -prompt "Please enter temporary password for new user"
$upn = $username+ "@domain.com.au"
$email = $Firstname+"."+$Lastname +"@domain.com.au"
if ($office -eq "City1")
{
$EnableVoice = $True
$Lyncserver="lync1.domain.com.au"
$Telephone = "(+61) 3 1234 5" +$Extension
$Street = "123 My Street"
$City = "City"
$State = "State"
$PostCode = "3000"
$ProfilePath = "\\fileserver\profiles\" +$username
$Fax = "(+61) 3 1234 5678 "
$IPphone = "3" +$Extension
$teluri = "tel:+612345" +$Extension +";ext=" +$IPphone
$info = "random text about user"
$Operator = "1000"
}
elseif ($office -eq "City2")
{
$EnableVoice = $True
$Lyncserver="lync2.domain.com.au"
$Telephone = "(+61) 3 1234 5" +$Extension
$Street = "123 My Street"
$City = "City"
$State = "State"
$PostCode = "3000"
$ProfilePath = "\\fileserver\profiles\" +$username
$Fax = "(+61) 3 1234 5678 "
$IPphone = "3" +$Extension
$teluri = "tel:+612345" +$Extension +";ext=" +$IPphone
$info = "random text about user"
$Operator = "1000"
}
elseif ($office -eq "City3")
{
$EnableVoice = $True
$Lyncserver="lync3.domain.com.au"
$Telephone = "(+61) 3 1234 5" +$Extension
$Street = "123 My Street"
$City = "City"
$State = "State"
$PostCode = "3000"
$ProfilePath = "\\fileserver\profiles\" +$username
$Fax = "(+61) 3 1234 5678 "
$IPphone = "3" +$Extension
$teluri = "tel:+612345" +$Extension +";ext=" +$IPphone
$info = "random text about user"
$Operator = "1000"
}
elseif ($office -eq "City4")
{
$EnableVoice = $True
$Lyncserver="lync4.domain.com.au"
$Telephone = "(+61) 3 1234 5" +$Extension
$Street = "123 My Street"
$City = "City"
$State = "State"
$PostCode = "3000"
$ProfilePath = "\\fileserver\profiles\" +$username
$Fax = "(+61) 3 1234 5678 "
$IPphone = "3" +$Extension
$teluri = "tel:+612345" +$Extension +";ext=" +$IPphone
$info = "random text about user"
$Operator = "1000"
}
else
{
write-host -foregroundcolor Red "Office not recognised. Quitting..."
exit
}
#Optional/Future
# $archivedatabase="Your Database holding online archives"
# $retentionpolicy="Your retention policy"
# $dialplan="Lync Voice Dial Plan"
# $voicepolicy="Lync Voice Policy"
# $locationpolicy="Lync Location Policy"
# $externalaccesspolicy="Lync External Access Policy"
Start-Transcript -path $LogFile -append
cls
write-host -foregroundcolor Green "New user setup starting for:" $firstname $lastname
write-host "`r"
#SETUP EXCHANGE
#--------------
#Create user and enable mailbox
New-Mailbox -DomainController $DC -name $name -userprincipalname $upn -Alias $username -OrganizationalUnit $userou -SamAccountName $username -FirstName $FirstName -Initials $initial -LastName $LastName -Password $accountpassword -ResetPasswordOnNextLogon $true -Database $mailboxdatabase | out-null
#OPTIONAL/FUTURE: -Archive -ArchiveDatabase $archivedatabase -RetentionPolicy $retentionpolicy
#pause for Exchange
write-host -foregroundcolor Green "New mailbox created - Pausing 10 seconds for Exchange changes"
write-host "`r"
Start-Sleep -s 10
#Update Notes info
Get-Mailbox $username -DomainController $DC | Set-User -DomainController $DC -notes $info
#Enable For Unified Messaging
if ($EnableVoice -eq $true)
{
Get-Mailbox $username -DomainController $DC | Enable-UMMailbox -DomainController $DC -ummailboxpolicy $umpolicy -sipresourceidentifier $email -extensions $IPphone
Start-Sleep -s 5
Get-Mailbox $username -DomainController $DC | Set-UMMailbox -OperatorNumber $Operator
write-host -foregroundcolor Green "Unified Messaging Properties updated - Pausing 10 Seconds for Exchange changes"
write-host "`r"
Start-Sleep -s 10
}
#Setup mailbox permissions
if (!($MailboxAccess -eq "")) {Add-MailboxPermission -Identity $manager -User $username -AccessRights 'FullAccess'}
#SETUP ACTIVE DIRECTORY
#-----------------------
#Update user properties
Set-ADUser -server $DC -Identity $username -City $City -Company $companyname -Country "AU" -Department $department -description $title -DisplayName $DisplayName -Division $department -Fax $Fax -HomePage $SharepointPage -Manager $manager -Office $office -OfficePhone $Telephone -postalCode $PostCode -profilePath $ProfilePath -State $State -StreetAddress $Street -Title $title -add @{ipphone=$IPphone}
#Update non-mandatory items
if (!($Mobile -eq "")) {Set-ADUser -server $DC -Identity $username -Replace @{mobile=$Mobile}}
write-host -foregroundcolor Green "Active Directory properties updated"
write-host "`r"
#Add to Groups (using SetupSameAs)
$ds = new-object directoryServices.directorySearcher
$ds.filter = "(&(objectCategory=person)(objectClass=user)(samAccountName="+$SetupSameAs+"))"
$dn = $ds.findOne()
$user = [ADSI]$dn.path
foreach ($group in $user.memberof)
{
Add-ADGroupMember -Identity $group -Members $username
#Trim group names
$GroupTrim = $group.indexof(",OU=")
if ($GroupTrim -gt 0)
{
$GroupName = $group.substring(0,$GroupTrim)
$GroupName = $GroupName -replace ("CN="," `n")
}
$RPTGroups = $RPTGroups+" "+$GroupName
}
#pause for AD changes
write-host -foregroundcolor Green "Active Directory groups and permissions update - Pausing 10 Seconds for all AD changes"
write-host "`r"
Start-Sleep -s 10
#SETUP USER DIRECTORIES
#----------------------
# User profile
$win7Profile = $ProfilePath +".V2"
IF (!(TEST-PATH $win7Profile)) {NEW-ITEM $win7Profile -type Directory}
#Build Access Control Entry List
$colRights = [System.Security.AccessControl.FileSystemRights]"FullControl"
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount("MyDomain\"+$username)
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($objUser, $colRights, $InheritanceFlag, $PropagationFlag, $objType)
#Apply Permissions
$objACL = Get-ACL $win7Profile
$objACL.AddAccessRule($objACE)
Set-ACL $win7Profile $objACL
#Apply Ownership
$objACL = Get-ACL $win7Profile
$objACL.SetOwner($objUser)
Set-Acl -aclobject $objACL -path $win7Profile -passthru
# User Home Drive
IF (!(TEST-PATH $HomePath)) {NEW-ITEM $HomePath -type Directory}
write-host -foregroundcolor Green "User Directories Created"
write-host "`r"
#SETUP LYNC
#----------
#enable for lync and configure settings
Get-mailbox $username -DomainController $DC | Enable-csuser -DomainController $DC -registrarpool $lyncserver -sipaddresstype EmailAddress -sipdomain $sipdomain
#pause for Lync changes
write-host -foregroundcolor Green "User setup for Lync - Pausing 10 Seconds for Lync Changes"
write-host "`r"
Start-Sleep -s 10
#Enable For Enterprise Voice
if ($EnableVoice -eq $true) {Get-mailbox $username -DomainController $DC | Set-CSUser -DomainController $DC -enterprisevoiceenabled $True -lineuri $teluri}
#OPTIONAL/FUTURE (if not <Default>):
#Get-mailbox $username | Grant-CSVoicePolicy -policyname $voicepolicy
#Get-mailbox $username | Grant-CSDialPlan -policyname $dialplan
#Get-mailbox $username | Grant-CSLocationPolicy -policyname $locationpolicy
#Get-mailbox $username | Grant-CSExternalAccessPolicy -policyname $externalaccesspolicy
#USER SUMMARY REPORT
#-------------------
cls
write-host -foregroundcolor Green "Applying final user settings and generating report..."
write-host "`r"
Start-Sleep -s 10
#Active Directory
write-host -foregroundcolor Green "Active Directory Details"
Get-ADUser $username -Server $DC
write-host "`r"
write-host "New user has been added to the following groups:" $RPTGroups
write-host "`r"
#Folders
write-host -foregroundcolor Green "User Directories"
write-host "`r"
write-host "Profile Path is " $win7Profile
write-host "Home Path is " $HomePath
write-host "`r"
#Exchange
write-host -foregroundcolor Green "Exchange Details"
Get-Mailbox $username -DomainController $DC
if ($EnableVoice -eq $true)
{
write-host -foregroundcolor Green "Unified Messaging Details"
get-ummailbox $username -DomainController $DC
}
#Lync
write-host -foregroundcolor Green "Lync Details"
Get-CSUser $username -DomainController $DC
#FINISH
#------
Stop-Transcript
#Email IT report
$MailSubject = "[AUTO] New account setup for " +$firstname+" "+$lastname
$MailBody = "A new user account has been setup for " +$firstname+" "+$lastname+", by "+$ScriptUserName+" on "+(get-date)+". `r
"+$firstname+" was setup with the following information:
Office: "+$office+"
Username: "+$username+"
First Name: "+$firstname+"
Last Name: "+$lastname+"
Initials: "+$initial+"
Departsment: "+$department+"
Role: "+$Role+"
Title: "+$title+"
Setup Same As: "+$SetupSameAs+"
Manager: "+$manager+"
Extension: "+$Extension+"
Mobile: "+$Mobile+"
`r
Please confirm these groups in AD (they have been copied from "+$SameAsDisplayName+", but may need to be changed) `n
"+$RPTGroups+"
`r
IT to complete the following items:
- Manual Steps 1 `r
- Manual Steps 2 `r
- Manual Steps 3 `r
`r
Regards
Admin Scripts"
Send-MailMessage -To $ScriptUserMail -cc $AdminEmail,$EmailCC1,$EmailCC2 -From "admin.scripts@domain.com.au" -Subject $MailSubject -SmtpServer $exchangeserver -body $MailBody -attachment $LogFile
#Pause for review, then load next line
write-host "`r"
write-host -foregroundcolor Green "User setup finished. Press any key to continue"
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
exit
|
PowerShellCorpus/GithubGist/jonforums_5080257_raw_3b6befffc826372fd54cf5eb8e7c0f7d29c13119_build_tcltk.ps1
|
jonforums_5080257_raw_3b6befffc826372fd54cf5eb8e7c0f7d29c13119_build_tcltk.ps1
|
#requires -version 2.0
# Author: Jon Maken
# License: 3-clause BSD
# Revision: 2013-03-04 18:48:14 -0600
#
# TODO:
# - extract generics into a downloadable utils helper module
# - add try-catch-finally error handling
# - add checkpoint support
# - support x86 and x64 builds (configure's --enable-64bit)
param(
[parameter(Mandatory=$true,
Position=0,
HelpMessage='TclTk version to build (eg - 8.6.0)')]
[alias('i')]
[string] $tcltk,
# TODO update to use DevKit's `provider-bits-version` syntax
[parameter(HelpMessage='mingw toolchain flavor to use (eg - mingw, mingw64)')]
[validateset('mingw','mingw64')]
[string] $toolchain = 'mingw',
[parameter(HelpMessage='Path to 7-Zip command line tool')]
[string] $7ZA = 'C:/tools/7za.exe',
[parameter(HelpMessage='Path to DevKit root directory')]
[string] $DEVKIT = 'C:/Devkit'
)
$msg_color = 'Yellow'
$root = split-path -parent $script:MyInvocation.MyCommand.Path
$source = @{tcl = "tcl${tcltk}-src.tar.gz"; tk = "tk${tcltk}-src.tar.gz"}
$repo_root = 'http://prdownloads.sourceforge.net/tcl/'
$archive = @{tcl = "${repo_root}$($source.tcl)"; tk = "${repo_root}$($source.tk)"}
#$archive_hash = "${repo_root}${source}.sha1"
# download and verify
# TODO implement progress bar when extracted to util helper module
if (-not ((test-path $source.tcl) -or (test-path $source.tk))) {
$client = new-object System.Net.WebClient
$client.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
#$hash = $client.DownloadString($archive_hash).Trim(" ","`r","`n").ToLower()
foreach ($src in $archive.keys) {
if (test-path $source[$src]) { continue }
write-host "[INFO] downloading $($archive[$src])" -foregroundcolor $msg_color
$client.DownloadFile($archive[$src], "$PWD/$($source[$src])")
}
<# TODO implement by embedding hash values as data into this file
$hasher = new-object System.Security.Cryptography.SHA1Managed
$fs = new-object System.IO.FileStream "$PWD/$source", 'Open', 'Read'
$test_hash = [BitConverter]::ToString($hasher.ComputeHash($fs)).Replace('-','').ToLower()
$fs.Close()
if ($test_hash -ne $hash) {
write-host "[ERROR] $source validation failed, exiting" -foregroundcolor 'Red'
break
}
#>
}
# extract
foreach ($tgz in $source.values) {
write-host "[INFO] extracting $tgz" -foregroundcolor $msg_color
$tar_file = "$($tgz.Substring(0, $tgz.LastIndexOf('-')))*.tar"
(& "$7ZA" "x" $tgz) -and (& "$7ZA" "x" $tar_file) -and (rm $tar_file) | out-null
}
# patch, configure, build, archive
foreach ($dir in "tcl${tcltk}", "tk${tcltk}") {
push-location $dir/win
# pre-configure patch - NA
# activate toolchain
# FIXME don't activate toolchain multiple times
write-host "[INFO] activating toolchain" -foregroundcolor $msg_color
. "$DEVKIT/devkitvars.ps1" | out-null
# configure
write-host "[INFO] configuring $dir" -foregroundcolor $msg_color
$clean_pwd = $(split-path $PWD -parent).Replace('\','/')
$install_dir = "$clean_pwd/my_install"
$cfg_args = "--prefix=$install_dir --enable-threads"
if ($dir -match '^tcl') { $tcl_build_dir = "$clean_pwd/win" }
if ($dir -match '^tk') { $cfg_args += " --with-tcl=$tcl_build_dir" }
sh -c "./configure $cfg_args" | out-null
# build
write-host "[INFO] building $dir" -foregroundcolor $msg_color
sh -c "make" | out-null
# install
sh -c "make install" | out-null
# archive
push-location "$install_dir"
write-host "[INFO] creating binary archive for $dir" -foregroundcolor $msg_color
$bin_archive = "${dir}-x86-windows-bin.7z"
& "7ZA" "a" "-mx=9" "-r" $bin_archive "*" | out-null
pop-location
# hoist binary archive to top level
mv "$install_dir\$bin_archive" $(split-path (split-path $PWD -parent) -parent)
pop-location
}
# cleanup
write-host "[INFO] cleaning up" -foregroundcolor $msg_color
foreach ($dir in "tcl${tcltk}", "tk${tcltk}") { rm -recurse -force $dir }
|
PowerShellCorpus/GithubGist/ovu_a65b11868d4e8e8078d9_raw_84847381a3a206dffc39719d832c0809d8368c76_gistfile1.ps1
|
ovu_a65b11868d4e8e8078d9_raw_84847381a3a206dffc39719d832c0809d8368c76_gistfile1.ps1
|
function prompt {
$gitbranch = & git rev-parse --abbrev-ref HEAD
if ($gitbranch) {
Write-Host $(Get-Location) -NoNewLine
Write-Host '[' -NoNewLine
Write-Host $gitbranch -NoNewLine -ForeGround 6
Write-Host ']' -NoNewLine
Write-Host ' ->' -NoNewLine -ForeGround Green
}
else {
Write-Host $(Get-Location) -NoNewLine
Write-Host ' ->' -NoNewLine -ForeGround Green
}
return ' '
}
|
PowerShellCorpus/GithubGist/GuruAnt_7215386_raw_5b414ed90b05d5566391e260c64a449dfd46335a_CheckIfServerOnListIsAVM.ps1
|
GuruAnt_7215386_raw_5b414ed90b05d5566391e260c64a449dfd46335a_CheckIfServerOnListIsAVM.ps1
|
# Check if Servers on Text List exist on VMware
# Assumes that the VM object name matches the server's DNS name
# Set this to the text file containing the list of servers, one per line
$strServerList = "C:\path\to\textFile.txt"
# Create empty array for servers which are found
$arrFoundServers = @()
# Assign all of the VM objects to a variable
$objVMs = Get-VM
# Read the list of servers, and assign it to a variable
$strServersOnList = (Get-Content -Path $serverlist)
# Loop through each VM
ForEach ($objVM in $objVMs){
# Loop through each server on the list
ForEach ($strServer in $strServersOnList){
# If the current VM object name matches the current item on the list
If ($objVM.Name -Like $strServer){
# Add it to the array of found machines
$arrFoundServers += $objVM
}
}
}
# Display the list of found machines
$arrFoundServers
|
PowerShellCorpus/GithubGist/Porkstone_3722751_raw_c957fedd3827e335ee1184a542bf1d81f2c62350_Search.ps1
|
Porkstone_3722751_raw_c957fedd3827e335ee1184a542bf1d81f2c62350_Search.ps1
|
# Example Usage:
# Search "*.cs" "classname"
function Search ($FileMask, $SearchString)
{
dir -filter $FileMask -recurse | select-string $SearchString
}
|
PowerShellCorpus/GithubGist/nzthiago_5899989_raw_a788e959d9f7d6912e0cec1bd9c8b4a7a9d0b165_downloadBUILD2013.ps1
|
nzthiago_5899989_raw_a788e959d9f7d6912e0cec1bd9c8b4a7a9d0b165_downloadBUILD2013.ps1
|
# Based on script from http://www.toddklindt.com/Scripts/downloadmp4-pptx.ps1.txt
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
$rss = (new-object net.webclient)
# Grab the RSS feed for the MP4 downloads
$a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/Build/2013/RSS/mp4high"))
# Walk through each item in the feed
$a.rss.channel.item | foreach{
$code = $_.comments.split("/") | select -last 1
# Grab the URL for the MP4 file
$url = New-Object System.Uri($_.enclosure.url)
# Create the PPTX URL from the MP4 URL
$urlpptx = ($_.enclosure.url).replace(".mp4",".pptx")
# Create the local file name for the MP4 download
$file = $code + "-" + $_.creator + "-" + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "") + ".mp4"
# Create the local file name for the PPTX download
$filepptx = $code + "-" + $_.creator + "-" + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "") + ".pptx"
# Make sure the PPTX file doesn't already exist
if (!(test-path $filepptx))
{
# Echo out the file that's being downloaded
$filepptx
$wc = (New-Object System.Net.WebClient)
# Download the PPTX file
$wc.DownloadFile($urlpptx, $filepptx)
}
# Make sure the MP4 file doesn't already exist
if (!(test-path $file))
{
# Echo out the file that's being downloaded
$file
# Download the MP4 file
$wc.DownloadFile($url, $file)
}
}
|
PowerShellCorpus/GithubGist/gpolitis_4371379_raw_95339e03af550083ccff5981b35b10a6dc4c3d85_gistfile1.ps1
|
gpolitis_4371379_raw_95339e03af550083ccff5981b35b10a6dc4c3d85_gistfile1.ps1
|
$cue = 'c:\Users\gp\example.cue'
$patt = '(?smi)TITLE\s"([^"]*)"(?:\n|\s)*PERFORMER\s*"([^"]*)"'
cat $cue -Raw |
sls -patt $patt -AllMatches |
% { $_.Matches } |
% { New-Object -Property @{ Title = $_.Groups[1].Value; Artist = $_.Groups[2].Value } } |
% { "\track {0} - {1}" -f $_.Artist, $_.Title }
|
PowerShellCorpus/GithubGist/zachbonham_4982148_raw_08da9b884b480aa5c008fee52cd2a6b191ce1694_driver.ps1
|
zachbonham_4982148_raw_08da9b884b480aa5c008fee52cd2a6b191ce1694_driver.ps1
|
$arg1 = "hello1"
$arg2 = "hello2"
$p = $(start-process -filepath .\bin\debug\hello.exe -argumentlist $arg1 -nonewwindow -passthru; start-process -filepath .\bin\debug\hello.exe -argumentlist $arg2 -nonewwindow -passthru);
#$p | wait-process
[console]::TreatControlCAsInput = $true
while($true)
{
if ( [console]::KeyAvailable )
{
$key = [system.console]::readkey($true)
if(($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C"))
{
"shutting down"
$p | % { $_.Kill() }
break;
}
}
}
|
PowerShellCorpus/GithubGist/mwrock_481048e7de5074e38b7f_raw_d0b9057164e085c50e4d2ef6e736a5eba2e6d06c_nuspec.ps1
|
mwrock_481048e7de5074e38b7f_raw_d0b9057164e085c50e4d2ef6e736a5eba2e6d06c_nuspec.ps1
|
@{
version = '11.0.1'
authors = @('Microsoft')
owners = @('Matt Wrock')
projectUrl = 'http://www.microsoft.com/visualstudio/11/en-us'
licenseUrl = 'http://msdn.microsoft.com/en-US/cc300389.aspx'
iconUrl = 'https://github.com/mwrock/Chocolatey-Packages/raw/master/VisualStudio2012Ultimate/vs.png'
id = 'VisualStudio2012Professional'
title = 'Visual Studio 2012 - Professional'
requireLicenseAcceptance = $false
description = @"
This silently installs the 90 day trial (http://msdn.microsoft.com/en-us/library/gg442061.aspx) of Visual Studio Professional along with the Microsoft .Net 4.5 Framework SDK. All Optional Features such as Blend, Sql Dev tools, Web dev tools, etc. are not installed. However, from the "Programs and Features" menu in Windows you can right click Microsoft Visual Studio Ultimate and choose "Change" and then add the features you want. This may take quite a while to install so grab your Lord of the Rings Battle Axe and re-enact the battle of Isengard while you wait!
"@
summary = @"
Professional developers need professional tools. Visual Studio Professional 2012 is a unified development experience that enables developers to create multi-tier applications across the web, cloud, and devices.
"@
# a tag for each word
tags = "Microsoft Visual Studio 2012 Professional IDE ALM".Split(" ")
dependencies = @( @{ id="DotNet4.5" } )
}
|
PowerShellCorpus/GithubGist/mbrownnycnyc_6511499_raw_dfcea19a047e7c55bbf1140b0e31b8c81596f148_uninstall_string_getter.ps1
|
mbrownnycnyc_6511499_raw_dfcea19a047e7c55bbf1140b0e31b8c81596f148_uninstall_string_getter.ps1
|
$global:debug = $false
$global:debugverbose = $false
Function GetUninstallString([string]$computername, $displayname)
{
try {
#first, we'll grab a collection of key names below HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for 64 bit
#we'll search for the DisplayName...
#if found, we'll query for the UninstallString and we'll stop looking
write-host "Getting UninstallString. This may take a moment..." -backgroundcolor "DarkYellow"
write-host "Enumerating 64-bit HKLM keys (or 32-bit keys if the host process is 32-bit)..." -backgroundcolor "DarkYellow"
$keynames = GetValueFromRegistryThruWMI "enumkey" "64" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" ""
foreach ( $key in $keynames) {
$dname = GetValueFromRegistryThruWMI "GetStringValue" "64" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "DisplayName"
if ( $dname -ne $false -and $dname.contains($displayname) ) {
$uninstallstring = GetValueFromRegistryThruWMI "GetStringValue" "64" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "UninstallString"
write-host "Got it... $uninstallstring" -backgroundcolor "darkgreen"
write-host "Passing it to the chocolatey gods for sacrifice..." -backgroundcolor "darkgreen"
return $uninstallstring
}
}
#then, we'll grab a collection of key names below HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for 32 bit
#we'll search for the DisplayName... if found, we'll query for the UninstallString and we'll stop looking
write-host "Enumerating 32-bit HKLM keys..." -backgroundcolor "DarkYellow"
write-host "Don't you just wish you had installed that 64-bit version now? C'mon! Quantum computing is almost here!" -backgroundcolor "DarkYellow"
$keynames = GetValueFromRegistryThruWMI "enumkey" "32" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" ""
foreach ( $key in $keynames) {
$dname = GetValueFromRegistryThruWMI "GetStringValue" "32" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "DisplayName"
if ( $dname -ne $false -and $dname.contains($displayname) ) {
$uninstallstring = GetValueFromRegistryThruWMI "GetStringValue" "32" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "UninstallString"
write-host "Got it... $uninstallstring" -backgroundcolor "darkgreen"
write-host "Passing it to the chocolatey gods for sacrifice..." -backgroundcolor "darkgreen"
return $uninstallstring
}
}
#then, we'll grab a collection of key names below HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for 64 bit
#we'll search for the DisplayName... if found, we'll query for the UninstallString and we'll stop looking
write-host "Enumerating 64-bit HKCU keys (or 32-bit keys if the host process is 32-bit)" -backgroundcolor "DarkYellow"
write-host "What great times we're having, huh?" -backgroundcolor "DarkYellow"
$keynames = GetValueFromRegistryThruWMI "enumkey" "64" "localhost" "HKCU" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" ""
foreach ( $key in $keynames) {
$dname = GetValueFromRegistryThruWMI "GetStringValue" "64" "localhost" "HKCU" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "DisplayName"
if ( $dname -ne $false -and $dname.contains($displayname) ) {
$uninstallstring = GetValueFromRegistryThruWMI "GetStringValue" "64" "localhost" "HKcU" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "UninstallString"
write-host "Got it... $uninstallstring" -backgroundcolor "darkgreen"
write-host "Passing it to the chocolatey gods for sacrifice..." -backgroundcolor "darkgreen"
return $uninstallstring
}
}
#then, we'll grab a collection of key names below HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall for 32 bit
#we'll search for the DisplayName... if found, we'll query for the UninstallString and we'll stop looking
write-host "Enumerating 32-bit HKCU keys " -backgroundcolor "DarkYellow"
write-host "The pain is almost over." -backgroundcolor "DarkYellow"
$keynames = GetValueFromRegistryThruWMI "enumkey" "32" "localhost" "HKCU" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" ""
foreach ( $key in $keynames) {
$dname = GetValueFromRegistryThruWMI "GetStringValue" "32" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "DisplayName"
if ( $dname -ne $false -and $dname.contains($displayname) ) {
$uninstallstring = GetValueFromRegistryThruWMI "GetStringValue" "32" "localhost" "HKLM" "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$key" "UninstallString"
write-host "Got it... $uninstallstring" -backgroundcolor "darkgreen"
write-host "Passing it to the chocolatey gods for sacrifice..." -backgroundcolor "darkgreen"
return $uninstallstring
}
}
throw "Couldn't find $displayname as a DIsplayName or couldn't find the DisplayName's UninstallString below Uninstall."
}
catch {
return $error[0]
}
}
Function GetValueFromRegistryThruWMI([string]$stdregprovmethod, $providerarchtoget, [string]$computername, $regtree, $regkey, $value)
{
try{
$stdregprovmethod = $stdregprovmethod.tostring().tolower()
#these are all the available methods for stdregprov: http://msdn.microsoft.com/en-us/library/aa393664%28v=vs.85%29.aspx
$supportedstdregprovmethods = 'enumkey','enumvalues','getstringvalue'
#$allstdregprovmethods = 'checkaccess','createkey','deletekey','deletevalue','enumkey','enumvalues','getbinaryvalue','getdwordvalue','getexpandedstringvalue','getmultistringvalue','getstringvalue','setbinaryvalue','setdwordvalue','setexpandedstringvalue','setmultistringvalue','setstringvalue','#these are not supported in windows version 5.x.x (<=2003/xp)','getqwordvalue','getsecuritydescriptor','setqwordvalue','setsecuritydescriptor'
if ( $supportedstdregprovmethods -notcontains $stdregprovmethod ) {
write-host You have provided a StrRegProv Method that is not supported yet.
write-host enumkey will be used instead.
$stdregprovmethod = 'enumkey'
}
else {
}
switch ($regtree)
{
#constant uints for registry trees
HKCR { $regtree = "&h80000000" }
HKCU { $regtree = "&h80000001" }
HKLM { $regtree = "&h80000002" }
HKU { $regtree = "&h80000003" }
#more obscure trees: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724836%28v=vs.85%29.aspx
HKPerformanceData { $regtree = "&h80000004" } # http://msdn.microsoft.com/en-us/library/windows/desktop/aa373219%28v=vs.85%29.aspx
HKCurrentConfig { $regtree = "&h80000005" }
HKCULocalSettings { $regtree = "&h80000007" }
default { $regtree = "&h80000002" }
}
$objNamedValueSet = New-Object -COM "WbemScripting.SWbemNamedValueSet"
if ( $providerarchtoget -eq 32 ) {
if ( [IntPtr]::size -eq 8 -and (test-path env:\PROCESSOR_ARCHITEW6432) ) {
if ($debugverbose) { write-host process arch is 64-bit, querying 32-bit provider as requested. }
$objNamedValueSet.Add("__ProviderArchitecture", 32) | Out-Null
}
elseif ( [IntPtr]::size -eq 4 ) {
if ($debugverbose) { write-host process arch is 32-bit, querying 32-bit provider. }
$objNamedValueSet.Add("__ProviderArchitecture", 32) | Out-Null
}
}
elseif ( $providerarchtoget -eq 64 ) {
if ( [IntPtr]::size -eq 8 -and (test-path env:\PROCESSOR_ARCHITEW6432) ) {
if ($debugverbose) { write-host process arch is 64-bit, querying 64-bit provider as requested. }
$objNamedValueSet.Add("__ProviderArchitecture", 64) | Out-Null
}
elseif ( [IntPtr]::size -eq 4 ) {
if ($debugverbose) { write-host process arch is 32-bit, querying 64-bit provider. }
$objNamedValueSet.Add("__ProviderArchitecture", 64) | Out-Null
}
}
else {
if ($debug) { write-host You have requested an architecture that is not handled. Please provide "32" or "64" as your first parameter. }
return
}
$objLocator = New-Object -COM "Wbemscripting.SWbemLocator"
$objServices = $objLocator.ConnectServer($computername,"root\default","","","","","",$objNamedValueSet)
$objStdRegProv = $objServices.Get("StdRegProv")
$Inparams = ($objStdRegProv.Methods_ | where {$_.name -eq $stdregprovmethod}).InParameters.SpawnInstance_()
if ($stdregprovmethod -eq "getstringvalue") {
if ($debugverbose) { write-host getting string value $regtree $regkey : $value }
($Inparams.Properties_ | where {$_.name -eq "Hdefkey"}).Value = $regtree
($Inparams.Properties_ | where {$_.name -eq "Ssubkeyname"}).Value = $regkey
($Inparams.Properties_ | where {$_.name -eq "Svaluename"}).Value = $value
$Outparams = $objStdRegProv.ExecMethod_("GetStringValue", $Inparams, "", $objNamedValueSet)
if (($Outparams.Properties_ | where {$_.name -eq "ReturnValue"}).Value -eq 0) {
$result = ($Outparams.Properties_ | where {$_.name -eq "sValue"}).Value
if ($debugverbose) { write-host '$result of GetStringValue: ' $result }
return $result
}
else{
if ($debugverbose) { write-host '$result of GetStringValue: ' $false }
return $false
}
}
elseif ($stdregprovmethod -eq "enumkey") {
if ($debug) { write-host enuming keys below $regtree : $regkey }
($Inparams.Properties_ | where {$_.name -eq "Hdefkey"}).Value = $regtree
($Inparams.Properties_ | where {$_.name -eq "Ssubkeyname"}).Value = $regkey
$Outparams = $objStdRegProv.ExecMethod_("EnumKey", $Inparams, "", $objNamedValueSet)
if (($Outparams.Properties_ | where {$_.name -eq "ReturnValue"}).Value -eq 0) {
$result = ($Outparams.Properties_ | where {$_.name -eq "sNames"}).Value
if ($debugverbose) { write-host '$result of EnumKey: ' $result }
return $result
}
else{
if ($debugverbose) { write-host '$result of EnumKey: ' $false }
return $false
}
}
}
catch {
$error[0]
}
}
$packageName = 'desktoprestore'
$fileType = 'MSI'
$silentArgs = '/x','/quiet', '/passive' #in this case, this must be an array instead of a string. We will expand during execution.
#not ready as of September 9th, 2013:
#Uninstall-ChocolateyPackage $packageName $fileType $silentArgs $filePath
$filePath = GetUninstallString localhost "Desktop Restore"
#We must parse the returned UninstallString and modify it, consider $fileType and $silentArgs
#let's take the example:
#$filePath = "MsiExec.exe /I{228CEA74-6DD1-40B9-B95F-77273F4316B5}"
#or this
#$filePath = "MsiExec.exe /xribbit11-.3adf.msi"
if ( $fileType -eq "MSI" ) {
#With MSIs, some UninstallString REG_SZs will contain the `/I{Product GUID}` which brings up the installer configuration screen for the installed product.
#There are three scenarios for an UninstallString that we are concerned with that will trigger an uninstall:
# `/x[Product GUID]`
# `/x[product.msi]`
# any arbitrary string that doesn't contain /i or /x (could be an exe)
#our primary step will be to isolate the Product GUID:
# (by the way, we get the product guid by querying the registry, but why would we perform more costly work again...
# We already queried the registry to deal with the condition that we aren't dealing with an MSI.)
# We will find the Product GUID by searching for the [0-9][a-z][a-Z] between '{' and '}' which is empirically stable.
if ( $filePath -match '{.*}' ) { $productGUID = $matches[0].tolower() }
#even if this $productGUID winds up being "", we can still search for other things:
#If the UninstallString contains '/x$productGUID'
# or if it contains
# '/x', followed by any character, followed by '.msi', followed by an end of line character, followed by whitespace, followed by any character.
# and
# any character, followed by any invalid character, followed by any character
# or if it doesn't contain '/x' or '/i'
#http://msdn.microsoft.com/en-us/library/aa365247.aspx
if ( $filePath.tolower() -match "/x$productGUID" -or (
$filePath.tolower() -match "/x.*.msi[$\s]*" -and
$filePath.tolower() -notmatch ".*[" + [regex]::Escape([System.IO.Path]::InvalidPathChars -join "") + "].*"
) -or (
-not $filePath.tolower() -match "/x" -or
-not $filePath.tolower() -match "/i"
)
) {
#then we can just run it as is. It contains the one of the uninstall commands ("/x$productGUID" or "/xproduct.msi") or it could be an EXE or something else [see pdfcreator for an example of this instance].
if ($debug) { write-host running "$filePath"}
(Start-Process -FilePath "$filePath" -Wait -Passthru).ExitCode
}
else {
#We'll gather up the switches, then we'll verify each as okay (only allow $silentArgs, except "/x" which requires more things)
# a switch is defined as any string that starts with a '/' that is followed by '[a-zA-Z]' then followed by parameters
# this excludes the /log switch as it can contain a parameter... maybe later...
# we can exclude the `/x` switch from this check as it was already handled in this conditional
$filePath -split "/" | foreach-object {
if ( $_ -ne "x") {
if ($silentArgs -match [regex]::Escape( $_.trim() ) ) {
[string[]]$matchedsilentargs += $_
}
}
}
foreach ($silentArg in $silentArgs) {
if ( $silentArg -ne "/x") {
[string[]]$matchedsilentargs += $silentArg
}
}
#Now, let's add /x$productGUID to $silentArgs. It wasn't already there, or the original condition (above) would have covered it.
#we might still only be dealing with "/x" $silentArgs
$silentArgs = "/x$productGUID " + ($matchedsilentargs)
#now we can execute it with the $silentArgs
if ($debug) { write-host running "msiexec.exe " $silentArgs }
(Start-Process -FilePath "msiexec.exe" -ArgumentList "$silentArgs" -Wait -Passthru).ExitCode
}
}
else {
#file type isn't MSI
#We'll gather up the switches, then we'll verify each as okay (only allow $silentArgs)
# a switch is defined as any string that starts with a '/' that is followed by '[a-zA-Z]' then followed by parameters
# this excludes any switch that takes in a parameter... maybe later...
$filePath -split "/" | foreach-object {
if ( $silentArgs -match [regex]::Escape( $_.trim() ) ) {
if ($debug) { write-host "adding to the array " $_ }
[string[]]$matchedsilentargs += $_
}
}
$silentArgs = ([string[]]$matchedsilentargs -join " /")
write-host running "$filePath" $silentArgs
(Start-Process -FilePath "msiexec.exe" -ArgumentList "$silentArgs" -Wait -Passthru).ExitCode
}
|
PowerShellCorpus/GithubGist/guitarrapc_2b1871a54ffe786c6b36_raw_de0c2c18db7a23a06ac0a13fb231884d5635be2b_RunwithConfiguraionData.ps1
|
guitarrapc_2b1871a54ffe786c6b36_raw_de0c2c18db7a23a06ac0a13fb231884d5635be2b_RunwithConfiguraionData.ps1
|
Service -ConfigurationData $configuraionData -OutputPath service
|
PowerShellCorpus/GithubGist/jpoehls_1077968_raw_a85260997a1440f85097445374163947bf8b2113_Hg-Export.ps1
|
jpoehls_1077968_raw_a85260997a1440f85097445374163947bf8b2113_Hg-Export.ps1
|
function Hg-Export([string]$Path) {
<#
.SYNOPSIS
Exports all uncommitted changes in the current HG repository
to a git formatted diff file at the specified path.
The resultant diff file can be re-imported into a repo using: hg import changes.diff
.EXAMPLE
Hg-Export changes.diff
# equivelant to: hg diff --git | Out-File changes.diff -Encoding ASCII; hg diff --stat
#>
hg diff --git | Out-File $Path -Encoding UTF8
hg diff --stat
}
|
PowerShellCorpus/GithubGist/guitarrapc_128716059fee41846e8f_raw_6f9b25604ecaef2aec5d4ab843d09bfd30129d14_ConfigurationUserAndGroupSample.ps1
|
guitarrapc_128716059fee41846e8f_raw_6f9b25604ecaef2aec5d4ab843d09bfd30129d14_ConfigurationUserAndGroupSample.ps1
|
Configuration Remote
{
param
(
[Parameter(Mandatory = 1, Position = 0)]
[pscredential]$Credential
)
User Remote
{
UserName = $Credential.UserName
Ensure = "Present"
Password = $Credential
Disabled = $false
PasswordNeverExpires = $true
}
Group Remote
{
GroupName = "RemoteUser"
Ensure = "Present"
MembersToInclude = $Credential.UserName, "Administrators"
DependsOn = "[User]Remote"
}
}
|
PowerShellCorpus/GithubGist/togakangaroo_7357291_raw_a210e92ef70c9cbd00aa7680f8c1d308b4789d7e_Transfer-SvnToHgCommits.ps1
|
togakangaroo_7357291_raw_a210e92ef70c9cbd00aa7680f8c1d308b4789d7e_Transfer-SvnToHgCommits.ps1
|
<#
.SYNOPSIS
Check out a range of Subversion revisions and recommit them to Mercurial
.DESCRIPTION
In the case where you already have an svn and an hg repository and you are transferring commits from one to the other (this is relevant when slowly transitioning svn to hg) you might get in a situation where several commits are made to the svn repository but not to the hg one. In this case you might want to check these out of svn one by one and re-commit to mercurial. This script automates the process.
This script requires an svn and an hg command to exist in your powershell environment. You can do this (assuming Tortoise) by adding 'C:\Program Files\TortoiseSVN\bin' and 'C:\Program Files\TortoiseHg' to your PATH or setting up the appropriate aliases.
.PARAMETER FromRevision
SVN revision to start checking out at.
.PARAMETER FromRevision
SVN revision to stop checking out at.
.PARAMETER NoConfirm
Do not ask for confirmation between each commit
#>
param(
[Parameter(Mandatory=$true)][int]$FromRevision,
[Parameter(Mandatory=$true)][int]$ToRevision,
[switch]$NoConfirm
)
if(-not (Get-Command svn)) { throw "Expected a globally available svn command" }
if(-not (Get-Command hg)) { throw "Expected a globally available hg command" }
if(-not ($FromRevision -le $ToRevision) ) { throw "FromRevision must be less than ToRevision" }
"Removing any mq patches"
hg qpop -a
foreach($revision in $FromRevision..$ToRevision) {
Write-Host "importing $revision"
if( (hg status) ) { throw "There are uncommited mercurial changes" }
svn update --revision $revision
$log = (svn log --revision $revision)
$msg = "Import from svn r$revision - $log".replace('"', "'")
if( -not (hg status) ) { throw "No changes detected" }
Write-Host $msg
if(-not $NoConfirm) {
$continue = Read-Host "Commit into Hg? (Y/N)"
if("Y" -ne $continue) { exit }
}
hg addremove
hg commit -m $msg
}
|
PowerShellCorpus/GithubGist/johnkors_5501060_raw_8c2df4c7abf4c584333513e345948cf3763d9d09_gistfile1.ps1
|
johnkors_5501060_raw_8c2df4c7abf4c584333513e345948cf3763d9d09_gistfile1.ps1
|
# helper to update ps sessions env variables
function Update-Environment {
$locations = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
'HKCU:\Environment'
$locations | ForEach-Object {
$k = Get-Item $_
$k.GetValueNames() | ForEach-Object {
$name = $_
$value = $k.GetValue($_)
if ($userLocation -and $name -ieq 'PATH') {
Env:\Path += ";$value"
} else {
Set-Item -Path Env:\$name -Value $value
}
}
$userLocation = $true
}
}
# Needed to run remote scripts
Set-ExecutionPolicy Unrestricted
# Install Chocolatey
$chocolateyInstallScriptUrl = "https://raw.github.com/chocolatey/chocolatey/master/chocolateyInstall/InstallChocolatey.ps1"
iex ((new-object net.webclient).DownloadString($chocolateyInstallScriptUrl))
write-host "**** INSTALLED CHOCOLATEY *****"
# Install node.js via Chocolatey
& cinst NodeJs.install
write-host "**** INSTALLED NODE.JS *****"
# Update Env variables in session so npm is available
Update-Environment
# Install karma test-runner from node package manager (npm) into global node_modules
& powershell -command {npm install -g karma}
write-host "**** INSTALLED KARMA *****"
# Set ENV variables for browsers, due to a bug in karma on Windows:
$CHROME_BIN = "C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe"
$FIREFOX_BIN = "C:\Program Files (x86)\Mozilla Firefox\Firefox.exe"
[Environment]::SetEnvironmentVariable("CHROME_BIN", $CHROME_BIN, "User")
[Environment]::SetEnvironmentVariable("FIREFOX_BIN", $FIREFOX_BIN, "User")
write-host "**** ADDED BROWSERS TO USER ENV VARIABLES *****"
|
PowerShellCorpus/GithubGist/grenade_7639518_raw_21ca05278888283075da5b28dca295ff470f35b6_EnablePowerShellNet4.ps1
|
grenade_7639518_raw_21ca05278888283075da5b28dca295ff470f35b6_EnablePowerShellNet4.ps1
|
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsIdentity)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
if (!($windowsPrincipal.IsInRole($adminRole))) {
$psi = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$psi.Arguments = $myInvocation.MyCommand.Definition;
$psi.Verb = "runas";
[System.Diagnostics.Process]::Start($psi);
exit
}
$psconfig = "{0}\powershell.exe.config" -f $pshome
if(!(Test-Path -Path ($psconfig)))
{
$config =
@"
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0.30319"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>
"@
New-Item -Path $psconfig –type file -value ($config)
}
|
PowerShellCorpus/GithubGist/vScripter_84faa2dd6a7c0a9ae105_raw_cbaecdceb08bcf730521e78bb37fa1d7d13fff58_Set-ConsoleWindowTitle.ps1
|
vScripter_84faa2dd6a7c0a9ae105_raw_cbaecdceb08bcf730521e78bb37fa1d7d13fff58_Set-ConsoleWindowTitle.ps1
|
function Set-ConsoleWindowTitle {
[cmdletbinding()]
param (
[parameter(Mandatory = $true,
Position = 0,
ParameterSetName = 'Default')]
[validateset("Default", "Custom")]
[string]$MessageType,
[parameter(Mandatory = $false,
Position = 1,
ParameterSetName = 'Default')]
[string]$Message
) # param
BEGIN {
$defaultTitle = $host.ui.RawUI.WindowTitle = "$env:COMPUTERNAME - $env:USERNAME"
} # BEGIN
PROCESS {
switch ($MessageType) {
'Default' {
if ($host.Name -eq 'ConsoleHost') {
$host.ui.RawUI.WindowTitle = $defaultTitle
} # end if
} # Default
'Custom' {
if ($host.Name -eq 'ConsoleHost') {
$host.ui.RawUI.WindowTitle = $Message
} # end if
} # Custom
} # switch
} # PROCESS
} # function Set-ConsoleWindowTitle
|
PowerShellCorpus/GithubGist/MatthewKing_6374590_raw_73573089ca242ce2d947b3e982ca20829a524291_count-loc.ps1
|
MatthewKing_6374590_raw_73573089ca242ce2d947b3e982ca20829a524291_count-loc.ps1
|
(Get-ChildItem -include *.cs -recurse | Select-String .).Count
|
PowerShellCorpus/GithubGist/antonydenyer_6087279_raw_1dbe68be9b19e039958b74e2dfd2a78565b885b4_OctoChef.ps1
|
antonydenyer_6087279_raw_1dbe68be9b19e039958b74e2dfd2a78565b885b4_OctoChef.ps1
|
param(
[parameter(Mandatory = $true)]
$packageName
)
$currentDirectory=$pwd
function CreateTempDir
{
$tmpDir = [System.IO.Path]::GetTempPath()
$tmpDir = [System.IO.Path]::Combine($tmpDir, [System.IO.Path]::GetRandomFileName())
[System.IO.Directory]::CreateDirectory($tmpDir) | Out-Null
$tmpDir
}
$tmpDir = CreateTempDir
$temp_file = [System.IO.Path]::Combine($tmpDir,"install.zip")
write-host $packageName
$nugetFeed = 'http://teamcity/guestAuth/app/nuget/v1/FeedService.svc/'
$url = $nugetFeed + 'Packages()?$filter=tolower(Id)%20eq%20''' + $packageName + '''&$orderby=Id'
write-host "Querying teamcity with $url"
$response = (Invoke-RestMethod -uri $url)
$url = $response[$response.Count - 1].content.src
write-host "Downloading package from $url to $tmpDir"
$client = new-object System.Net.WebClient
$client.DownloadFile($url, $temp_file)
(new-object -com shell.application).namespace($tmpDir).CopyHere((new-object -com shell.application).namespace($temp_file).Items(),16)
cd $tmpDir
.\tools\Deploy.ps1
cd $currentDirectory
|
PowerShellCorpus/GithubGist/Romoku_4004215_raw_d5ce9a20b20ee459e5ff52d49bbefa1dc0057ce2_utorrent.ps1
|
Romoku_4004215_raw_d5ce9a20b20ee459e5ff52d49bbefa1dc0057ce2_utorrent.ps1
|
param(
[String]$filePath="",
[String]$fileName=""
)
$encoderDirectory = "c:\temp\done"
$encoder = "C:\temp\done\sample.bat"
$extension = "*.jnt"
Function StripChar($s)
{
$s.replace(" ","_").replace(",","_").replace("~","_").replace("#", "_")
}
Function MoveFile($filePath, $fileName)
{
$newPath = "${encoderDirectory}\${fileName}"
[System.IO.File]::Move($filePath, $newPath)
}
Function StartEncoding($fileName) {
Start-Process $encoder $fileName
}
if($fileName -and $filePath)
{
$fileFullName = "${filePath}\${fileName}"
$fixedFileName = StripChar $fileName
MoveFile $fileFullName $fixedFileName
$encoderPath = "${encoderDirectory}\${fixedFileName}"
StartEncoding $encoderPath
}
|
PowerShellCorpus/GithubGist/weipah_4169900_raw_a7093ffe35f4f15b3050b787350386fa42a4bbf6_findUserOnTerminalServer.ps1
|
weipah_4169900_raw_a7093ffe35f4f15b3050b787350386fa42a4bbf6_findUserOnTerminalServer.ps1
|
#require -version 2.0
# based on source from: http://www.nivot.org/blog/post.aspx?id=1f8255b2-05a7-4947-8dc3-01ce3c478cc2
# does not really work, because the waithandle is not processed correctly
# using $wait[$i].WaitOne() in for-loop would work, but is not the right way to process jobs in parallel
# create a pool of 10 runspaces
$pool = [runspacefactory]::CreateRunspacePool(1,10)
$pool.Open()
write-host "Available Runspaces: $($pool.GetAvailableRunspaces())"
$jobs = @()
$pipes = @()
$wait = @()
$file = "C:\Users\adm-ml\Documents\WindowsPowerShell\Modules\PSTerminalServices\aco-terminal-servers.txt"
$location = (get-location)
# run multiple background pipelines
$servers = (Get-Content $file)
for ($i=0; $i -lt $servers.count; $i++) {
# create a "powershell pipeline runner"
[PowerShell]$ps = [powershell]::create()
# assign our pool of runspaces to use
$ps.runspacepool = $pool
# Add commands to pipeline
#[String]$command = "param($servername) Import-Module PSTerminalServices; get-tssession -ComputerName $servername -State active -Username mlenhardt;"
# [Scriptblock]$ScriptBlock = [ScriptBlock]::Create($command)
[ScriptBlock]$ScriptBlock = {
param([String]$servername)
set-location C:\Users\adm-ml\Documents\WindowsPowerShell
Import-Module PSTerminalServices;
get-tssession -Computername $servername -Username mlenhardt;
}
[void]$ps.AddScript($ScriptBlock).AddArgument($servers[$i])
# Organize pipelines in an Array
$pipes += $ps
#[void]$pipes[$i].AddScript($ScriptBlock)
$jobs += $pipes[$i].BeginInvoke();
write-host "Available runspaces: $($pool.GetAvailableRunspaces())"
# store wait handles for WaitForAll call
$wait += $jobs[$i].AsyncWaitHandle
[System.Threading.WaitHandle]::WaitAll($wait)
}
# wait 20 seconds for all jobs to complete, else abort
#$success = [System.Threading.WaitHandle]::WaitAll($wait)
write-host "All completed? $success"
# End asynchronous call..
# create array to receive results for each job
[PSObject]$result = @()
for ($i = 0; $i -lt $servers.count; $i++) {
write "Job $($i): $($jobs[$i].iscompleted)"
try {
write "receive results for job $($i)"
$result += $pipes[$i].endinvoke($jobs[$i])
write "-- end result --"
} catch {
# Catch-Error...
write-warning "error: $_"
}
# info about completed pipelines
#$info = $pipes[$i].InvocationStateInfo
#write-host "State: $($info.state) ; Reason: $($info.reason)"
}
# all runspaces should be available again...
write-host "Available runspaces: $($pool.GetAvailableRunspaces())"
|
PowerShellCorpus/GithubGist/johnmiller_172753ed0adaca866a81_raw_f9245e2dafa390d7fb581dc2ce276eae85c4077a_show-all-project-branches.ps1
|
johnmiller_172753ed0adaca866a81_raw_f9245e2dafa390d7fb581dc2ce276eae85c4077a_show-all-project-branches.ps1
|
function show-all-project-branches
{
$Workspace = "C:\Workspace\"
$InitialLocation = Get-Location
function show-repo-branch($dir)
{
$GitDir = $dir.FullName + "\.git"
$IsRepository = Test-Path $GitDir
if (!$IsRepository) { return }
cd $dir.FullName
$CurrentBranch = git rev-parse --abbrev-ref HEAD
Write-Host "$dir`: $CurrentBranch"
}
Get-ChildItem -Directory $Workspace | foreach { show-repo-branch($_); }
cd $InitialLocation
}
|
PowerShellCorpus/GithubGist/constructor-igor_18e88b456833f3dc9d7f_raw_d8dd8b7db56cf576250b7bc9980af5d6792390f7_gistfile1.ps1
|
constructor-igor_18e88b456833f3dc9d7f_raw_d8dd8b7db56cf576250b7bc9980af5d6792390f7_gistfile1.ps1
|
#
# sample:
#$title = "MyChart"
#$size = "700x350"
#$url = CreateChartUrl $valueArray $labelArray $title $size
#
function CreateChartUrl ($valueArray, $labelArray, [string]$title, $size) {
$chartType = "lc"
$chartData = [string]::join(",", $valueArray)
$chartLabel = [string]::join("|", $labelArray)
Write-Output "http://chart.apis.google.com/chart?chtt=$title&cht=$chartType&chd=t:$chartdata&chs=$size&chl=$chartLabel&chds=a&chxt=y"
}
|
PowerShellCorpus/GithubGist/Yoos01_a1fe1784362d7b8042d1_raw_d5c19e49df8c42fb5f3927cc40000f1182e852b0_gistfile1.ps1
|
Yoos01_a1fe1784362d7b8042d1_raw_d5c19e49df8c42fb5f3927cc40000f1182e852b0_gistfile1.ps1
|
#Script principale
write-host "Renommage du poste"
$Answer="n"
Do{
$CompName = read-host "Veuillez saisir le nom du poste"
Write-Host "Vous avez saisis comme nom de poste : $CompName"
$Answer = read-host "Voulez vous poursuivre y/n ?"
}while ($Answer -ne "y" -and $Answer -ne "Y")
RenameComputer -ComputerName $CompName
## Fonction
function RenameComputer {
[CmdletBinding()]
param (
[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[string[]]$hostname=$env:computername,
[parameter(Mandatory=$true)]
[string]$ComputerName
)
Rename-computer -NewName $ComputerName -LocalCredential $env:ComputerName\Jeremie -Confirm
}
|
PowerShellCorpus/GithubGist/andreaswasita_71eb3894abf4379b3b7e_raw_e959ba34f90a3bb0c54d59455e3095cfa76bd8f7_Add-AzureVMAntiMalware.ps1
|
andreaswasita_71eb3894abf4379b3b7e_raw_e959ba34f90a3bb0c54d59455e3095cfa76bd8f7_Add-AzureVMAntiMalware.ps1
|
$service= "AzureVMAntiMalware"
$name = "MyAzureVM01"
# Get the Azure VM
$vm = Get-AzureVM –ServiceName $service –Name $name
# Add Microsoft Antimalware Agent to Azure VM
Set-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -VM $vm.VM
# Update the VM which will install the Antimalware Agent
Update-AzureVM -Name $name -ServiceName $service -VM $vm.VM
|
PowerShellCorpus/GithubGist/yogex_2857140_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
|
yogex_2857140_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
|
# SSH Agent Functions
# Mark Embling (http://www.markembling.info/)
#
# How to use:
# - Place this file into %USERPROFILE%\Documents\WindowsPowershell (or location of choice)
# - Import into your profile.ps1:
# e.g. ". (Resolve-Path ~/Documents/WindowsPowershell/ssh-agent-utils.ps1)" [without quotes]
# - Enjoy
#
# Note: ensure you have ssh and ssh-agent available on your path, from Git's Unix tools or Cygwin.
# Retrieve the current SSH agent PId (or zero). Can be used to determine if there
# is an agent already starting.
function Get-SshAgent() {
$agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "User")
if ([int]$agentPid -eq 0) {
$agentPid = [Environment]::GetEnvironmentVariable("SSH_AGENT_PID", "Process")
}
if ([int]$agentPid -eq 0) {
0
} else {
# Make sure the process is actually running
$process = Get-Process -Id $agentPid -ErrorAction SilentlyContinue
if(($process -eq $null) -or ($process.ProcessName -ne "ssh-agent")) {
# It is not running (this is an error). Remove env vars and return 0 for no agent.
[Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process")
[Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User")
[Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process")
[Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User")
0
} else {
# It is running. Return the PID.
$agentPid
}
}
}
# Start the SSH agent.
function Start-SshAgent() {
# Start the agent and gather its feedback info
[string]$output = ssh-agent
$lines = $output.Split(";")
$agentPid = 0
foreach ($line in $lines) {
if (([string]$line).Trim() -match "(.+)=(.*)") {
# Set environment variables for user and current process.
[Environment]::SetEnvironmentVariable($matches[1], $matches[2], "Process")
[Environment]::SetEnvironmentVariable($matches[1], $matches[2], "User")
if ($matches[1] -eq "SSH_AGENT_PID") {
$agentPid = $matches[2]
}
}
}
# Show the agent's PID as expected.
Write-Host "SSH agent PID:", $agentPid
}
# Stop a running SSH agent
function Stop-SshAgent() {
[int]$agentPid = Get-SshAgent
if ([int]$agentPid -gt 0) {
# Stop agent process
$proc = Get-Process -Id $agentPid
if ($proc -ne $null) {
Stop-Process $agentPid
}
# Remove all enviroment variables
[Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "Process")
[Environment]::SetEnvironmentVariable("SSH_AGENT_PID", $null, "User")
[Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "Process")
[Environment]::SetEnvironmentVariable("SSH_AUTH_SOCK", $null, "User")
}
}
# Add a key to the SSH agent
function Add-SshKey() {
if ($args.Count -eq 0) {
# Add the default key (~/id_rsa)
ssh-add
} else {
foreach ($value in $args) {
ssh-add $value
}
}
}
# Start the agent if not already running; provide feedback
$agent = Get-SshAgent
if ($agent -eq 0) {
Write-Host "Starting SSH agent..."
Start-SshAgent # Start agent
Add-SshKey # Add my default key
} else {
Write-Host "SSH agent is running (PID $agent)"
}
|
PowerShellCorpus/GithubGist/miriyagi_6699897_raw_94cc74b2aeca2f22de089d46befa8e648d7b386b_Remove-DuplicatedMusicFiles.ps1
|
miriyagi_6699897_raw_94cc74b2aeca2f22de089d46befa8e648d7b386b_Remove-DuplicatedMusicFiles.ps1
|
Get-ChildItem -Hidden -Recurse . | %{
[string] $originalFileName = (($_.FullName -replace ' 1\.m4a$', '.m4a') -replace '-YUKI\.m4a', '.m4a')
if ($originalFileName -ne $_.FullName -and (Test-Path -LiteralPath $originalFileName)) {
Remove-Item -Force -LiteralPath $_.FullName
}
}
|
PowerShellCorpus/GithubGist/smasterson_25862683c8f822917177_raw_fec373d9f466d1b063c20f8d73c40f9f2cdd327c_Get-VMHostInfo.ps1
|
smasterson_25862683c8f822917177_raw_fec373d9f466d1b063c20f8d73c40f9f2cdd327c_Get-VMHostInfo.ps1
|
#Requires –Version 3
#Requires -PSSnapin VMware.VimAutomation.Core
<#
.SYNOPSIS
Exports VMware host (ESX/ESXi) information to Excel
.DESCRIPTION
Queries one or more ESX/ESXi servers directly and exports all info to an Excel workbook
A new workbook/file will be created for each host
.PARAMETER Server
The name of one or more ESX/ESXi servers to query
.PARAMETER Path
Path to folder where Excel workbook is saved
.EXAMPLE
.\Get-VMHostInfo.ps1 -server myesxhost -path "E:\Reports"
Gathers info from myesxhost and exports info to an Excel workbook saved in E:\Reports
.EXAMPLE
.\Get-VMHostInfo.ps1 -server "myesxhost","myotheresxhost" -path "E:\Reports"
Gathers info from myesxhost and myotheresxhost, exports info to separate Excel workbooks located in E:\Reports
.EXAMPLE
$servers = Get-Content "E:\myhosts.txt";.\Get-VMHostInfo.ps1 -server $servers -path "E:\Reports"
Gathers a list of ESX/ESXi host names from E:\myhosts.txt and gathers\exports info to separate Excel workbooks located in E:\Reports
.NOTES
Author : Shawn Masterson
Export-Xlsx function from Gilbert van Griensven https://www.itpilgrims.com/2013/01/export-xlsx-extended/
Excel is required to be installed on script host
Tested with ESX 4 and ESXi 4.1 thru 5.5
#>
[CmdletBinding()]
Param (
[parameter(Mandatory=$true)]
[String[]]
$server,
[parameter(Mandatory=$true)]
[String]
$path
)
### Supporting function ###
Function Export-Xlsx {
<#
.SYNOPSIS
Exports objects to an Excel workbook
.DESCRIPTION
Exports objects to an Excel workbook and applies cosmetics. Optionally add a title, autofilter, autofit and a chart.
Allows for export to .xls and .xlsx format. If .xlsx is specified but not available (Excel 2003) the data will be exported to .xls.
.PARAMETER InputObject
The data to be exported to Excel
.PARAMETER Path
The path of the Excel file. Defaults to %HomeDrive%\Export.xlsx.
.PARAMETER WorksheetName
The name of the worksheet. Defaults to filename in $Path without extension.
.PARAMETER ExpandArrayValues
Joins an array value to a newline separated list.
.PARAMETER ChartType
Name of an Excel chart to be added.
.PARAMETER TableStyle
Apply a style to the created table. Does not work in Excel 2003.
For an overview of styles see http://msdn.microsoft.com/fr-fr/library/documentformat.openxml.spreadsheet.tablestyle.aspx
The Pivot styles are not used in this function.
.PARAMETER Title
Adds a title to the worksheet.
.PARAMETER SheetPosition
Adds the worksheet either to the 'begin' or 'end' of the Excel file.
.PARAMETER TransposeColumnProperty
Selects a property of the input object which will be moved to the top row of the transposed table.
.PARAMETER ChartOnNewSheet
Adds a chart to a new worksheet instead of to the worksheet containing data.
The Chart will be placed after the sheet containing data.
.PARAMETER AppendWorksheet
Appends a worksheet to an existing Excel file.
.PARAMETER Borders
Adds borders to all cells. Defaults to True.
.PARAMETER HeaderColor
Applies background color to the header row. Defaults to True.
.PARAMETER AutoFit
Apply autofit to columns. Defaults to True.
.PARAMETER AutoFilter
Apply autofilter. Defaults to True.
.PARAMETER PassThru
Returns file object of the generated file.
.PARAMETER Force
Overwrites existing Excel sheet. When this switch is not used but the Excel file already exists, a new file with datestamp will be generated.
.PARAMETER Transpose
Transposes the data in Excel. This will automatically disable AutoFilter and HeaderColor.
.PARAMETER FreezePanes
Freezes the title row.
.EXAMPLE
Get-Process | Export-Xlsx -Path D:\Data\ProcessList.xlsx
Exports a list of running processes to Excel
.EXAMPLE
Get-ADuser -Filter {enabled -ne $True} | Select-Object Name,Surname,GivenName,DistinguishedName | Export-Xlsx -Path 'D:\Data\Disabled Users.xlsx' -Title 'Disabled users of Contoso.com'
Export all disabled AD users to Excel with optional title
.EXAMPLE
Get-Process | Sort-Object CPU -Descending | Export-Xlsx -Path D:\Data\Processes_by_CPU.xlsx
Export a sorted processlist to Excel
.EXAMPLE
Export-Xlsx (Get-Process) -AutoFilter:$False -PassThru | Invoke-Item
Export a processlist to %HomeDrive%\Export.xlsx with AutoFilter disabled, and open the Excel file
.NOTES
Author : Gilbert van Griensven
Based on http://www.lucd.info/2010/05/29/beyond-export-csv-export-xls/
#>
[CmdletBinding(DefaultParametersetName="Default")]
Param (
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$True)]
[ValidateNotNullOrEmpty()]
$InputObject,
[ValidateScript({
$ReqExt = [System.IO.Path]::GetExtension($_)
($ReqExt -eq ".xls") -or
($ReqExt -eq ".xlsx")
})]
$Path=(Join-Path $env:HomeDrive "Export.xlsx"),
$WorksheetName = [System.IO.Path]::GetFileNameWithoutExtension($Path),
[Switch] $AppendWorksheet,
[ValidateSet("begin","end")] $SheetPosition="begin",
$Title,
[Switch] $AutoFit=$True,
[Switch] $AutoFilter=$True,
[Switch] $FreezePanes,
[Switch] $Transpose,
[String] $TransposeColumnProperty,
[Switch] $ExpandArrayValues,
[PSObject] $ChartType,
[Switch] $ChartOnNewSheet,
[Parameter(ParameterSetName="CustomStyle")]
[Switch] $Borders=$True,
[Parameter(ParameterSetName="CustomStyle")]
[Switch] $HeaderColor=$True,
[Parameter(ParameterSetName="TableStyle")]
[String] $TableStyle,
[Switch] $Force,
[Switch] $PassThru
)
DynamicParam {
# Adds custom argument completers for 'ChartType' and 'TableStyle' parameters for this function only
If ([Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Excel") -ne $Null) {
$Completion_xlChartType = {
Param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
[Enum]::GetValues([Microsoft.Office.Interop.Excel.XlChartType]) | % {
New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', "$($_)"
}
}
$Completion_xlTableStyle = {
Param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
1..28 | % {
@("TableStyleMedium$($_)")
If ($_ -le 21) { @("TableStyleLight$($_)") }
If ($_ -le 11) { @("TableStyleDark$($_)") }
} |
Sort-Object | % {
New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', "$($_)"
}
}
If (!($global:options)) { $global:options = @{CustomArgumentCompleters = @{};NativeArgumentCompleters = @{}} }
$global:options['CustomArgumentCompleters']['Export-Xlsx:ChartType'] = $Completion_xlChartType
$global:options['CustomArgumentCompleters']['Export-Xlsx:TableStyle'] = $Completion_xlTableStyle
$function:tabexpansion2 = $function:tabexpansion2 -replace 'End\r\n{','End { If ($Null -ne $options) {$options += $global:options} Else {$options = $global:options}'
}
}
Begin {
Function Convert-NumberToA1 {
Param([parameter(Mandatory=$true)] [int]$number)
$a1Value = $null
While ($number -gt 0) {
$multiplier = [int][system.math]::Floor(($number / 26))
$charNumber = $number - ($multiplier * 26)
If ($charNumber -eq 0) { $multiplier-- ; $charNumber = 26 }
$a1Value = [char]($charNumber + 96) + $a1Value
$number = $multiplier
}
Write-Verbose "Converted '$($number)' to '$($a1Value)'"
Return $a1Value
}
Function Using-Culture ([System.Globalization.CultureInfo]$Culture, [ScriptBlock]$Script) {
$OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
Trap { [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture }
[System.Threading.Thread]::CurrentThread.CurrentCulture = $Culture
$ExecutionContext.InvokeCommand.InvokeScript($Script)
[System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}
$Path = [System.IO.Path]::GetFullPath($Path)
$Script:WorkingData = @()
}
Process {
$Script:WorkingData += $InputObject
}
End {
If ($Script:WorkingData.Count -eq 0) {
$ExceptionMessage = New-Object System.FormatException "Input object is empty. Nothing to export to Excel."
Throw $ExceptionMessage
}
$Props = $Script:WorkingData[0].PSObject.properties | % { $_.Name }
Write-Verbose "$($Props.Count) object properties detected"
If ($Transpose) {
Write-Verbose "Setting up for transposed data collection"
If (($TransposeColumnProperty) -and ($Props -contains $TransposeColumnProperty)) {
$Props = $Props | ? {$_ -ne $TransposeColumnProperty}
$Rows = 1
} Else {
$TransposeColumnProperty = $Null
$HeaderColor = $False
}
$Rows += $Props.Count
$Cols = $Script:WorkingData.Count+1
$AutoFilter = $False
} Else {
Write-Verbose "Setting up for data collection"
$Rows = $Script:WorkingData.Count+1
$Cols = $Props.Count
}
Write-Verbose "Input object has $($Rows) rows and $($Cols) columns"
$A1Cols = Convert-NumberToA1 $Cols
$Array = New-Object 'object[,]' $Rows,$Cols
$Col = 0
$Row = 0
Write-Verbose "Storing object properties as data headers into array"
If (($Transpose) -and ($TransposeColumnProperty)) {
$Array[$Row,$Col] = $TransposeColumnProperty
$Row++
}
$Props | % {
$Array[$Row,$Col] = $_.ToString()
If ($Transpose) {
$Row++
} Else {
$Col++
}
}
Write-Verbose "Storing object data into array"
$Row = 1
$Script:WorkingData | % {
$Item = $_
$Col = 0
$Props | % {
If (($Transpose) -and ($TransposeColumnProperty) -and ($Col -eq 0)) {
$Array[$Col,$Row] = $Item.($TransposeColumnProperty).ToString()
$Col++
}
If ($Item.($_) -eq $Null) {
If ($Transpose) {
$Array[$Col,$Row] = ""
} Else {
$Array[$Row,$Col] = ""
}
} Else {
If (($Item.($_) -is [System.Array]) -and ($ExpandArrayValues)) {
$ItemData = [String]::Join("`r`n",$Item.($_))
} Else {
$ItemData = $Item.($_).ToString()
}
If ($Transpose) {
$Array[$Col,$Row] = $ItemData
} Else {
$Array[$Row,$Col] = $ItemData
}
}
$Col++
}
$Row++
}
Using-Culture en-US {
Write-Verbose "Attempting to start Excel as COM object"
Try { $ExcelApplication = New-Object -ComObject Excel.Application }
Catch {
$ExceptionMessage = New-Object System.FormatException "Could not create COM object. Please ensure Microsoft Excel is installed."
Throw $ExceptionMessage
}
$ExcelApplication.DisplayAlerts = $False
$ExcelApplicationFixedFormat = [Microsoft.Office.Interop.Excel.XLFileFormat]::xlWorkbookNormal
If ([System.IO.Path]::GetExtension($Path) -eq '.xlsx') {
Write-Verbose "Selected file format: .xlsx"
If ($ExcelApplication.Version -lt 12) {
Write-Verbose "Current Excel version `($($ExcelApplication.Version)`)does not support .xlsx format. Switching to .xls format"
$Path = [System.IO.Path]::ChangeExtension($Path,".xls")
} Else {
$ExcelApplicationFixedFormat = [Microsoft.Office.Interop.Excel.XLFileFormat]::xlWorkbookDefault
}
} Else {
Write-Verbose "Selected file format: .xls"
}
If (Test-Path -Path $Path -PathType "Leaf") {
Write-Verbose "$($Path) exists"
If ($AppendWorkSheet) {
Write-Verbose "AppendWorkSheet parameter received. Attempting to open $($Path)"
$Workbook = $ExcelApplication.Workbooks.Open($Path)
If ($Workbook.ReadOnly) {
$Workbook.Close()
$ExcelApplication.Quit()
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Workbook)) {}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelApplication)) {}
[GC]::Collect()
$ExceptionMessage = New-Object System.FormatException "The file $($Path) is marked read-only. Please check NTFS permissions and ensure the file is not open in other applications"
Throw $ExceptionMessage
}
If ($SheetPosition -eq "end") {
Write-Verbose "Setting sheet position to 'end'"
$Workbook.Worksheets.Add([System.Reflection.Missing]::Value,$Workbook.Sheets.Item($Workbook.Sheets.Count)) | Out-Null
} Else {
Write-Verbose "Setting sheet position to 'begin'"
$Workbook.Worksheets.Add($Workbook.Worksheets.Item(1)) | Out-Null
}
} Else {
If (!($Force)) {
$Path = $Path.Insert($Path.LastIndexOf(".")," - $(Get-Date -Format "ddMMyyyy-HHmm")")
Write-Verbose "No Force parameter specified. Target file is changed to: $($Path)"
} Else {
Write-Verbose "Force parameter specified. Overwriting existing file"
}
Write-Verbose "Adding new workbook"
$Workbook = $ExcelApplication.Workbooks.Add()
While ($Workbook.Worksheets.Count -gt 1) { $Workbook.Worksheets.Item(1).Delete() }
}
} Else {
Write-Verbose "$($Path) does not exist. Adding new workbook"
$Workbook = $ExcelApplication.Workbooks.Add()
While ($Workbook.Worksheets.Count -gt 1) { $Workbook.Worksheets.Item(1).Delete() }
}
$Worksheet = $Workbook.ActiveSheet
Try { $Worksheet.Name = $WorksheetName }
Catch {
Write-Verbose "!!! Unable to set worksheet name to $($WorksheetName)"
}
If ($Title) {
Write-Verbose "Adding title"
$Worksheet.Cells.Item(1,1) = $Title
$TitleRange = $Worksheet.Range("a1","$($A1Cols)2")
$TitleRange.Font.Size = 18
$TitleRange.Font.Bold=$True
$TitleRange.Font.Name = "Cambria"
$TitleRange.Font.ThemeFont = 1
$TitleRange.Font.ThemeColor = 4
$TitleRange.Font.ColorIndex = 55
$TitleRange.Font.Color = 8210719
$TitleRange.Merge()
$TitleRange.VerticalAlignment = -4160
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($TitleRange)) {}
$UsedRange = $Worksheet.Range("a3","$($A1Cols)$($Rows + 2)")
If ($HeaderColor) {
Write-Verbose "Setting header row background color"
$Worksheet.Range("a3","$($A1Cols)3").Interior.ColorIndex = 48
$Worksheet.Range("a3","$($A1Cols)3").Font.Bold = $True
}
If (($FreezePanes) -and ((($Transpose) -and ($TransposeColumnProperty)) -or (!($Transpose)))) {
Write-Verbose "Freezing panes"
$Worksheet.Range("a4:a4").Select() | Out-Null
$ExcelApplication.ActiveWindow.FreezePanes = $True
}
} Else {
$UsedRange = $Worksheet.Range("a1","$($A1Cols)$($Rows)")
If ($HeaderColor) {
Write-Verbose "Setting header row background color"
$Worksheet.Range("a1","$($A1Cols)1").Interior.ColorIndex = 48
$Worksheet.Range("a1","$($A1Cols)1").Font.Bold = $True
}
If (($FreezePanes) -and ((($Transpose) -and ($TransposeColumnProperty)) -or (!($Transpose)))) {
Write-Verbose "Freezing panes"
$Worksheet.Range("a2:a2").Select() | Out-Null
$ExcelApplication.ActiveWindow.FreezePanes = $True
}
}
Write-Verbose "Transferring array data to selected range in Excel"
$UsedRange.Value2 = $Array
$UsedRange.HorizontalAlignment = -4131
$UsedRange.VerticalAlignment = -4160
If ($Borders) {
Write-Verbose "Adding borders"
$UsedRange.Borders.LineStyle = 1
$UsedRange.Borders.Weight = 2
}
If ($AutoFilter) {
Write-Verbose "Applying autofilter"
$UsedRange.AutoFilter() | Out-Null
}
If ($AutoFit) {
Write-Verbose "Applying autofit"
$Worksheet.UsedRange.EntireColumn.AutoFit() | Out-Null
$Worksheet.UsedRange.EntireRow.AutoFit() | Out-Null
}
If (($TableStyle) -and ($ExcelApplication.Version -ge 12)) {
Write-Verbose "Applying table style '$($TableStyle)'"
$ListObject = $Worksheet.ListObjects.Add([Microsoft.Office.Interop.Excel.XlListObjectSourceType]::xlSrcRange, $UsedRange, $Null, [Microsoft.Office.Interop.Excel.XlYesNoGuess]::xlYes, $Null)
$ListObject.TableStyle = $TableStyle
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($ListObject)) {}
}
If ($ChartType) {
Try {
Write-Verbose "Attempting to add chart of type '$($ChartType)'"
[Microsoft.Office.Interop.Excel.XlChartType]$ChartType = $ChartType
If ($ChartOnNewSheet) {
Write-Verbose "Adding chart to new worksheet"
$Workbook.Charts.Add().ChartType = $ChartType
$Workbook.ActiveChart.setSourceData($UsedRange)
Try { $Workbook.ActiveChart.Name = "$($WorksheetName) - Chart" }
Catch { }
$Workbook.ActiveChart.Move([System.Reflection.Missing]::Value,$Workbook.Sheets.Item($Worksheet.Name))
} Else {
Write-Verbose "Adding chart to current sheet"
$Worksheet.Shapes.AddChart($ChartType).Chart.setSourceData($UsedRange) | Out-Null
}
}
Catch {
Write-Verbose "!!! '$($ChartType)' is not a valid Excel chart type. Use tab expansion to choose between valid chart types."
}
}
Write-Verbose "Saving Excel workbook to $($Path)"
$Workbook.Worksheets.Item(1).Select()
Try { $Workbook.SaveAs($Path,$ExcelApplicationFixedFormat) }
Catch { $ExceptionMessage = New-Object System.FormatException "Unable to save to $($Path). Please ensure you have write access." }
Write-Verbose "Closing Excel and cleaning up references"
$Workbook.Close()
$ExcelApplication.Quit()
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($UsedRange)) {}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Worksheet)) {}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Workbook)) {}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelApplication)) {}
[GC]::Collect()
If ($ExceptionMessage) { Throw $ExceptionMessage }
}
If ($PassThru) { Return Get-Item $Path }
}
}
### Main script begin ###
# Test path
If (!(Test-Path $path)) {
Write-Host "Path not found - $path" -ForegroundColor Red
Exit
}
# Obtain Credentials
$creds = Get-Credential -Message "Enter ESX/ESXi host credentials used to connect" -UserName root
# Cycle through servers gathering and exporting info
Foreach ($ESX in $Server) {
# Create full path to Excel workbook
$FullPath = $Path.Trimend('\') + "\HostInfo_" + $ESX + "_" + (Get-Date -Format MM-dd-yyyy) + ".xlsx"
# Connect to ESX/ESXi host
$connection = Connect-VIServer $ESX -Credential $creds
# Ensure connection
If ($connection) {
Write-Host "Connected to $ESX"
# Get ESX(i) Host Info
$VMHost = Get-VMHost $ESX
$VMHostProp = [ordered]@{}
$VMHostProp.Name = $VMHost.NetworkInfo.HostName
$VMHostProp."Domain Name" = $VMHost.NetworkInfo.DomainName
$VMHostProp.Hypervisor = $VMHost.Extensiondata.Config.Product.FullName
$VMHostProp.License = $VMHost.LicenseKey
$VMHostProp.Vendor = $VMHost.Manufacturer
$VMHostProp.Model = $VMHost.Model
$VMHostProp."BIOS Version" = $VMHost.Extensiondata.Hardware.BiosInfo.BiosVersion
$VMHostProp."CPU Model" = $VMHost.ProcessorType
$VMHostProp."CPU Count" = $VMHost.ExtensionData.Summary.Hardware.NumCpuPkgs
$VMHostProp."Total Cores" = $VMHost.ExtensionData.Summary.Hardware.numCpuCores
$VMHostProp."Total Threads" = $VMHost.ExtensionData.Summary.Hardware.numCpuThreads
$VMHostProp."Hyperthreading Enabled" = $VMHost.HyperThreadingActive
$VMHostProp."CPU Current Usage (Mhz)" = $VMHost.CpuUsageMhz
$VMHostProp."Memory (GB)" = [Math]::Round($VMHost.MemoryTotalGB,0)
$VMHostProp."Memory Current Usage (GB)" = [Math]::Round($VMHost.MemoryUsageGB,0)
$VMHostProp."FC HBAs" = ($VMHost | Get-VMHostHba | where {$_.Type -eq "FibreChannel"}).Count
$VMHostProp."iSCSI HBAs" = ($VMHost | Get-VMHostHba | where {$_.Type -eq "IScsi"}).Count
$VMHostProp."Physical NICs" = $VMHost.ExtensionData.Config.Network.Pnic.Count
If ($VMHost.NetworkInfo.VMKernelGateway) {
$VMHostProp."VMKernel Gateway" = $VMHost.NetworkInfo.VMKernelGateway
} Else {
$VMHostProp."Console Gateway" = $VMHost.NetworkInfo.ConsoleGateway
}
Try {
$domainStatus = ""
$domainStatus = $VMHost | Get-VMHostAuthentication -ErrorAction Stop
$VMHostProp."Authentication Domain" = If ($domainStatus.Domain){$domainStatus.Domain} Else {"Not Configured"}
$VMHostProp."Authentication Domain Status" = If ($domainStatus.DomainMembershipStatus){$domainStatus.DomainMembershipStatus} Else {"Unknown"}
$VMHostProp."Trusted Domains" = If ($domainStatus.Trusteddomains) {$domainStatus | Select -ExpandProperty TrustedDomains | Out-String} Else {"None"}
} Catch {}
$VMHostProp."DNS Server(s)" = $VMHost.ExtensionData.Config.Network.DnsConfig.Address | Out-String
$VMHostProp."Search Domain(s)" = $VMHost.NetworkInfo.SearchDomain | Out-String
$VMHostProp.TimeZone = $VMHost.TimeZone
$VMHostProp."NTP Server(s)" = $VMHost | Get-VMHostNtpServer | Out-String
Try {
$VMHostProp."Syslog Server(s)" = $VMHost | Get-VMHostSysLogServer -ErrorAction Stop | %{$_.Host + ":" + $_.Port} | Out-String
} Catch {
$VMHostProp."Syslog Server(s)" = "Unavailable"
}
Try {
$VMHostProp."Firewall Default Allow Incoming" = $VMHost | Get-VMHostFirewallDefaultPolicy -ErrorAction Stop | Select -ExpandProperty IncomingEnabled
$VMHostProp."Firewall Default Allow Outgoing" = $VMHost | Get-VMHostFirewallDefaultPolicy -ErrorAction Stop | Select -ExpandProperty OutgoingEnabled
} Catch {}
$VMHostProp."VM Count" = ($VMHost | Get-VM).Count
$VMHostProp."Report Created" = Get-Date
$VMHostInfo = New-Object –TypeName PSObject –Prop $VMHostProp
$VMHostInfo | Export-Xlsx -Path $FullPath -WorksheetName "ESX(i) Info" -Title "VMHost Information" -Transpose -Borders:$false -Force
# Get HBA Info
$HBAInfo = @()
$HBAs = $VMHost | Get-VMHostHba
Foreach ($HBA in $HBAs) {
$HBAProp = [ordered]@{}
$HBAProp.Device = $HBA.Device
$HBAProp."HBA Model" = $HBA.Model
$HBAProp."HBA Type" = $HBA.Type
$HBAProp.Driver = $HBA.Driver
$HBAProp.PCI = $HBA.PCI
$NWWN = $null
$NWWNFormatted = $null
[String] $NWWN = "{0:x}" -f $HBA.NodeWorldWideName
If ($NWWN) {
For ($i=0;$i -lt 8;$i++)
{
$NWWNFormatted += "{0}:" -f $($NWWN.SubString($i * 2, 2))
}
$NWWNFormatted = $NWWNFormatted.SubString(0, $NWWNFormatted.Length - 1)
}
$PWWN = $null
$PWWNFormatted = $null
[String] $PWWN = "{0:x}" -f $HBA.PortWorldWideName
If ($PWWN) {
For ($i=0;$i -lt 8;$i++)
{
$PWWNFormatted += "{0}:" -f $($PWWN.SubString($i * 2, 2))
}
$PWWNFormatted = $PWWNFormatted.SubString(0, $PWWNFormatted.Length - 1)
}
$HBAProp.NWWN = $NWWNFormatted
$HBAProp.PWWN = $PWWNFormatted
$HBAProp."Software Based" = $HBA.IsSoftwareBased
$HBAProp."iSCSI Name" = $HBA.IScsiName
$HBAProp."iSCSI Alias" = $HBA.IScsiAlias
$HBAProp.Status = $HBA.Status
$HBATemp = New-Object –TypeName PSObject –Prop $HBAProp
$HBAInfo += $HBATemp
}
If ($HBAInfo) {
$HBAInfo | Export-Xlsx -Path $FullPath -WorksheetName "HBA Info" -Title "HBA Info" -AppendWorksheet -SheetPosition "end"
}
# Get Host Disks
$diskInfo = @()
$disks = $VMHost | Get-VMHostDisk
ForEach ($disk in $disks) {
$diskProp = [ordered]@{}
$diskProp."Device Name" = $disk.DeviceName
$diskProp."SCSI LUN" = $disk.ScsiLun
$diskProp.Cylinders = $disk.Cylinders
$diskProp.Heads = $disk.Heads
$diskProp.Sectors = $disk.Sectors
$diskProp.TotalSectors = $disk.TotalSectors
$diskTemp = New-Object –TypeName PSObject –Prop $diskProp
$diskInfo += $diskTemp
}
If ($diskInfo) {
$diskInfo | Sort "Device Name" | Export-Xlsx -Path $FullPath -WorksheetName "Disks" -Title "Host Disks" -AppendWorksheet -SheetPosition "end"
}
# Get SCSI LUNs
$lunInfo = @()
$scsiLuns = $VMHost | Get-ScsiLun
ForEach ($scsiLun in $scsiLuns) {
$scsiLunProp = [ordered]@{}
$scsiLunProp."Runtime Name" = $scsiLun.RuntimeName
$scsiLunProp."Canonical Name" = $scsiLun.CanonicalName
$scsiLunProp."Device Path" = $scsiLun.ConsoleDeviceName
$scsiLunProp.Type = $scsiLun.LunType
$scsiLunProp.Vendor = $scsiLun.Vendor
$scsiLunProp.Model = $scsiLun.Model
$scsiLunProp."Serial Number" = $scsiLun.SerialNumber
$scsiLunProp."Capacity (GB)" = [Math]::Round($scsiLun.CapacityGB,2)
$scsiLunProp."Multipath Policy" = $scsiLun.MultipathPolicy
$scsiLunProp.Local = $scsiLun.IsLocal
$scsiLunProp.SSD = $scsiLun.ExtensionData.Ssd
$scsiLunProp.UUID = $scsiLun.ExtensionData.Uuid
$scsiLunTemp = New-Object –TypeName PSObject –Prop $scsiLunProp
$lunInfo += $scsiLunTemp
}
If ($lunInfo) {
$lunInfo | Sort Type | Export-Xlsx -Path $FullPath -WorksheetName "SCSI LUNs" -Title "SCSI LUNs" -AppendWorksheet -SheetPosition "end"
}
# Get Multipathing Info
$pathInfo = @()
$luns = $VMhost.ExtensionData.config.storagedevice.multipathinfo.lun
ForEach ($lun in $luns) {
$lunName = $lun.Id
$lunPolicy = $lun.policy.policy
$lunPaths = $lun.path
Foreach ($lunPath in $lunPaths) {
$pathProp = [ordered]@{}
$pathProp."LUN ID" = $lunName
$pathProp."LUN Policy" = $lunPolicy
$pathProp.State = $lunPath.pathstate
$pathProp."Path Name" = $lunPath.Name
$pathProp."Adapter Name" = ($lunPath.Name).Split("-")[0]
$pathProp."Target Name" = ($lunPath.Name).Split("-")[1]
$pathProp."LUN Name" = ($lunPath.Name).Split("-")[2]
$pathTemp = New-Object –TypeName PSObject –Prop $pathProp
$pathInfo += $pathTemp
}
}
If ($pathInfo) {
$pathInfo | Sort "LUN ID" | Export-Xlsx -Path $FullPath -WorksheetName "Multipath Info" -Title "Multipath Info" -AppendWorksheet -SheetPosition "end"
}
# Get iSCSI HBA Targets
$iscsiTargetInfo = @()
$iscsiTargets = Get-IScsiHbaTarget -Server $ESX
ForEach ($iscsiTarget in $iscsiTargets) {
$iscsiTargetProp = [ordered]@{}
$iscsiTargetProp.Name = $iscsiTarget.Name
$iscsiTargetProp."iSCSI Name" = $iscsiTarget.IScsiName
$iscsiTargetProp.Address = $iscsiTarget.Address
$iscsiTargetProp.Port = $iscsiTarget.Port
$iscsiTargetProp.Authentication = $iscsiTarget.AuthenticationProperties
$iscsiTargetProp.Type = $iscsiTarget.Type
$iscsiTargetProp."iSCSI HBA Name" = $iscsiTarget.IScsiHbaName
$iscsiTargetTemp = New-Object –TypeName PSObject –Prop $iscsiTargetProp
$iscsiTargetInfo += $iscsiTargetTemp
}
If ($iscsiTargetInfo) {
$iscsiTargetInfo | Sort Name | Export-Xlsx -Path $FullPath -WorksheetName "iSCSI Targets" -Title "iSCSI HBA Targets" -AppendWorksheet -SheetPosition "end"
}
# Get Host Diagnostic Partitions
$diagInfo = @()
$diags = $VMHost | Get-VMHostDiagnosticPartition
ForEach ($diag in $diags) {
$diagProp = [ordered]@{}
$diagProp."Canonical Name" = $diag.CanonicalName
$diagProp."Diagnostic Type" = $diag.DiagnosticType
$diagProp."Storage Type" = $diag.StorageType
$diagProp.Slots = $diag.SlotCount
$diagProp.Active = $diag.Active
$diagTemp = New-Object –TypeName PSObject –Prop $diagProp
$diagInfo += $diagTemp
}
If ($diagInfo) {
$diagInfo | Sort Active -Descending | Export-Xlsx -Path $FullPath -WorksheetName "Diagnostic Partitions" -Title "Diagnostic Partitions" -AppendWorksheet -SheetPosition "end"
}
# Get Datastore Info
$DSInfo = @()
$DSs = $VMHost | Get-Datastore
Foreach ($DS in $DSs) {
$DSProp = [ordered]@{}
$DSProp.Name = $DS.Name
$DSProp.Type = $DS.Type
$DSProp."Size (GB)" = [Math]::Round($DS.CapacityGB,2)
$DSProp."Used (GB)" = [Math]::Round($DS.CapacityGB - $DS.FreeSpaceGB,2)
$DSProp."Free (GB)" = [Math]::Round($DS.FreeSpaceGB,2)
$usedPerc = ($DS.CapacityGB - $DS.FreeSpaceGB)/$DS.CapacityGB
$DSProp."Used %" = "{0:P1}" -f $usedPerc
$DSProp."Mount Point" = $DS.ExtensionData.Info.Url
$DSProp.Extents = If ($DS.Type -eq "VMFS"){$DS.ExtensionData.Info.Vmfs.Extent.DiskName}
ElseIf ($DS.Type -eq "NFS"){$DS.ExtensionData.Info.Nas.RemoteHost + ":" + $DS.ExtensionData.Info.Nas.RemotePath}
$DSProp.StorageIOControlEnabled = $DS.StorageIOControlEnabled
$DSProp.FileSystemVersion = $DS.FileSystemVersion
$DSProp.BlockSize = $DS.ExtensionData.Info.Vmfs.BlockSizeMB
$DSProp.SSD = $DS.ExtensionData.Info.Vmfs.Ssd
$DSProp.Local = $DS.ExtensionData.Info.Vmfs.Local
$DSProp."VM Count" = ($DS | Get-VM).Count
$DSProp.State = $DS.State
$DSTemp = New-Object –TypeName PSObject –Prop $DSProp
$DSInfo += $DSTemp
}
If ($DSInfo) {
$DSInfo | Sort Name | Export-Xlsx -Path $FullPath -WorksheetName "Datastores" -Title "Datastores" -AppendWorksheet -SheetPosition "end"
}
# Get Datastore Chart
$DSInfo = @()
Foreach ($DS in $DSs) {
$DSProp = [ordered]@{}
$DSProp.Name = $DS.Name
$DSProp."Used (GB)" = [Math]::Round($DS.CapacityGB - $DS.FreeSpaceGB,2)
$DSProp."Free (GB)" = [Math]::Round($DS.FreeSpaceGB,2)
$DSTemp = New-Object –TypeName PSObject –Prop $DSProp
$DSInfo += $DSTemp
}
If ($DSInfo) {
$DSInfo | Sort Name | Export-Xlsx -Path $FullPath -WorksheetName "Datastores - Chart" -Title "Datastores - Chart" -ChartType xlColumnStacked -AppendWorksheet -SheetPosition "end"
}
# Get Physical NIC Info
$pNICInfo = @()
$NICs = $VMHost | Get-VMHostNetworkAdapter -Physical
Foreach ($NIC in $NICs) {
$NICProp = [ordered]@{}
$NICProp.pNIC = $NIC.DeviceName
$NICProp.Model = ($VMHost.ExtensionData.Hardware.PciDevice | where {$_.Id -eq $NIC.ExtensionData.Pci}).DeviceName
$NICProp.Driver = $NIC.ExtensionData.Driver
$NICProp."Speed (MB)" = $NIC.ExtensionData.LinkSpeed.SpeedMB
$NICProp."Full Duplex" = $NIC.ExtensionData.LinkSpeed.Duplex
$NICProp.MAC = $NIC.Mac
$NICProp."PCI Location" = $NIC.ExtensionData.Pci
$NICProp.vSwitch = ($VMHost | Get-VirtualSwitch | where {$_.Nic -contains $NIC.DeviceName}).Name
$NICTemp = New-Object –TypeName PSObject –Prop $NICProp
$pNICInfo += $NICTemp
}
If ($pNICInfo) {
$pNICInfo | Export-Xlsx -Path $FullPath -WorksheetName "pNIC Info" -Title "Physical NIC Info" -AppendWorksheet -SheetPosition "end"
}
# Get VMKernel Virtual Network Adapter Info
$vNICInfo = @()
$vNICs = $VMHost | Get-VMHostNetworkAdapter -VMKernel
Foreach ($vNIC in $vNICs) {
$vNICProp = [ordered]@{}
$vNICProp.VMKernel = $vNIC.DeviceName
$vNICProp.MAC = $vNIC.Mac
$vNICProp.MTU = $vNIC.Mtu
$vNICProp.IPv6Enabled = $vNIC.IPv6Enabled
$vNICProp.DHCPEnabled = $vNIC.DhcpEnabled
$vNICProp.IP = $vNIC.IP
$vNICProp.SubnetMask = $vNIC.SubnetMask
$vNICProp.PortGroupName = $vNIC.PortGroupName
$vNICProp.MgmtEnabled = $vNIC.ManagementTrafficEnabled
$vNICProp.vMotionEnabled = $vNIC.vMotionEnabled
$vNICProp.FTEnabled = $vNIC.FaultToleranceLoggingEnabled
$vNICProp.VSANEnabled = $vNIC.VsanTrafficEnabled
$vNICTemp = New-Object –TypeName PSObject –Prop $vNICProp
$vNICInfo += $vNICTemp
}
If ($vNICInfo) {
$vNICInfo | Export-Xlsx -Path $FullPath -WorksheetName "VMKernel Info" -Title "VMKernel Info" -AppendWorksheet -SheetPosition "end"
}
# Get Service Console Info
$cNICInfo = @()
$cNICs = $VMHost | Get-VMHostNetworkAdapter -Console
Foreach ($cNIC in $cNICs) {
$cNICProp = [ordered]@{}
$cNICProp.cNIC = $cNIC.DeviceName
$cNICProp.MAC = $cNIC.Mac
$cNICProp.DHCPEnabled = $cNIC.DhcpEnabled
$cNICProp.IP = $cNIC.IP
$cNICProp.SubnetMask = $cNIC.SubnetMask
$cNICProp.PortGroupName = $cNIC.PortGroupName
$cNICTemp = New-Object –TypeName PSObject –Prop $cNICProp
$cNICInfo += $cNICTemp
}
If ($cNICInfo) {
$cNICInfo | Export-Xlsx -Path $FullPath -WorksheetName "Service Console Info" -Title "Service Console Info" -AppendWorksheet -SheetPosition "end"
}
# Get Standard Switch Info
$sSwInfo = @()
$sSwitchs = $VMHost | Get-VirtualSwitch -Standard
Foreach ($sSwitch in $sSwitchs) {
$sSwProp = [ordered]@{}
$sSwProp.Name = $sSwitch.Name
$sSwProp.MTU = $sSwitch.Mtu
$sSwProp."pNIC(s)" = $sSwitch.Nic | Out-String
$sSwProp."Load Balancing" = $sSwitch.ExtensionData.Spec.Policy.NicTeaming.Policy
$sSwProp."Network Failure Detection" = If ($sSwitch.ExtensionData.Spec.Policy.NicTeaming.FailureCriteria.CheckBeacon) {
"Beacon probing"} Else {"Link status only"}
$sSwProp."Notify Switches" = $sSwitch.ExtensionData.Spec.Policy.NicTeaming.NotifySwitches
$sSwProp."Failback" = $sSwitch.ExtensionData.Spec.Policy.NicTeaming.ReversePolicy
$sSwProp."Active pNIC(s)" = $sSwitch.ExtensionData.Spec.Policy.NicTeaming.NicOrder.ActiveNic | Out-String
$sSwProp."Standby pNIC(s)" = $sSwitch.ExtensionData.Spec.Policy.NicTeaming.NicOrder.StandbyNic | Out-String
$sSwProp."Promiscuous Mode" = $sSwitch.ExtensionData.Spec.Policy.Security.AllowPromiscuous
$sSwProp."Mac Address Changes" = $sSwitch.ExtensionData.Spec.Policy.Security.MacChanges
$sSwProp."Forged Transmits" = $sSwitch.ExtensionData.Spec.Policy.Security.ForgedTransmits
$sSwProp."Traffic Shaping Enabled" = $sSwitch.ExtensionData.Spec.Policy.ShapingPolicy.Enabled
$sSwProp."Average Bandwidth" = $sSwitch.ExtensionData.Spec.Policy.ShapingPolicy.AverageBandwidth
$sSwProp."Peak Bandwidth" = $sSwitch.ExtensionData.Spec.Policy.ShapingPolicy.PeakBandwidth
$sSwProp."Burst Size" = $sSwitch.ExtensionData.Spec.Policy.ShapingPolicy.BurstSize
$sSwProp."Portgroup(s)" = $sSwitch | Get-VirtualPortGroup | Select -ExpandProperty Name | Out-String
$sSwTemp = New-Object –TypeName PSObject –Prop $sSwProp
$sSwInfo += $sSwTemp
}
If ($sSwInfo) {
$sSwInfo | Export-Xlsx -Path $FullPath -WorksheetName "Standard Switch Info" -Title "Standard Switch Info" -AppendWorksheet -SheetPosition "end"
}
# Get Distributed Switch Information
$dvSwInfo = @()
$dvSwitchs = $VMHost | Get-VDSwitch
Foreach ($dvSwitch in $dvSwitchs) {
$dvSwProp = [ordered]@{}
$dvSwProp.Name = $dvSwitch.Name
$dvSwProp.MTU = $dvSwitch.Mtu
$dvSwProp."Overall Status" = $dvSwitch.ExtensionData.OverallStatus
$dvSwProp."Config Status" = $dvSwitch.ExtensionData.ConfigStatus
$dvSwProp.Note = "vCenter needed for further info"
$dvSwTemp = New-Object –TypeName PSObject –Prop $dvSwProp
$dvSwInfo += $dvSwTemp
}
If ($dvSwInfo) {
$dvSwInfo | Export-Xlsx -Path $FullPath -WorksheetName "Distributed Switch Info" -Title "Distributed Switch Info" -AppendWorksheet -SheetPosition "end"
}
# Get Standard Portgroup Information
$sPortInfo = @()
$sPortGroups = $VMHost | Get-VirtualPortGroup -Standard
Foreach ($sPortGroup in $sPortGroups) {
$sPortProp = [ordered]@{}
$sPortProp."Virtual Switch" = $sPortGroup.VirtualSwitchName
$sPortProp.Portgroup = $sPortGroup.Name
$sPortProp.VLAN = $sPortGroup.Vlanid
$sPortProp."Load Balancing" = $sPortGroup.ExtensionData.ComputedPolicy.NicTeaming.Policy
$sPortProp."Network Failure Detection" = If ($sPortGroup.ExtensionData.ComputedPolicy.NicTeaming.FailureCriteria.CheckBeacon) {
"Beacon probing"} Else {"Link status only"}
$sPortProp."Notify Switches" = $sPortGroup.ExtensionData.ComputedPolicy.NicTeaming.NotifySwitches
$sPortProp."Failback" = $sPortGroup.ExtensionData.ComputedPolicy.NicTeaming.ReversePolicy
$sPortProp."Active pNIC(s)" = $sPortGroup.ExtensionData.ComputedPolicy.NicTeaming.NicOrder.ActiveNic | Out-String
$sPortProp."Standby pNIC(s)" = $sPortGroup.ExtensionData.ComputedPolicy.NicTeaming.NicOrder.StandbyNic | Out-String
$sPortProp."Promiscuous Mode" = $sPortGroup.ExtensionData.ComputedPolicy.Security.AllowPromiscuous
$sPortProp."Mac Address Changes" = $sPortGroup.ExtensionData.ComputedPolicy.Security.MacChanges
$sPortProp."Forged Transmits" = $sPortGroup.ExtensionData.ComputedPolicy.Security.ForgedTransmits
$sPortProp."Traffic Shaping Enabled" = $sPortGroup.ExtensionData.ComputedPolicy.ShapingPolicy.Enabled
$sPortProp."Average Bandwidth" = $sPortGroup.ExtensionData.ComputedPolicy.ShapingPolicy.AverageBandwidth
$sPortProp."Peak Bandwidth" = $sPortGroup.ExtensionData.ComputedPolicy.ShapingPolicy.PeakBandwidth
$sPortProp."Burst Size" = $sPortGroup.ExtensionData.ComputedPolicy.ShapingPolicy.BurstSize
$sPortProp."VM Count" = ($sPortGroup | Get-VM).Count
$sPortTemp = New-Object –TypeName PSObject –Prop $sPortProp
$sPortInfo += $sPortTemp
}
If ($sPortInfo) {
$sPortInfo | Sort "Virtual Switch", Portgroup | Export-Xlsx -Path $FullPath -WorksheetName "Standard Portgroup Info" -Title "Standard Portgroup Info" -AppendWorksheet -SheetPosition "end"
}
# Get Distributed Portgroup Information
$dvPortInfo = @()
$dvPortGroups = Get-VDPortgroup -Server $ESX
Foreach ($dvPortGroup in $dvPortGroups) {
$dvPortProp = [ordered]@{}
$dvPortProp."Virtual Switch" = $dvPortGroup.VDSwitch
$dvPortProp.Portgroup = $dvPortGroup.Name
$dvPortProp."Port Binding" = $dvPortGroup.PortBinding
$dvPortProp."Overall Status" = $dvPortGroup.ExtensionData.OverallStatus
$dvPortProp."Config Status" = $dvPortGroup.ExtensionData.ConfigStatus
$dvPortProp.Note = "vCenter needed for further info"
$dvPortTemp = New-Object –TypeName PSObject –Prop $dvPortProp
$dvPortInfo += $dvPortTemp
}
If ($dvPortInfo) {
$dvPortInfo | Sort "Virtual Switch", Portgroup | Export-Xlsx -Path $FullPath -WorksheetName "Distributed Portgroup Info" -Title "Distributed Portgroup Info" -AppendWorksheet -SheetPosition "end"
}
# Get Firewall Exceptions
$fwInfo = @()
Try {
$fwExceptions = $VMHost | Get-VMHostFirewallException -ErrorAction Stop
Foreach ($fwException in $fwExceptions) {
$fwProp = [ordered]@{}
$fwProp.Enabled = $fwException.Enabled
$fwProp.Name = $fwException.Name
$fwProp."Incoming Ports" = $fwException.IncomingPorts
$fwProp."Outgoing Ports" = $fwException.OutgoingPorts
$fwProp."Protocol(s)" = $fwException.Protocols
$fwProp."Allow all IPs" = $fwException.ExtensionData.AllowedHosts.AllIp
$fwProp.Service = $fwException.ExtensionData.Service
$fwProp."Service Running" = $fwException.ServiceRunning
$fwTemp = New-Object –TypeName PSObject –Prop $fwProp
$fwInfo += $fwTemp
}
} Catch {}
If ($fwInfo) {
$fwInfo | Sort Enabled, Name | Export-Xlsx -Path $FullPath -WorksheetName "Firewall Exceptions" -Title "Firewall Exceptions" -AppendWorksheet -SheetPosition "end"
}
# Get Services Information
$svcInfo = @()
$services = $VMHost | Get-VMHostService
Foreach ($service in $services) {
$svcProp = [ordered]@{}
$svcProp.Service = $service.Label
$svcProp.Key = $service.Key
$svcProp.Running = $service.Running
switch ($service.Policy)
{
"on" {$svcProp."Startup Policy" = "Start and stop with host"}
"off" {$svcProp."Startup Policy" = "Start and stop manually"}
"automatic" {$svcProp."Startup Policy" = "Start and stop with port usage"}
default {$svcProp."Startup Policy" = "Unknown"}
}
$svcProp.Required = $service.Required
$svcProp.Uninstallable = $service.Uninstallable
$svcProp."Source Package" = $service.ExtensionData.SourcePackage.SourcePackageName
$svcProp."Source Package Desc" = $service.ExtensionData.SourcePackage.Description
$svcTemp = New-Object –TypeName PSObject –Prop $svcProp
$svcInfo += $svcTemp
}
If ($svcInfo) {
$svcInfo | Sort Service | Export-Xlsx -Path $FullPath -WorksheetName "Services Info" -Title "Services Info" -AppendWorksheet -SheetPosition "end"
}
# Get SNMP Info
$snmpInfo = @()
$snmpDetails = Get-VMHostSnmp -Server $ESX
$snmpProp = [ordered]@{}
$snmpProp.Enabled = $snmpDetails.Enabled
$snmpProp.Port = $snmpDetails.Port
$snmpProp."Read Only Communities" = $snmpDetails.ReadOnlyCommunities | Out-String
$snmpProp."Trap Targets" = $snmpDetails.TrapTargets | Out-String
$snmpTemp = New-Object –TypeName PSObject –Prop $snmpProp
$snmpInfo += $snmpTemp
If ($snmpInfo) {
$snmpInfo | Export-Xlsx -Path $FullPath -WorksheetName "SNMP Info" -Title "SNMP Info" -AppendWorksheet -SheetPosition "end"
}
# Get Installed ESX(i) Patches
$patchInfo = @()
Try {
$patches = (Get-EsxCli).software.vib.list()
ForEach ($patch in $patches) {
$patchProp = [ordered]@{}
$patchProp.Name = $patch.Name
$patchProp.ID = $patch.ID
$patchProp.Vendor = $patch.Vendor
$patchProp.Version = $patch.Version
$patchProp."Acceptance Level" = $patch.AcceptanceLevel
$patchProp."Created Date" = $patch.CreationDate
$patchProp."Install Date" = $patch.InstallDate
$patchProp.Status = $patch.Status
$patchTemp = New-Object –TypeName PSObject –Prop $patchProp
$patchInfo += $patchTemp
}
} Catch {
$patches = $VMHost | Get-VMHostPatch
ForEach ($patch in $patches) {
$patchProp = [ordered]@{}
$patchProp.Name = $patch.Description
$patchProp.ID = $patch.ID
$patchProp."Install Date" = $patch.InstallDate
$patchTemp = New-Object –TypeName PSObject –Prop $patchProp
$patchInfo += $patchTemp
}
}
If ($patchInfo) {
$patchInfo | Sort "Install Date" -Descending | Export-Xlsx -Path $FullPath -WorksheetName "Patch Info" -Title "Patch Info" -AppendWorksheet -SheetPosition "end"
}
# Get Local Users
$accountInfo = @()
$accounts = Get-VMHostAccount -Server $ESX
ForEach ($account in $accounts) {
$accountProp = [ordered]@{}
$accountProp.Name = $account.Name
$accountProp.Description = $account.Description
$accountProp.ShellAccess = $account.ShellAccessEnabled
$accountProp.Groups = $account.Groups | Out-String
$accountTemp = New-Object –TypeName PSObject –Prop $accountProp
$accountInfo += $accountTemp
}
If ($accountInfo) {
$accountInfo | Sort IsSystem, Name | Export-Xlsx -Path $FullPath -WorksheetName "Local Users" -Title "Local Users" -AppendWorksheet -SheetPosition "end"
}
# Get Local Groups
$grpInfo = @()
Try {
$grps = Get-VMHostAccount -Server $ESX -Group -ErrorAction Stop
ForEach ($grp in $grps) {
$grpProp = [ordered]@{}
$grpProp.Name = $grp.Name
$grpProp.Description = $grp.Description
$grpProp.Users = $grp.Users | Out-String
$grpTemp = New-Object –TypeName PSObject –Prop $grpProp
$grpInfo += $grpTemp
}
} Catch {}
If ($grpInfo) {
$grpInfo | Sort Name | Export-Xlsx -Path $FullPath -WorksheetName "Local Groups" -Title "Local Groups" -AppendWorksheet -SheetPosition "end"
}
# Get VI Roles
$roleInfo = @()
$roles = Get-VIRole -Server $ESX
ForEach ($role in $roles) {
$roleProp = [ordered]@{}
$roleProp.Name = $role.Name
$roleProp.Description = $role.Description
$roleProp.IsSystem = $role.IsSystem
$roleProp.Privileges = $role.PrivilegeList | Out-String
$roleTemp = New-Object –TypeName PSObject –Prop $roleProp
$roleInfo += $roleTemp
}
If ($roleInfo) {
$roleInfo | Sort IsSystem, Name | Export-Xlsx -Path $FullPath -WorksheetName "VI Roles" -Title "VI Roles" -AppendWorksheet -SheetPosition "end"
}
# Get Permissions
$permInfo = @()
$perms = Get-VIPermission -Server $ESX
ForEach ($perm in $perms) {
$permProp = [ordered]@{}
$permProp.Entity = $perm.Entity
$permProp.Role = $perm.Role
$permProp.Principal = $perm.Principal
$permProp.IsGroup = $perm.IsGroup
$permProp.Propagate = $perm.Propagate
$permTemp = New-Object –TypeName PSObject –Prop $permProp
$permInfo += $permTemp
}
If ($permInfo) {
$permInfo | Sort Entity, Principal | Export-Xlsx -Path $FullPath -WorksheetName "Permissions" -Title "Permissions" -AppendWorksheet -SheetPosition "end"
}
# Get VM Info
$vmInfo = @()
$vms = $VMHost | Get-VM
ForEach ($vm in $vms) {
$vmProp = [ordered]@{}
$vmProp.Name = $vm.Name
$vmProp.State = $vm.PowerState
$vmProp.FullName = If (!$VM.Guest.hostname) {"Tools Not Running\Unknown"} Else {$VM.Guest.hostname}
$vmProp.GuestOS = If (!$VM.Guest.OSFullName) {"Tools Not Running\Unknown"} Else {$VM.Guest.OSFullName}
$vmProp.IP = If (!$VM.Guest.IPAddress[0]) {"Tools Not Running\Unknown"} Else {$VM.Guest.IPAddress[0]}
$vmProp.NumCPU = $vm.NumCPU
[int]$vmProp."Memory (GB)" = $vm.MemoryGB
$vmProp."Disk (GB)" = [Math]::Round((($vm.HardDisks | Measure-Object -Property CapacityKB -Sum).Sum * 1KB / 1GB),2)
$vmProp."DiskFree (GB)" = If (![Math]::Round((($vm.Guest.Disks | Measure-Object -Property FreeSpace -Sum).Sum / 1GB),2)) `
{"Tools Not Running\Unknown"} Else {[Math]::Round((($vm.Guest.Disks | Measure-Object -Property FreeSpace -Sum).Sum / 1GB),2)}
$vmProp."DiskUsed (GB)" = If ($vmProp."DiskFree (GB)" -eq "Tools Not Running\Unknown") `
{"Tools Not Running\Unknown"} Else {$vmProp."Disk (GB)" - $vmProp."DiskFree (GB)"}
$vmProp.Notes = $VM.Notes
$vmTemp = New-Object –TypeName PSObject –Prop $vmProp
$vmInfo += $vmTemp
}
If ($vmInfo) {
$vmInfo | Sort Created -Descending | Export-Xlsx -Path $FullPath -WorksheetName "VM Info" -Title "VM Info" -AppendWorksheet -SheetPosition "end"
}
# Get VM Snapshots
$snapInfo = @()
$snaps = $VMHost | Get-VM | Get-Snapshot
ForEach ($snap in $snaps) {
$snapProp = [ordered]@{}
$snapProp.VM = $snap.VM
$snapProp.Name = $snap.Name
$snapProp.Description = $snap.Description
$snapProp.Created = $snap.Created
$snapProp."Size (GB)" = [Math]::Round($snap.SizeGB,2)
$snapProp.IsCurrent = $snap.IsCurrent
$snapTemp = New-Object –TypeName PSObject –Prop $snapProp
$snapInfo += $snapTemp
}
If ($snapInfo) {
$snapInfo | Sort Created -Descending | Export-Xlsx -Path $FullPath -WorksheetName "Snapshot Info" -Title "Snapshot Info" -AppendWorksheet -SheetPosition "end"
}
Disconnect-VIServer $ESX -Confirm:$false
Write-Host "$ESX Report Complete - $FullPath"
} Else {
Write-Host "Unable to connect to $ESX" -ForegroundColor Red
}
}
|
PowerShellCorpus/GithubGist/Gethe_7617988_raw_99a8d36128f82bc80d2102145c8e8df69a22bae3_wow%20patch.ps1
|
Gethe_7617988_raw_99a8d36128f82bc80d2102145c8e8df69a22bae3_wow%20patch.ps1
|
### Options ###
#valid modes: live, ptr, beta
$mode = "ptr"
$locale = "enUS"
### End Options ###
[int]$build = Read-Host "What build do you want to start at?" #17595
if ($mode -eq "live") {
$basicURL = "http://ak.worldofwarcraft.com.edgesuite.net/wow-pod-retail/NA/15890.direct"
} elseif ($mode -eq "ptr") {
$basicURL = "http://ak.worldofwarcraft.com.edgesuite.net/wow-pod/public-test/15890.direct"
} elseif ($mode -eq "beta") {
$basicURL = "http://ak.worldofwarcraft.com.edgesuite.net/wow-pod/beta/0E1FFF21/NA/15050.direct"
}
function DownloadFile($url, $targetFile) {
$url = $basicURL + $url
$uri = New-Object "System.Uri" "$url"
$request = [System.Net.HttpWebRequest]::Create($uri)
$request.set_Timeout(15000) #15 second timeout
$response = $request.GetResponse()
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
$responseStream = $response.GetResponseStream()
$targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $targetFile, Create
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
while ($count -gt 0) {
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
Write-Progress -activity "Downloading file '$($url.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength) * 100)
}
Write-Progress -activity "Finished downloading file '$($url.split('/') | Select -Last 1)'"
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
function testPath($url) {
$url = $basicURL + $url
"---------Test-Path------------"
$test = $url
$req = [system.Net.WebRequest]::Create($test)
try {
$res = $req.GetResponse()
} catch [System.Net.WebException] {
$res = $_.Exception.Response
}
$res.StatusCode
[int]$res.StatusCode
}
do {
$build++
$build
$i++
$i
$data = "/Data/wow-update-base-" + $build + ".MPQ"
$dataLocale = "/Data/" + $locale + "/wow-update-" + $locale + "-" + $build + ".MPQ"
$updates = "/Updates/wow-0-" + $build + "-Win-final.MPQ"
$status = testPath($data)
if ($status -eq "OK") {
"This is it!"
DownloadFile $data "$pwd$data"
DownloadFile $dataLocale "$pwd$dataLocale"
DownloadFile $updates "$pwd$updates"
}
}
until (($status -eq "OK") -or ($i -eq 200))
"Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
PowerShellCorpus/GithubGist/adoprog_5605387_raw_dc48002eaeeff9f1bcfba3567598487a16bf49c2_gistfile1.ps1
|
adoprog_5605387_raw_dc48002eaeeff9f1bcfba3567598487a16bf49c2_gistfile1.ps1
|
Clear-Host
remove-module [p]sake
import-module .\Tools\psake\psake.psm1
$psake.use_exit_on_error = $true
Invoke-psake .\buildscript.ps1 Package -properties @{ buildNumber = '12345'; }
|
PowerShellCorpus/GithubGist/StevenMcD_4008594_raw_a93339004453e006c5b6f46fd8729c682864e2f4_TeamCity_helperFunctions.ps1
|
StevenMcD_4008594_raw_a93339004453e006c5b6f46fd8729c682864e2f4_TeamCity_helperFunctions.ps1
|
#############################
# Mercilessly copied from https://github.com/kvarv/Continuous-Delivery
#############################
function TeamCity-TestSuiteStarted([string]$name) {
Write-Output "##teamcity[testSuiteStarted name='$name']"
}
function TeamCity-TestSuiteFinished([string]$name) {
Write-Output "##teamcity[testSuiteFinished name='$name']"
}
function TeamCity-TestStarted([string]$name) {
Write-Output "##teamcity[testStarted name='$name']"
}
function TeamCity-TestFinished([string]$name) {
Write-Output "##teamcity[testFinished name='$name']"
}
function TeamCity-TestIgnored([string]$name, [string]$message='') {
Write-Output "##teamcity[testIgnored name='$name' message='$message']"
}
function TeamCity-TestOutput([string]$name, [string]$output) {
Write-Output "##teamcity[testStdOut name='$name' out='$output']"
}
function TeamCity-TestError([string]$name, [string]$output) {
Write-Output "##teamcity[testStdErr name='$name' out='$output']"
}
function TeamCity-TestFailed([string]$name, [string]$message, [string]$details='', [string]$type='', [string]$expected='', [string]$actual='') {
$output="##teamcity[testFailed ";
if (![string]::IsNullOrEmpty($type)) {
$output += " type='$type'"
}
$output += " name='$name' message='$message' details='$details'"
if (![string]::IsNullOrEmpty($expected)) {
$output += " expected='$expected'"
}
if (![string]::IsNullOrEmpty($actual)) {
$output += " actual='$actual'"
}
$output += ']'
Write-Output $output
}
function TeamCity-PublishArtifact([string]$path) {
Write-Output "##teamcity[publishArtifacts '$path']"
}
function TeamCity-ReportBuildStart([string]$message) {
Write-Output "##teamcity[progessStart '$message']"
}
function TeamCity-ReportBuildProgress([string]$message) {
Write-Output "##teamcity[progessMessage '$message']"
}
function TeamCity-ReportBuildFinish([string]$message) {
Write-Output "##teamcity[progessFinish '$message']"
}
function TeamCity-ReportBuildStatus([string]$status, [string]$text='') {
Write-Output "##teamcity[buildStatus '$status' text='$text']"
}
function TeamCity-SetBuildNumber([string]$buildNumber) {
Write-Output "##teamcity[buildNumber '$buildNumber']"
}
function TeamCity-SetBuildStatistic([string]$key, [string]$value) {
Write-Output "##teamcity[buildStatisticValue key='$key' value='$value']"
}
function TeamCity-CreateInfoDocument([string]$buildNumber='', [boolean]$status=$true, [string[]]$statusText=$null, [System.Collections.IDictionary]$statistics=$null) {
$doc=New-Object xml;
$buildEl=$doc.CreateElement('build');
if (![string]::IsNullOrEmpty($buildNumber)) {
$buildEl.SetAttribute('number', $buildNumber);
}
$buildEl=$doc.AppendChild($buildEl);
$statusEl=$doc.CreateElement('statusInfo');
if ($status) {
$statusEl.SetAttribute('status', 'SUCCESS');
} else {
$statusEl.SetAttribute('status', 'FAILURE');
}
if ($statusText -ne $null) {
foreach ($text in $statusText) {
$textEl=$doc.CreateElement('text');
$textEl.SetAttribute('action', 'append');
$textEl.set_InnerText($text);
$textEl=$statusEl.AppendChild($textEl);
}
}
$statusEl=$buildEl.AppendChild($statusEl);
if ($statistics -ne $null) {
foreach ($key in $statistics.Keys) {
$val=$statistics.$key
if ($val -eq $null) {
$val=''
}
$statEl=$doc.CreateElement('statisticsValue');
$statEl.SetAttribute('key', $key);
$statEl.SetAttribute('value', $val.ToString());
$statEl=$buildEl.AppendChild($statEl);
}
}
return $doc;
}
function TeamCity-WriteInfoDocument([xml]$doc) {
$dir=(Split-Path $buildFile)
$path=(Join-Path $dir 'teamcity-info.xml')
$doc.Save($path);
}
|
PowerShellCorpus/GithubGist/talesin_f1f57242e2d367a6a539_raw_0c52313fb6e8cf5a24da90447829b683f9933ee0_vs.ps1
|
talesin_f1f57242e2d367a6a539_raw_0c52313fb6e8cf5a24da90447829b683f9933ee0_vs.ps1
|
function vs {
param($Path = ".")
if ($Path -inotmatch "\.sln$") { $Path = Join-Path $Path "*.sln" }
dir -ErrorAction SilentlyContinue -recurse *.sln |
&{
$d = @($input)
if ($d.Count -eq 1) { $d[0] }
elseif ($d.Count -eq 0) { $null }
else {
$choice = Read-Host ("Please select a solution:`n" + ($d | %{$i = 0} { "[$i] $_`n"; $i++ }))
$d[([int]$choice)]
}
} |
&{
$p = @($input)[0]
if ($p -ne $null) {
Write-Host "Opening $p"
& "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" $p
}
}
}
|
PowerShellCorpus/GithubGist/alienone_3f21fcd376187bd8871a_raw_1106521efbc04af855188b5f07e82f461b650cda_adjust_firewall.ps1
|
alienone_3f21fcd376187bd8871a_raw_1106521efbc04af855188b5f07e82f461b650cda_adjust_firewall.ps1
|
New-NetFirewallRule -DisplayName "ISP MQ Series" -Group "ISP" -Direction Inbound -Protocol TCP -LocalPort 1414, 1415 -Program "D:\mqm\bin\runmqlsr.exe (file:///D:/mqm/bin/runmqlsr.exe)" -Action Allow
|
PowerShellCorpus/GithubGist/tkmtmkt_2948484_raw_2c08fd8f81396e43f6f59989175081b198a269fe_gistfile1.ps1
|
tkmtmkt_2948484_raw_2c08fd8f81396e43f6f59989175081b198a269fe_gistfile1.ps1
|
gwmi -Namespace root\wmi WmiMonitorID | %{
New-Object PSObject -Property @{
ManufacturerName = -join ($_.ManufacturerName | %{[char]$_})
ProductCodeID = -join ($_.ProductCodeID | %{[char]$_})
SerialNumberID = -join ($_.SerialNumberID | %{[char]$_})
UserFriendlyName = -join ($_.UserFriendlyName | %{[char]$_})
WeekOfManufacture = $_.WeekOfManufacture
YearOfManufacture = $_.YearOfManufacture
}
}
|
PowerShellCorpus/GithubGist/guitarrapc_df61ae6b1080cc676d5c_raw_8e09257a4864cb8453be79a3812faf41008caf03_return%E3%81%AE%E7%BD%A0.ps1
|
guitarrapc_df61ae6b1080cc676d5c_raw_8e09257a4864cb8453be79a3812faf41008caf03_return%E3%81%AE%E7%BD%A0.ps1
|
1..3 | %{
return $_
$_
}
<#
1
2
3
#>
foreach ($x in (1..3))
{
return $x
$x
}
<#
1
#>
|
PowerShellCorpus/GithubGist/janikvonrotz_6622205_raw_a04167017b6f7deb42ca154827485c9d60956426_Sync-GitHubGists.ps1
|
janikvonrotz_6622205_raw_a04167017b6f7deb42ca154827485c9d60956426_Sync-GitHubGists.ps1
|
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
function Sync-GitHubGists{
param(
[string[]]$Url,
[string]$Path
)
# settings
$TagFileName = "Tags.txt"
$GithubGists = $null
$Url | %{
# get json
$WebClient = New-Object System.Net.WebClient
$webClient.Headers.Add("user-agent", "PowerShell Scripts")
$WebResponse = $WebClient.DownloadString($_)
# json to object
$JavaScriptSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$GitHubGists += $JavaScriptSerializer.DeserializeObject($WebResponse)
}
# get repos
$GitHubGists = $GitHubGists | select `
@{L="Name";E={($_.description).split("#")[0] -replace "`n","" -replace "`r","" -replace "`r`n",""}}, `
@{L="Tags";E={($_.description).split("#")[1..100] | %{"#$_" -replace "`n","" -replace "`r","" -replace "`r`n",""}}}, `
@{L="git_pull_url";E={$_.git_pull_url}}
# update or create local repos
$GitHubGists | %{
$LocalGitPath = Join-Path $Path ($_.Name -replace ":","")
if(Test-Path $LocalGitPath){
cd ($LocalGitPath)
Write-Host "Update GitHubGist: $($_.Name)"
git pull
}else{
$LocalGitClonePath = "`"$LocalGitPath`"" -replace "`n",""
Write-Host "Cloning GitHubGist: $($_.Name)"
git clone ($_.git_pull_url) $LocalGitClonePath
}
$TagFilePath = Join-Path $LocalGitPath $TagFileName
if(-not (Test-Path $TagFilePath)){New-Item -Path $TagFilePath -ItemType File}
Set-Content -Value $_.Tags -Path $TagFilePath
}
# delete old repos
$GitHubGistNames = $GitHubGists | %{"$($_.Name)" -replace ":",""}
Get-ChildItem -Path $Path | where{$_.psiscontainer -and $GitHubGistNames -notcontains $_.Name} | %{
Write-Host "Delete GitHubGist: $($_.Name)"
$_ | Remove-Item -Force -Recurse
}
}
Sync-GitHubGists -Url "https://api.github.com/users/janikvonrotz/gists?page=1", `
"https://api.github.com/users/janikvonrotz/gists?page=2", `
"https://api.github.com/users/janikvonrotz/gists?page=3", `
"https://api.github.com/users/janikvonrotz/gists?page=4", `
"https://api.github.com/users/janikvonrotz/gists?page=5", `
"https://api.github.com/users/janikvonrotz/gists?page=6", `
"https://api.github.com/users/janikvonrotz/gists?page=7", `
"https://api.github.com/users/janikvonrotz/gists?page=8", `
"https://api.github.com/users/janikvonrotz/gists?page=9", `
"https://api.github.com/users/janikvonrotz/gists?page=10" `
-Path (Get-Path "$($PSscripts.Path)/GitHubGist")
|
PowerShellCorpus/GithubGist/andrebocchini_4376306_raw_9845580a537dda9275d1ba310703e7e747e0290e_Find-RunningProcess.ps1
|
andrebocchini_4376306_raw_9845580a537dda9275d1ba310703e7e747e0290e_Find-RunningProcess.ps1
|
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]$computerNameList,
[parameter(Mandatory=$true)]$processName
)
foreach($computerName in $computerNameList) {
try {
$process = Get-Process -ComputerName $computerName | Where { $_.Name -like "$processName" } | Select-Object MachineName,Name,Id
if($process) {
Write-Host "$computerName`tRunning`t" -Foreground Green
} else {
Write-Host "$computerName`tNot Running`t" -Foreground Red
}
} catch [Exception] {
Write-Host "$computerName`tUnreachable " -Foreground Yellow
}
}
|
PowerShellCorpus/GithubGist/Vidanez_8d70df70e91c5d1103fc_raw_2eca53ab8aab87d3c4d7a894b31fa5f290e1debd_DeployVM.ps1
|
Vidanez_8d70df70e91c5d1103fc_raw_2eca53ab8aab87d3c4d7a894b31fa5f290e1debd_DeployVM.ps1
|
<#
.SYNOPSIS
Deploy Multiple VMs to vCenter
.DESCRIPTION
VMs are deployed asynchronously based on a pre-configured csv file (DeployVM.csv)
Designed to run from Powershell ISE
.PARAMETER csvfile
Path to DeployVM.csv file with new VM info
.PARAMETER vCenter
vCenter Server FQDN or IP
.PARAMETER auto
Will allow script to run with no review or confirmation
.PARAMETER createcsv
Generates a blank csv file - DeployVM.csv
.EXAMPLE
.\DeployVM.ps1
Runs DeployVM
.EXAMPLE
.\DeployVM.ps1 -vcenter my.vcenter.address
Runs DeployVM specifying vCenter address
.EXAMPLE
.\DeployVM.ps1 -csvfile "E:\Scripts\Deploy\DeployVM.csv" -vcenter my.vcenter.address -auto
Runs DeployVM specifying path to csv file, vCenter address and no confirmation
.EXAMPLE
.\DeployVM.ps1 -createcsv
Creates a new/blank DeployVM.csv file in same directory as script
.NOTES
Author: Shawn Masterson
Created: May 2014
Version: 1.2
Author: JJ Vidanez
Created: Nov 2014
Version: 1.3
Add creation onthefly for customization Spec for linux systems
Ability to create machines names and guest hostname using different names
Added a value to find out the kind of disk because powercli bug for SDRS reported at https://communities.vmware.com/message/2442684#2442684
Remove the dependency for an already created OScustomization Spec
REQUIREMENTS
PowerShell v3 or greater
vCenter (tested on 5.1/5.5)
PowerCLI 5.5 R2 or later
CSV File - VM info with the following headers
NameVM, Name, Boot, OSType, Template, CustSpec, Folder, ResourcePool, CPU, RAM, Disk2, Disk3, Disk4, SDRS, Datastore, DiskStorageFormat, NetType, Network, DHCP, IPAddress, SubnetMask, Gateway, pDNS, sDNS, Notes, Domain
Must be named DeployVM.csv
Can be created with -createcsv switch
CSV Field Definitions
NameVM - Name of VM
Name - Name of guest OS VM
Boot - Determines whether or not to boot the VM - Must be 'true' or 'false'
OSType - Must be 'Windows' or 'Linux'
Template - Name of existing template to clone
Folder - Folder in which to place VM in vCenter (optional)
ResourcePool - VM placement - can be a reasource pool, host or a cluster
CPU - Number of vCPU
RAM - Amount of RAM
Disk2 - Size of additional disk to add (GB)(optional)
Disk3 - Size of additional disk to add (GB)(optional)
Disk4 - Size of additional disk to add (GB)(optional)
SDRS - Mark to use a SDRS or not - Must be 'true' or 'false'
Datastore - Datastore placement - Can be a datastore or datastore cluster
DiskStorageFormat - Disk storage format - Must be 'Thin', 'Thick' or 'EagerZeroedThick' - Only funcional when SDRS = true
NetType - vSwitch type - Must be 'vSS' or 'vDS'
Network - Network/Port Group to connect NIC
DHCP - Use DHCP - Must be 'true' or 'false'
IPAddress - IP Address for NIC
SubnetMask - Subnet Mask for NIC
Gateway - Gateway for NIC
pDNS - Primary DNS must be populated
sDNS - Secondary NIC must be populated
Notes - Description applied to the vCenter Notes field on VM
Domain - DNS Domain must be populated
CREDITS
Handling New-VM Async - LucD - @LucD22
http://www.lucd.info/2010/02/21/about-async-tasks-the-get-task-cmdlet-and-a-hash-table/
http://blog.smasterson.com/2014/05/21/deploying-multiple-vms-via-powercli-updated-v1-2/
http://blogs.vmware.com/PowerCLI/2014/05/working-customization-specifications-powercli-part-1.html
http://blogs.vmware.com/PowerCLI/2014/06/working-customization-specifications-powercli-part-2.html
http://blogs.vmware.com/PowerCLI/2014/06/working-customization-specifications-powercli-part-3.html
USE AT YOUR OWN RISK!
.LINK
http://blog.smasterson.com/2014/05/21/deploying-multiple-vms-via-powercli-updated-v1-2/
http://www.vidanez.com/2014/11/02/crear-multiples-linux-vms-de-un-fichero-csv-usando-powercli-deploying-multiple-linux-vms-using-powercli/
#>
#requires -Version 3
#--------------------------------------------------------------------
# Parameters
param (
[parameter(Mandatory=$false)]
[string]$csvfile,
[parameter(Mandatory=$false)]
[string]$vcenter,
[parameter(Mandatory=$false)]
[switch]$auto,
[parameter(Mandatory=$false)]
[switch]$createcsv
)
#--------------------------------------------------------------------
# User Defined Variables
#--------------------------------------------------------------------
# Static Variables
$scriptName = "DeployVM"
$scriptVer = "1.3"
$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$starttime = Get-Date -uformat "%m-%d-%Y %I:%M:%S"
$logDir = $scriptDir + "\Logs\"
$logfile = $logDir + $scriptName + "_" + (Get-Date -uformat %m-%d-%Y_%I-%M-%S) + "_" + $env:username + ".txt"
$deployedDir = $scriptDir + "\Deployed\"
$deployedFile = $deployedDir + "DeployVM_" + (Get-Date -uformat %m-%d-%Y_%I-%M-%S) + "_" + $env:username + ".csv"
$exportpath = $scriptDir + "\DeployVM.csv"
$headers = "" | Select-Object NameVM, Name, Boot, OSType, Template, Folder, ResourcePool, CPU, RAM, Disk2, Disk3, Disk4, SDRS, Datastore, DiskStorageFormat, NetType, Network, DHCP, IPAddress, SubnetMask, Gateway, pDNS, sDNS, Notes, Domain
$taskTab = @{}
#--------------------------------------------------------------------
# Load Snap-ins
# Add VMware snap-in if required
If ((Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) {add-pssnapin VMware.VimAutomation.Core}
#--------------------------------------------------------------------
# Functions
Function Out-Log {
Param(
[Parameter(Mandatory=$true)][string]$LineValue,
[Parameter(Mandatory=$false)][string]$fcolor = "White"
)
Add-Content -Path $logfile -Value $LineValue
Write-Host $LineValue -ForegroundColor $fcolor
}
Function Read-OpenFileDialog([string]$WindowTitle, [string]$InitialDirectory, [string]$Filter = "All files (*.*)|*.*", [switch]$AllowMultiSelect)
{
Add-Type -AssemblyName System.Windows.Forms
$openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$openFileDialog.Title = $WindowTitle
if (![string]::IsNullOrWhiteSpace($InitialDirectory)) { $openFileDialog.InitialDirectory = $InitialDirectory }
$openFileDialog.Filter = $Filter
if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true }
$openFileDialog.ShowHelp = $true # Without this line the ShowDialog() function may hang depending on system configuration and running from console vs. ISE.
$openFileDialog.ShowDialog() > $null
if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename }
}
#--------------------------------------------------------------------
# Main Procedures
# Start Logging
Clear-Host
If (!(Test-Path $logDir)) {New-Item -ItemType directory -Path $logDir | Out-Null}
Out-Log "**************************************************************************************"
Out-Log "$scriptName`tVer:$scriptVer`t`t`t`tStart Time:`t$starttime"
Out-Log "**************************************************************************************`n"
# If requested, create DeployVM.csv and exit
If ($createcsv) {
If (Test-Path $exportpath) {
Out-Log "`n$exportpath Already Exists!`n" "Red"
Exit
} Else {
Out-Log "`nCreating $exportpath`n" "Yellow"
$headers | Export-Csv $exportpath -NoTypeInformation
Out-Log "Done!`n"
Exit
}
}
# Ensure PowerCLI is at least version 5.5 R2 (Build 1649237)
If ((Get-PowerCLIVersion).Build -lt 1649237) {
Out-Log "Error: DeployVM script requires PowerCLI version 5.5 R2 (Build 1649237) or later" "Red"
Out-Log "PowerCLI Version Detected: $((Get-PowerCLIVersion).UserFriendlyVersion)" "Red"
Out-Log "Exiting...`n`n" "Red"
Exit
}
# Test to ensure csv file is available
If ($csvfile -eq "" -or !(Test-Path $csvfile) -or !$csvfile.EndsWith("DeployVM.csv")) {
Out-Log "Path to DeployVM.csv not specified...prompting`n" "Yellow"
$csvfile = Read-OpenFileDialog "Locate DeployVM.csv" "C:\" "DeployVM.csv|DeployVM.csv"
}
If ($csvfile -eq "" -or !(Test-Path $csvfile) -or !$csvfile.EndsWith("DeployVM.csv")) {
Out-Log "`nStill can't find it...I give up" "Red"
Out-Log "Exiting..." "Red"
Exit
}
Out-Log "Using $csvfile`n" "Yellow"
# Make copy of DeployVM.csv
If (!(Test-Path $deployedDir)) {New-Item -ItemType directory -Path $deployedDir | Out-Null}
Copy-Item $csvfile -Destination $deployedFile | Out-Null
# Import VMs from csv
$newVMs = Import-Csv $csvfile
$newVMs = $newVMs | Where {$_.Name -ne ""}
[INT]$totalVMs = @($newVMs).count
Out-Log "New VMs to create: $totalVMs" "Yellow"
# Check to ensure csv is populated
If ($totalVMs -lt 1) {
Out-Log "`nError: No entries found in DeployVM.csv" "Red"
Out-Log "Exiting...`n" "Red"
Exit
}
# Show input and ask for confirmation, unless -auto was used
If (!$auto) {
$newVMs | Out-GridView -Title "VMs to be Created"
$continue = Read-Host "`nContinue (y/n)?"
If ($continue -notmatch "y") {
Out-Log "Exiting..." "Red"
Exit
}
}
# Connect to vCenter server
If ($vcenter -eq "") {$vcenter = Read-Host "`nEnter vCenter server FQDN or IP"}
Try {
Out-Log "`nConnecting to vCenter - $vcenter`n`n" "Yellow"
Connect-VIServer $vcenter -EA Stop | Out-Null
} Catch {
Out-Log "`r`n`r`nUnable to connect to $vcenter" "Red"
Out-Log "Exiting...`r`n`r`n" "Red"
Exit
}
# Start provisioning VMs
$v = 0
Out-Log "Deploying VMs`n" "Yellow"
Foreach ($VM in $newVMs) {
$Error.Clear()
$vmName = $VM.Name
$v++
$vmStatus = "[{0} of {1}] {2}" -f $v, $newVMs.count, $vmName
Write-Progress -Activity "Deploying VMs" -Status $vmStatus -PercentComplete (100*$v/($newVMs.count))
# Create custom OS Custumization spec
If ($vm.DHCP -match "true") {
If ($VM.OSType -eq "Windows") {
$tempSpec = New-OSCustomizationSpec -Name temp$vmName -NamingScheme fixed `
-NamingPrefix $VM.Name -Domain $VM.domain -OSType Windows
$tempSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping `
-IpMode UseDhcp | Out-Null
} ElseIF ($VM.OSType -eq "Linux") {
$tempSpec = New-OSCustomizationSpec -Name temp$vmName -NamingScheme fixed `
-NamingPrefix $VM.Name -Domain $VM.domain -OSType Linux -DnsServer $VM.pDNS,$VM.sDNS
$tempSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping `
-IpMode UseDhcp | Out-Null
}
} Else {
If ($VM.OSType -eq "Windows") {
$tempSpec = New-OSCustomizationSpec -Name temp$vmName -NamingScheme fixed `
-NamingPrefix $VM.Name -Domain $VM.domain -OSType Windows
$tempSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping `
-IpMode UseStaticIP -IpAddress $VM.IPAddress -SubnetMask $VM.SubnetMask `
-Dns $VM.pDNS,$VM.sDNS -DefaultGateway $VM.Gateway | Out-Null
} ElseIF ($VM.OSType -eq "Linux") {
$tempSpec = New-OSCustomizationSpec -Name temp$vmName -NamingScheme fixed `
-NamingPrefix $VM.Name -Domain $VM.domain -OSType Linux -DnsServer $VM.pDNS,$VM.sDNS
$tempSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping `
-IpMode UseStaticIP -IpAddress $VM.IPAddress -SubnetMask $VM.SubnetMask -DefaultGateway $VM.Gateway | Out-Null
}
}
# Create VM depeding on the parameter SDRS true or false
Out-Log "Deploying $vmName"
If ($VM.SDRS -match "true") {
Out-Log "SDRS Cluster disk on $vmName - removing DiskStorageFormat parameter " "Yellow"
$taskTab[(New-VM -Name $VM.NameVM -ResourcePool $VM.ResourcePool -Location $VM.Folder -Datastore $VM.Datastore `
-Notes $VM.Notes -Template $VM.Template -OSCustomizationSpec temp$vmName -RunAsync -EA SilentlyContinue).Id] = $VM.Name
} Else {
Out-Log "NON SDRS Cluster disk on $vmName - using DiskStorageFormat parameter " "Yellow"
$taskTab[(New-VM -Name $VM.NameVM -ResourcePool $VM.ResourcePool -Location $VM.Folder -Datastore $VM.Datastore `
-DiskStorageFormat $VM.DiskStorageFormat -Notes $VM.Notes -Template $VM.Template -OSCustomizationSpec temp$vmName -RunAsync -EA SilentlyContinue).Id] = $VM.Name
}
# Remove temp OS Custumization spec
Remove-OSCustomizationSpec -OSCustomizationSpec temp$vmName -Confirm:$false
# Log errors
If ($Error.Count -ne 0) {
If ($Error.Count -eq 1 -and $Error.Exception -match "'Location' expects a single value") {
$vmLocation = $VM.Folder
Out-Log "Unable to place $vmName in desired location, multiple $vmLocation folders exist, check root folder" "Red"
} Else {
Out-Log "`n$vmName failed to deploy!" "Red"
Foreach ($err in $Error) {
Out-Log "$err" "Red"
}
$failDeploy += @($vmName)
}
}
}
Out-Log "`n`nAll Deployment Tasks Created" "Yellow"
Out-Log "`n`nMonitoring Task Processing" "Yellow"
# When finsihed deploying, reconfigure new VMs
$totalTasks = $taskTab.Count
$runningTasks = $totalTasks
while($runningTasks -gt 0){
$vmStatus = "[{0} of {1}] {2}" -f $runningTasks, $totalTasks, "Tasks Remaining"
Write-Progress -Activity "Monitoring Task Processing" -Status $vmStatus -PercentComplete (100*($totalTasks-$runningTasks)/$totalTasks)
Get-Task | % {
if($taskTab.ContainsKey($_.Id) -and $_.State -eq "Success"){
#Deployment completed
$Error.Clear()
$vmName = $taskTab[$_.Id]
Out-Log "`n`nReconfiguring $vmName" "Yellow"
$VM = Get-VM $vmName
$VMconfig = $newVMs | Where {$_.Name -eq $vmName}
# Set CPU and RAM
Out-Log "Setting vCPU(s) and RAM on $vmName" "Yellow"
$VM | Set-VM -NumCpu $VMconfig.CPU -MemoryGB $VMconfig.RAM -Confirm:$false | Out-Null
# Set port group on virtual adapter
Out-Log "Setting Port Group on $vmName" "Yellow"
If ($VMconfig.NetType -match "vSS") {
$network = @{
'NetworkName' = $VMconfig.network
'Confirm' = $false
}
} Else {
$network = @{
'Portgroup' = $VMconfig.network
'Confirm' = $false
}
}
$VM | Get-NetworkAdapter | Set-NetworkAdapter @network | Out-Null
# Add additional disks if needed
If ($VMConfig.Disk2 -gt 1) {
Out-Log "Adding additional disk on $vmName - don't forget to format within the OS" "Yellow"
$VM | New-HardDisk -CapacityGB $VMConfig.Disk2 -StorageFormat $VMConfig.DiskStorageFormat -Persistence persistent | Out-Null
}
If ($VMConfig.Disk3 -gt 1) {
Out-Log "Adding additional disk on $vmName - don't forget to format within the OS" "Yellow"
$VM | New-HardDisk -CapacityGB $VMConfig.Disk3 -StorageFormat $VMConfig.DiskStorageFormat -Persistence persistent | Out-Null
}
If ($VMConfig.Disk4 -gt 1) {
Out-Log "Adding additional disk on $vmName - don't forget to format within the OS" "Yellow"
$VM | New-HardDisk -CapacityGB $VMConfig.Disk4 -StorageFormat $VMConfig.DiskStorageFormat -Persistence persistent | Out-Null
}
# Boot VM
If ($VMconfig.Boot -match "true") {
Out-Log "Booting $vmName" "Yellow"
$VM | Start-VM -EA SilentlyContinue | Out-Null
}
$taskTab.Remove($_.Id)
$runningTasks--
If ($Error.Count -ne 0) {
Out-Log "$vmName completed with errors" "Red"
Foreach ($err in $Error) {
Out-Log "$Err" "Red"
}
$failReconfig += @($vmName)
} Else {
Out-Log "$vmName is Complete" "Green"
$successVMs += @($vmName)
}
}
elseif($taskTab.ContainsKey($_.Id) -and $_.State -eq "Error"){
# Deployment failed
$failed = $taskTab[$_.Id]
Out-Log "`n$failed failed to deploy!`n" "Red"
$taskTab.Remove($_.Id)
$runningTasks--
$failDeploy += @($failed)
}
}
Start-Sleep -Seconds 10
}
#--------------------------------------------------------------------
# Close Connections
Disconnect-VIServer -Server $vcenter -Force -Confirm:$false
#--------------------------------------------------------------------
# Outputs
Out-Log "`n**************************************************************************************"
Out-Log "Processing Complete" "Yellow"
If ($successVMs -ne $null) {
Out-Log "`nThe following VMs were successfully created:" "Yellow"
Foreach ($success in $successVMs) {Out-Log "$success" "Green"}
}
If ($failReconfig -ne $null) {
Out-Log "`nThe following VMs failed to reconfigure properly:" "Yellow"
Foreach ($reconfig in $failReconfig) {Out-Log "$reconfig" "Red"}
}
If ($failDeploy -ne $null) {
Out-Log "`nThe following VMs failed to deploy:" "Yellow"
Foreach ($deploy in $failDeploy) {Out-Log "$deploy" "Red"}
}
$finishtime = Get-Date -uformat "%m-%d-%Y %I:%M:%S"
Out-Log "`n`n"
Out-Log "**************************************************************************************"
Out-Log "$scriptName`t`t`t`t`tFinish Time:`t$finishtime"
Out-Log "**************************************************************************************"
|
PowerShellCorpus/GithubGist/meadhikari_a677fa835ee3b73a3d3f_raw_6f7f35ea4ecc3218cc9c8d2a795c3176b0333291_deactivate.ps1
|
meadhikari_a677fa835ee3b73a3d3f_raw_6f7f35ea4ecc3218cc9c8d2a795c3176b0333291_deactivate.ps1
|
$connection = new-object System.Data.SqlClient.SQLConnection("Data Source=.;Integrated Security=SSPI;Initial Catalog=aspnetdb");
$cmd = new-object System.Data.SqlClient.SqlCommand("UPDATE dbo.aspnet_Membership SET IsApproved = 0 where LastLoginDate < DATEADD(DAY, -30, GETDATE())", $connection);
$connection.Open();
$reader = $cmd.ExecuteNonQuery()
$connection.Close();
Write-output $reader
|
PowerShellCorpus/GithubGist/gilmation_466630_raw_4554a8e5d96549ff0a4a94e6310cc40fffa08fbe_Microsoft.PowerShell_profile.ps1
|
gilmation_466630_raw_4554a8e5d96549ff0a4a94e6310cc40fffa08fbe_Microsoft.PowerShell_profile.ps1
|
# Set the execution policy
Set-ExecutionPolicy RemoteSigned
# Set up functions
# To use this profile the following environment variables must exist:
# They can be created by substituting:
# $VALUE for the value that you want for each variable
# The third argument can be either of Process|User|Machine.
# Process gets and sets to the current window
# so for persistent values use User|Machine but remember that to avoid problems
# use the same option for both get and set.
# Run these commands in a PowerShell window
#
# [Environment]::SetEnvironmentVariable("WORKSPACE_HOME", "$VALUE", "User")
# [Environment]::SetEnvironmentVariable("EXAMPLE_HOME", "$VALUE", "User")
# [Environment]::SetEnvironmentVariable("EXAMPLE_DB_HOME", "$VALUE", "User")
# [Environment]::SetEnvironmentVariable("DATA_HOME", "$VALUE", "User")
# [Environment]::SetEnvironmentVariable("SELENIUM_HOME", "$VALUE", "User")
# Create the shortcut functions to move us into project dirs
function workspace {cd $([Environment]::GetEnvironmentVariable('WORKSPACE_HOME', 'User'))}
function example {cd $([Environment]::GetEnvironmentVariable('EXAMPLE_HOME', 'User'))}
function exampleDB {cd $([Environment]::GetEnvironmentVariable('EXAMPLE_DB_HOME', 'User'))}
# Database functions
# Connect to the mysql schema for the project EXAMPLE_DB_HOME
function con_mysql_ex {& "$([Environment]::GetEnvironmentVariable('EXAMPLE_DB_HOME', 'User'))\bin\mysql.ps1"}
# Connect to the mysql test schema for the project EXAMPLE_DB_HOME
function con_mysql_ex_test {& "$([Environment]::GetEnvironmentVariable('EXAMPLE_DB_HOME', 'User'))\bin\mysqlTest.ps1"}
# refresh the mysql schema for the project EXAMPLE_DB_HOME
function ref_ex {& "$([Environment]::GetEnvironmentVariable('EXAMPLE_DB_HOME', 'User'))\bin\createExampleAll.ps1"}
# refresh the mysql test schema for the project EXAMPLE_DB_HOME
function ref_ex_test {& "$([Environment]::GetEnvironmentVariable('EXAMPLE_DB_HOME', 'User'))\bin\createExampleAllTest.ps1"}
# Launch GVim - the path could be moved out into an environmental variable
function vim {[diagnostics.process]::start("C:\Vim\vim72\gvim.exe", "$args")}
# Show the environment ordered by variable name
function geten {get-childitem env: | sort-object -property name}
# Show the list of available functions - including those defined here
function getfu {get-item function:}
# As close to a Unix tail as we can get
function tail {
if($args.length -lt 1) {
write-host Usage: "tail $TARGET_FILE"
return
}
Get-Content $args[0] -wait
}
# Kill the launchy process
function killLaunchy {
kill (ps Launchy).get_Id()
}
# Generate a database schema using the phing and propel
#function genDataSchema {
# cd $env:PROPEL_HOME\generator
# phing reverse "-Dproject.dir=$([Environment]::GetEnvironmentVariable('DATA_HOME', 'User'))\build\propel"
#}
# Copy data from one dir to another drive - if there are files that already exist in the target dir overwrite them
#function copyData {cp -rec "$env:DATA_HOME\**" "Z:\tmp" -ErrorAction SilentlyContinue}
# Startup the selenium java server
#function startSelenium {java "-Dhttp.proxyHost=192.168.0.27" "-Dhttp.proxyPort=3128" -jar "$([Environment]::GetEnvironmentVariable('SELENIUM_HOME', 'User'))\selenium-server-1.0-beta-2\selenium-server.jar" -firefoxProfileTemplate "C:\Documents and Settings\hgilmour\Datos de programa\Mozilla\Firefox\Profiles\qvs55du3.default"}
# Aliases
Set-Alias ll get-childitem
|
PowerShellCorpus/GithubGist/guitarrapc_670ff96a2a3966613a0d_raw_634c6ced8a7438af5377ed0043906d67df76264a_InvalidOutputType.ps1
|
guitarrapc_670ff96a2a3966613a0d_raw_634c6ced8a7438af5377ed0043906d67df76264a_InvalidOutputType.ps1
|
function nyao
{
[OutputType([int])]
[CmdletBinding()]
param()
return [uri]"http://google.com"
}
|
PowerShellCorpus/GithubGist/fishnugget77_4151288_raw_9ad2b9e66033bdb175e560580b8ea46e0f737fa5_post-build.ps1
|
fishnugget77_4151288_raw_9ad2b9e66033bdb175e560580b8ea46e0f737fa5_post-build.ps1
|
mkdir "%USERPROFILE%\RightNowDev"
mkdir "%USERPROFILE%\RightNowDev\AddIns"
mkdir "%USERPROFILE%\RightNowDev\AddIns\$(TargetName)"
copy /Y "$(TargetDir)$(TargetName).*" "%USERPROFILE%\RightNowDev\AddIns\$(TargetName)\"
|
PowerShellCorpus/GithubGist/smasterson_9141509_raw_623fd4dacc566a27269713176c50bf52f7ff5273_VeeamSingleBackup.ps1
|
smasterson_9141509_raw_623fd4dacc566a27269713176c50bf52f7ff5273_VeeamSingleBackup.ps1
|
# Load Veeam snapin
Add-PsSnapin -Name VeeamPSSnapIn -ErrorAction SilentlyContinue
Clear-Host
Write-Host "VM must be explicitly defined in the job"
Write-Host "VM can not be inherited by a folder, datastore or other object or it will get excluded as well and job will be empty."
Write-Host ""
Write-Host "Always confirm job completion via Veeam BR Console"
Write-Host ""
# Check Veeam Version (Must be v7)
If ((Get-PSSnapin VeeamPSSnapin).Version.Major -ne 7) {
Write-Host "You must be running VBR v7 to run this script...Exiting"
Exit
}
# User Input
$jobName = Read-Host "Enter Job Name"
$vmName = Read-Host "Enter VM Name"
# Find the job that has our VM
$job = Get-VBRJob | ?{$_.Name -eq $jobName}
# Get all objects in job apart from our target VM
$execObjs = $job.GetObjectsInJob() | ?{$_.Name -ne $vmName}
# Exclude the objects from the job(*Note: this isn't removing the objects
# from the job)
Remove-VBRJobObject -Objects $execObjs
# Start the job only backing up the target VM
Start-VBRJob -Job $job
# Find the exclude job objects
$incObjs = $job.GetObjectsInJob() | ?{$_.Type -eq "Exclude"}
# Delete the exclude objects and re-add to job
foreach ($obj in $incObjs) {
$Excitem = $obj.GetObject().GetItem()
Add-VBRViJobObject -job $Job -Entities $Excitem
$obj.Delete() | Out-Null
}
|
PowerShellCorpus/GithubGist/thoemmi_2937183_raw_40ffb1851a4d9bce1ac09704f335dc27472bfd15_Add-XmlFragment.ps1
|
thoemmi_2937183_raw_40ffb1851a4d9bce1ac09704f335dc27472bfd15_Add-XmlFragment.ps1
|
<#
.SYNOPSIS
Adds an XML fragment to an XmlNode
.DESCRIPTION
Adds an XML fragment to an XmlNode
.NOTES
Author : Thomas Freudenberg - info@thomasfreudenberg.com
.EXAMPLE
Add-XmlFragment $xml.configuration.connectionStrings "<add name='MyConString' connectionString='...' providerName='...'>"
Adds the connection string "MyConString" to the web.config file.
#>
function Add-XmlFragment {
Param(
[Parameter(Mandatory=$true)][System.Xml.XmlNode] $xmlElement,
[Parameter(Mandatory=$true)][string] $text)
$xml = $xmlElement.OwnerDocument.ImportNode(([xml]$text).DocumentElement, $true)
[void]$xmlElement.AppendChild($xml)
}
|
PowerShellCorpus/GithubGist/rbocchinfuso_9368894_raw_59beb30c7c3acec04579e1b84ae1e5ed7f7fb414_check_vm_snaps.ps1
|
rbocchinfuso_9368894_raw_59beb30c7c3acec04579e1b84ae1e5ed7f7fb414_check_vm_snaps.ps1
|
# PowerShell script to check for VM snapshots and send Email report
add-pssnapin VMware.VimAutomation.Core
Connect-VIServer -Server 'vcenter' -User 'domain\user' -Password 'password'
# HTML formatting
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: LightBlue}"
$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: white}"
$a = $a + "</style>"
# Main section of check
Write-Host "Checking VMs for for snapshots"
$date = get-date
$datefile = get-date -uformat '%m-%d-%Y-%H%M%S'
$filename = "x:\dir\Snaps_" + $datefile + ".htm"
# Get list of VMs with snapshots
# Note: It may take some time for the Get-VM cmdlet to enumerate VMs in larger environments
$ss = Get-vm | Get-Snapshot
Write-Host " Complete" -ForegroundColor Green
Write-Host "Generating VM snapshot report"
#$ss | Select-Object vm, name, description, powerstate | ConvertTo-HTML -head $a -body "<H2>VM Snapshot Report</H2>"| Out-File $filename
$ss | Select-Object vm, name, description | ConvertTo-HTML -head $a -body "<H2>VM Snapshot Report</H2>"| Out-File $filename
Write-Host " Complete" -ForegroundColor Green
Write-Host "Your snapshot report has been saved to:" $filename
# Create mail message
$server = "smtp.domain.com"
$port = 25
$to = "user@domain.com"
$from = "user@domain.com"
$subject = "VM Snapshot Report"
$body = Get-Content $filename
$message = New-Object system.net.mail.MailMessage $from, $to, $subject, $body
# Create SMTP client
$client = New-Object system.Net.Mail.SmtpClient $server, $port
# Credentials are necessary if the server requires the client # to authenticate before it will send e-mail on the client's behalf.
$client.Credentials = [system.Net.CredentialCache]::DefaultNetworkCredentials
# Try to send the message
try {
# Convert body to HTML
$message.IsBodyHTML = $true
# Uncomment these lines if you want to attach the html file to the email message
# $attachment = new-object Net.Mail.Attachment($filename)
# $message.attachments.add($attachment)
# Send message
$client.Send($message)
"Message sent successfully"
}
#Catch error
catch {
"Exception caught in CreateTestMessage1(): "
}
|
PowerShellCorpus/GithubGist/thiagowfx_7223952_raw_bd78c26a96b71739f532f54a0ba35b2655771523_gistfile1.ps1
|
thiagowfx_7223952_raw_bd78c26a96b71739f532f54a0ba35b2655771523_gistfile1.ps1
|
# move openbox config dir to github repo
mv ~/.config/openbox ~/git/openbox
# symlink back
ln -s ~/git/openbox/openbox ~/.config/openbox
|
PowerShellCorpus/GithubGist/andrebocchini_6368082_raw_26edb8d6e5f22f0a901161c48aed1961f3d5558b_gistfile1.ps1
|
andrebocchini_6368082_raw_26edb8d6e5f22f0a901161c48aed1961f3d5558b_gistfile1.ps1
|
Function New-SCCMSupportedPlatform {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[string]
$name,
[parameter(Mandatory=$true, Position=1)]
[ValidateNotNullOrEmpty()]
[string]
$maxVersion,
[parameter(Mandatory=$true, Position=2)]
[ValidateNotNullOrEmpty()]
[string]
$minVersion,
[parameter(Mandatory=$true, Position=3)]
[ValidateNotNullOrEmpty()]
[string]
$platform
)
$newPlatform = ([WMIClass]("\\$siteProvider\root\sms\site_" + "$siteCode" + ":SMS_OS_Details")).CreateInstance()
if($newPlatform) {
$newPlatform.Name = $name
$newPlatform.MaxVersion = $maxVersion
$newPlatform.MinVersion = $minVersion
$newPlatform.Platform = $platform
return $newPlatform
} else {
Throw "Unable to create new supported platform"
}
}
Function Print-PlatformDetails {
param(
$platform
)
Write-Host "`nName: $($platform.Name)"
Write-Host "Min Version: $($platform.MinVersion)"
Write-Host "Max Version: $($platform.MaxVersion)"
Write-Host "Platform: $($platform.Platform)"
}
# Configure these with values relevant to your site
$siteProvider = "server.contoso.com"
$siteCode = "xxx"
# Find a way to build the list of programs you want to change.
# For this example, I'm only getting a single program (since I
# only created a single test program in my site with this name)
# whose name matches the name entered in the variable $programName.
$programName = "Program-OS-Test"
$allPrograms = Get-WMIObject -ComputerName $siteProvider -Namespace "root\sms\site_$siteCode" -Query "SELECT * FROM SMS_Program WHERE ProgramName='$programName'"
# If you want, you can get more creative and match programs to packages
# or whatever other criteria you want. Look up SMS_Program
# (http://msdn.microsoft.com/en-us/library/cc144361.aspx) and
# SMS_Package (http://msdn.microsoft.com/en-us/library/cc144959.aspx)
# for some ideas on what criteria you can use. For example, to get
# all programs belonging to a particular package:
# $packageId = "XXX00001"
# $allPrograms = Get-WMIObject -ComputerName $siteProvider -Namespace "root\sms\site_$siteCode" -Query "SELECT * FROM SMS_Program WHERE PackageID='$packageId' AND ProgramName='$programName'"
# Now you need a list of all the platforms you want to support. Each platform
# is represented by an SMS_OS_Details (http://msdn.microsoft.com/en-us/library/cc146485.aspx)
# object. You have to create an array containing all of the objects you want.
# Once you have that array, you put it into the SupportedOperatingSystems
# property of your SMS_Program. In this example, I'm only creating two
# supported platforms. One for all Windows 7 x64 (6.10), and one for all
# Windows 8 x64 (6.20). If you want to see a list of all the supported
# platforms on your server, run this:
# Get-WmiObject -ComputerName $siteProvider -Namespace "root\sms\site_$siteCode" -Query "Select * From SMS_SupportedPlatforms"
$allPlatformsWeWantToAddToProgram = @()
$allPlatformsWeWantToAddToProgram += New-SCCMSupportedPlatform -name "Win NT" -maxVersion "6.10.9999.9999" -minVersion "6.10.0000.0"` -platform "x64"
$allPlatformsWeWantToAddToProgram += New-SCCMSupportedPlatform -name "Win NT" -maxVersion "6.20.9999.9999" -minVersion "6.20.0000.0"` -platform "x64"
foreach ($program in $allPrograms) {
$program.Get() # SupportedOperatingSystems is a lazy property so we have to do a Get() on the program
$allCurrentlySupportedPlatformsForThisProgram = $program.SupportedOperatingSystems
Write-Host "`n>>> Program Name: $($program.ProgramName)"
Write-Host ">>> Package ID: $($program.PackageID)"
Write-Host ">>> Platforms this package currently supports:"
foreach ($supportedPlatform in $allCurrentlySupportedPlatformsForThisProgram) {
Print-PlatformDetails $supportedPlatform
}
foreach ($newPlatformWeWantToAddToProgram in $allPlatformsWeWantToAddToProgram) {
Write-Host "`n>>> Checking if the following platform is supported:"
Print-PlatformDetails $newPlatformWeWantToAddToProgram
if ($allCurrentlySupportedPlatformsForThisProgram -contains $newPlatformWeWantToAddToProgram) {
Write-Host "`n>>> Platform is already supported by this program"
} else {
Write-Host "`n>>> Platform is not already supported. Adding it..."
$allCurrentlySupportedPlatformsForThisProgram += $newPlatformWeWantToAddToProgram
}
}
# This makes sure the "Only on specified platforms" checkbox is checked
if ($program.ProgramFlags -band 0x08000000) {
Write-Host "`n>>> Checking `"Only on specified client platforms`" box"
$program.ProgramFlags = $program.ProgramFlags -bxor 0x08000000
} else {
Write-Host "`n>>> `"Only on specified client platforms`" box is already checked"
}
Write-Host "`n>>> Setting supported platforms"
$program.SupportedOperatingSystems = $allCurrentlySupportedPlatformsForThisProgram
# If you decide to clear the list of supported platforms, use an empty array and
# uncheck the "Only on specified client platforms" by XOR'ing it if it's already checked
<#
if ($program.ProgramFlags -band 0x08000000) {
Write-Host "`n>>> `"Only on specified client platforms`" box is already unchecked"
} else {
Write-Host "`n>>> Un-checking `"Only on specified client platforms`" box"
$program.ProgramFlags = $program.ProgramFlags -bxor 0x08000000
}
Write-Host "`n>>> Clearing all supported platforms"
$program.SupportedOperatingSystems = @()
#>
# And here you "save" the program back into the database
Write-Host "`n>>> Saving program"
$program.Put()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.