full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/GithubGist/bill-long_10150938_raw_f0d45b8400ec957af8a58ebd8f54020abbc870e9_Fix-MailEnabled.ps1
|
bill-long_10150938_raw_f0d45b8400ec957af8a58ebd8f54020abbc870e9_Fix-MailEnabled.ps1
|
# Fix-MailEnabled.ps1
#
# The purpose of this script is to read an ExFolders or PFDAVAdmin
# property export of public folders, and fix the folders where the
# mail-enabled state is not consistent.
#
# The export must include the following properties:
# PR_PF_PROXY, PR_PF_PROXY_REQUIRED, DS:proxyAddresses
#
# The export can optionally include the following
# properties, and if they are included, the script will preserve
# that setting:
# DS:msExchHideFromAddressLists
#
# This script must be run from Exchange Management Shell.
# File is required, ExchangeServer and DC are optional
# Example syntax:
# .\Fix-MailEnabled C:\ExFoldersExport.txt
# .\Fix-MailEnabled C:\ExFoldersExport.txt CONTOSO1 DC01
# .\Fix-MailEnabled -File C:\ExFoldersExport.txt -ExchangeServer CONTOSO1 -DC DC01
param([string]$File, [string]$ExchangeServer, [string]$DC, [string]$emailAddress, [string]$smtpServer)
# Log file stuff
$ScriptPath = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
$Global:LogFileName = "FixMailEnabled"
$Global:LogFile = $ScriptPath + "\" + $LogFileName + ".log"
$Global:ErrorLogFile = $ScriptPath + "\FixMailEnabled-Errors.log"
$sendEmailOnError = $false
if ($emailAddress -ne $null -and $emailAddress.Length -gt 0 -and $smtpServer -ne $null -and $smtpServer.Length -gt 0)
{
$sendEmailOnError = $true
}
function Test-Transcribing
{
$externalHost = $host.gettype().getproperty("ExternalHost", [reflection.bindingflags]"NonPublic,Instance").getvalue($host, @())
try
{
$externalHost.gettype().getproperty("IsTranscribing", [reflection.bindingflags]"NonPublic,Instance").getvalue($externalHost, @())
}
catch
{
write-warning "This host does not support transcription."
}
}
function writelog([string]$value = "")
{
$Global:LogDate = Get-Date -uformat "%Y %m-%d %H:%M:%S"
("$LogDate $value")
}
function writeerror([string]$value = "")
{
$Global:LogDate = Get-Date -uformat "%Y %m-%d %H:%M:%S"
Add-Content -Path $Global:ErrorLogFile -Value ("$LogDate $value")
if ($sendEmailOnError)
{
writelog("Sending email notification...")
Send-MailMessage -From "Fix-MailEnabled@Fix-MailEnabled" -To $emailAddress -Subject "Fix-MailEnabled script error" `
-Body $value -SmtpServer $smtpServer
}
}
$isTranscribing = Test-Transcribing
if (!($isTranscribing))
{
$transcript = Start-Transcript $Global:LogFile -Append
writelog ($transcript)
}
else
{
writelog ("Transcript already started. Logging to the current file will continue.")
}
writelog ("Fix-MailEnabled starting.")
# Directory objects will be exported prior to deletion. This could
# potentionally create a lot of export files. By default these are
# put in the same folder as the script. If you want to put them
# elsewhere, change this path and make sure the folder exists.
$ExportPath = $ScriptPath
if ($ExchangeServer -eq "")
{
# Choose a PF server
$pfdbs = Get-PublicFolderDatabase
if ($pfdbs.Length -ne $null)
{
$ExchangeServer = $pfdbs[0].Server.Name
}
else
{
$ExchangeServer = $pfdbs.Server.Name
}
writelog ("ExchangeServer parameter was not supplied. Using server: " + $ExchangeServer)
}
if ($DC -eq "")
{
# Choose a DC
$rootDSE = [ADSI]("LDAP://RootDSE")
$DC = $rootDSE.Properties.dnsHostName
writelog ("DC parameter was not supplied. Using DC: " + $DC)
}
$reader = new-object System.IO.StreamReader($File)
# The first line in this file must be the header line, so we can
# figure out which column is which. Folder Path is always the
# first column in an ExFolders property export.
$headerLine = $reader.ReadLine()
if (!($headerLine.StartsWith("Folder Path")))
{
writelog "The input file doesn't seem to have the headers on the first line."
return
}
# Figure out which column is which
$folderPathIndex = -1
$proxyIndex = -1
$proxyRequiredIndex = -1
$proxyAddressesIndex = -1
$hideFromAddressListsIndex = -1
$headers = $headerLine.Split("`t")
for ($x = 0; $x -lt $headers.Length; $x++)
{
if ($headers[$x] -eq "Folder Path")
{
$folderPathIndex = $x
}
elseif ($headers[$x] -eq "PR_PF_PROXY: 0x671D0102")
{
$proxyIndex = $x
}
elseif ($headers[$x] -eq "PR_PF_PROXY_REQUIRED: 0x671F000B")
{
$proxyRequiredIndex = $x
}
elseif ($headers[$x] -eq "DS:proxyAddresses")
{
$proxyAddressesIndex = $x
}
elseif ($headers[$x] -eq "DS:msExchHideFromAddressLists")
{
$hideFromAddressListsIndex = $x
}
}
if ($folderPathIndex -lt 0 -or `
$proxyIndex -lt 0 -or `
$proxyRequiredIndex -lt 0 -or `
$proxyAddressesIndex -lt 0)
{
writelog "Required columns were not present in the input file."
writelog "Headers found:"
writelog $headers
return
}
# Loop through the lines in the file
while ($null -ne ($buffer = $reader.ReadLine()))
{
$columns = $buffer.Split("`t")
if ($columns.Length -lt 4)
{
continue
}
# Folder paths from ExFolders always start with "Public Folders" or
# "System Folders", so trim the first 14 characters.
$folderPath = $columns[$folderPathIndex].Substring(14)
$guidString = $columns[$proxyIndex]
$proxyRequired = $columns[$proxyRequiredIndex]
$proxyAddresses = $columns[$proxyAddressesIndex]
$hideFromAddressLists = $false
if ($hideFromAddressListsIndex -gt -1)
{
if ($columns[$hideFromAddressListsIndex] -eq "True")
{
$hideFromAddressLists = $true
}
}
if ($proxyRequired -ne "True" -and $proxyRequired -ne "1" -and $guidString -ne "PropertyError: NotFound" -and $guidString -ne "" -and $guidString -ne $null)
{
# does this objectGUID actually exist?
$proxyObject = [ADSI]("LDAP://" + $DC + "/<GUID=" + $guidString + ">")
if ($proxyObject.Path -eq $null)
{
# It's possible the object is in a different domain than the one
# held by the specified DC, so let's try again without a specific DC.
$proxyObject = [ADSI]("LDAP://<GUID=" + $guidString + ">")
}
if ($proxyObject.Path -ne $null)
{
# PR_PF_PROXY_REQUIRED is false or not set, but we have a directory object.
# This means we need to mail-enable the folder. Ideally it would link up to
# the existing directory object, but often, that doesn't seem to happen, and
# we get a duplicate. So, what we're going to do here is delete the existing
# directory object, mail-enable the folder, and then set the proxy addresses
# from the old directory object onto the new directory object.
# First, check if it's already mail-enabled. The input file could be out of
# sync with the actual properties.
$folder = Get-PublicFolder $folderPath -Server $ExchangeServer
if ($folder -ne $null)
{
if ($folder.MailEnabled)
{
writelog ("Skipping folder because it is already mail-enabled: " + $folderPath)
continue
}
}
else
{
writelog ("Skipping folder because it was not found: " + $folderPath)
continue
}
# If we got to this point, we found the PublicFolder object and it is not
# already mail-enabled.
writelog ("Found problem folder: " + $folderPath)
# Export the directory object before we delete it, just in case
$fileName = $ExportPath + "\" + $guidString + ".ldif"
$ldifoutput = ldifde -d $proxyObject.Properties.distinguishedName -f ($fileName)
writelog (" " + $ldifoutput)
writelog (" Exported directory object to file: " + $fileName)
# Save any explicit permissions
$explicitPerms = Get-MailPublicFolder $proxyObject.Properties.distinguishedName[0] | Get-ADPermission | `
WHERE { $_.IsInherited -eq $false -and (!($_.User.ToString().StartsWith("NT AUTHORITY"))) }
# Save group memberships
# We need to do this from a GC to make sure we get them all
$memberOf = ([ADSI]("GC://" + $proxyObject.Properties.distinguishedName[0])).Properties.memberOf
# Delete the current directory object
# For some reason Parent comes back as a string in Powershell, so
# we have to go bind to the parent.
$parent = [ADSI]($proxyObject.Parent.Replace("LDAP://", ("LDAP://" + $DC + "/")))
if ($parent.Path -eq $null)
{
$parent = [ADSI]($proxyObject.Parent)
}
if ($parent.Path -eq $null)
{
$proxyObject.Parent
writelog ("Skipping folder because bind to parent container failed: " + $folderPath)
continue
}
$parent.Children.Remove($proxyObject)
writelog (" Deleted old directory object.")
# Mail-enable the folder
Enable-MailPublicFolder $folderPath -Server $ExchangeServer
writelog (" Mail-enabled the folder.")
# Disable the email address policy and set the addresses.
# Because we just deleted the directory object a few seconds ago, it's
# possible that that change has not replicated everywhere yet. If the
# Exchange server still sees the object, setting the email addresses will
# fail. The purpose of the following loop is to retry until it succeeds,
# pausing in between. If this is constantly failing on the first try, it
# may be helpful to increase the initial pause.
$initialSleep = 30 # This is the initial pause. Increase it if needed.
writelog (" Sleeping for " + $initialSleep.ToString() + " seconds.")
Start-Sleep $initialSleep
# Filter out any addresses that aren't SMTP, and put the smtp addresses
# into a single comma-separated string.
$proxyAddressArray = $proxyAddresses.Split(" ")
$proxyAddresses = ""
foreach ($proxy in $proxyAddressArray)
{
if ($proxy.StartsWith("smtp:"))
{
if ($proxyAddresses.Length -gt 0)
{
$proxyAddresses += ","
}
$proxyAddresses += $proxy.Substring(5)
}
elseif ($proxy.StartsWith("SMTP:"))
{
if ($proxyAddresses.Length -gt 0)
{
$proxyAddresses = $proxy.Substring(5) + "," + $proxyAddresses
}
else
{
$proxyAddresses = $proxy.Substring(5)
}
}
}
$proxyAddresses = $proxyAddresses.Split(",")
$retryCount = 0
$maxRetry = 3 # The maximum number of times we'll retry
$succeeded = $false
while (!($succeeded))
{
writelog (" Setting proxy addresses...")
# Retrieve the new proxy object
$newMailPublicFolder = Get-MailPublicFolder $folderPath -Server $ExchangeServer
# Now set the properties
$Error.Clear()
Set-MailPublicFolder $newMailPublicFolder.Identity -EmailAddressPolicyEnabled $false -EmailAddresses $proxyAddresses `
-HiddenFromAddressListsEnabled $hideFromAddressLists -Server $ExchangeServer
if ($Error[0] -eq $null)
{
$succeeded = $true
}
else
{
writelog (" Error encountered in Set-MailPublicFolder: " + $Error[0].ToString())
if ($retryCount -lt $maxRetry)
{
$retryCount++
writelog (" Pausing before retry. This will be retry number " `
+ $retryCount.ToString() + ". Max retry attempts is " + $maxRetry.ToString() + ".")
Start-Sleep 60 # This is how long we'll pause before trying again
}
else
{
writelog (" Max retries reached. You must manually set the properties.")
writelog (" See the error log for more details.")
writeerror ("Failed to set proxyAddresses on folder.`r`nFolder: " + $folderPath + `
"`r`nProxy Addresses:`r`n" + $proxyAddresses + `
"`r`nGroup membership:`r`n" + $memberOf + `
"`r`nExplicit Permissions:`r`n" + ($explicitPerms | Select-Object User,AccessRights | out-string) + "`r`n")
break
}
}
}
if ($succeeded -and $explicitPerms -ne $null)
{
$succeeded = $true
writelog (" Setting explicit permissions on new directory object...")
$newMailPublicFolder = Get-MailPublicFolder $folderPath -Server $ExchangeServer
foreach ($permission in $explicitPerms)
{
$Error.Clear()
$temp = Add-ADPermission $newMailPublicFolder.Identity -User $permission.User -AccessRights $permission.AccessRights
if ($Error[0] -ne $null)
{
$succeeded = $false
writelog (" Error setting explicit permissions. You must manually set the permissions:")
writelog ($explicitPerms)
writeerror ("Failed to set explicit permissions on folder.`r`nFolder: " + $folderPath + `
"`r`nExplicit Permissions:`r`n" + ($explicitPerms | Select-Object User,AccessRights | out-string) + "`r`n")
break
}
}
}
if ($succeeded -and $memberOf -ne $null)
{
writelog (" Setting group memberships...")
$newMailPublicFolder = Get-MailPublicFolder $folderPath -Server $ExchangeServer
$proxy = [ADSI]("LDAP://<GUID=" + $newMailPublicFolder.Guid + ">")
$proxyDn = $proxy.Properties.distinguishedName[0]
$succeeded = $true
foreach ($group in $memberOf)
{
$Error.Clear()
$groupObject = [ADSI]("LDAP://" + $group)
$temp = $groupObject.Properties.member.Add($proxyDn)
$groupObject.CommitChanges()
if ($Error[0] -ne $null)
{
writelog (" Error setting group memberships. You must add the folder to these groups:")
writelog ($memberOf)
writeerror ("Failed to set group memberships on folder.`r`nFolder: " + $folderPath + `
"`r`nGroup memberships:`r`n" + $memberOf + "`r`n")
$succeeded = $false
break
}
}
}
writelog (" Set the properties on the new directory object.")
writelog (" Done with this folder.")
}
else
{
# This means the input file said this was a bad folder, but when we tried
# to bind to the objectGUID from PR_PF_PROXY, we failed. Either the file
# is out of sync with the folder settings, or something else went wrong.
# Do we want to generate any output here?
writelog ("Skipping folder because the objectGUID was not found: " + $folderPath)
}
}
else
{
# If we got here, it means that according to the input file, the folder is
# not in a state where it has a directory object but is not mail-enabled.
# Nothing we need to do in that case. The folder is good.
}
}
$reader.Close()
writelog "Done!"
if (!($isTranscribing))
{
Stop-Transcript
}
|
PowerShellCorpus/GithubGist/rshk_a1fcde3b5c77bff3756b_raw_49540c8c06a0487675ea7e49b558cb006c01df73_create-vm.ps1
|
rshk_a1fcde3b5c77bff3756b_raw_49540c8c06a0487675ea7e49b558cb006c01df73_create-vm.ps1
|
# ------------------------------------------------------------
# Create Hyper-V virtual machine via PowerShell
# ------------------------------------------------------------
# Variables
$VM_NAME = "PS_TEST_VM"
$VM_MAC = "00:15:5d:11:22:01"
$VM_RAM = 256GB
$VM_CPUS = 16
$VM_DEST_PATH = "C:\ClusterStorage\Volume1\tests"
$VM_VLAN = 82
$VM_HOST = "HYPERV_NODE_25"
$NETWORK_SWITCH = "DefaultNetwork"
$ROOT_VHD_TPL = "C:\ClusterStorage\Volume1\tests\Template.vhdx"
$VM_ROOT_VHD = "${VM_DEST_PATH}/${VM_NAME}.vhdx"
$VM_DATA_VHD = "${VM_DEST_PATH}/${VM_NAME}-data.vhdx"
$VM_DATA_VHD_SIZE = 80GB
$VM_CLUSTER = "HV_CLUSTER_05"
# Create destination folder for VMs
MD $VM_DEST_PATH -ErrorAction SilentlyContinue
# Create Virtual Machine
# ------------------------------------------------------------
echo "Creating VM: $VM_NAME on ${VM_HOST}"
$VM = New-VM -Name $VM_NAME -Path $VM_DEST_PATH -MemoryStartupBytes $VM_RAM -ComputerName $VM_HOST
#echo " VM Id: $( $VM.Id )"
#echo " VM Name: $( $VM.Name )"
#echo " Host: $( $VM.ComputerName )"
# Create & attach VHDs
# ------------------------------------------------------------
# Note: it is impossible to boot from SCSI controllers
echo "Getting first SCSI controller"
echo "Copying Root VHD to $VM_ROOT_VHD"
Convert-VHD -Path $ROOT_VHD_TPL -DestinationPath $VM_ROOT_VHD
Add-VMHardDiskDrive -VM $VM -ControllerType IDE -ControllerNumber 0 -ControllerLocation 0 -Path $VM_ROOT_VHD
echo "Creating new Data disk $VM_DATA_VHD_SIZE in $VM_DATA_VHD"
New-VHD -Path $VM_DATA_VHD -SizeBytes $VM_DATA_VHD_SIZE -Dynamic
Add-VMHardDiskDrive -VM $VM -ControllerType IDE -ControllerNumber 0 -ControllerLocation 1 -Path $VM_DATA_VHD
# Set CPU / memory
# ------------------------------------------------------------
echo "Setting CPU / Memory configuration"
Set-VMProcessor -VM $VM -Count $VM_CPUS
Set-VMMemory -VM $VM -DynamicMemoryEnabled $True -MaximumBytes 512GB -MinimumBytes 16GB -StartupBytes $VM_RAM
# Configure NIC
# ------------------------------------------------------------
echo "Configuring NIC (mac address: ${VM_MAC}, switch: ${NETWORK_SWITCH})"
Remove-VMNetworkAdapter -VM $VM
Add-VMNetworkAdapter -VM $VM -Name PublicNIC -StaticMacAddress $VM_MAC -SwitchName $NETWORK_SWITCH
$ADAPTER = Get-VMNetworkAdapter -VM $VM
Set-VMNetworkAdapterVlan -VMNetworkAdapter $ADAPTER -Access -VlanId $VM_VLAN
# Connect-VMNetworkAdapter -VMNetworkAdapter $ADAPTER -SwitchName $NETWORK_SWITCH
# Add VM to cluster
# ------------------------------------------------------------
echo "Adding VM to cluster"
Add-ClusterVirtualMachineRole -VMName $VM_NAME -Cluster $VM_CLUSTER
# Start VM
# ------------------------------------------------------------
#Start-VM $VM_NAME
|
PowerShellCorpus/GithubGist/dfch_3a6d9fb037896c0c2c41_raw_7fd9f8371359a058598279d526c093ec97b21a4d_ExternalWFStubs-Part2.ps1
|
dfch_3a6d9fb037896c0c2c41_raw_7fd9f8371359a058598279d526c093ec97b21a4d_ExternalWFStubs-Part2.ps1
|
# http://d-fens.ch/2013/12/05/vcac-dynamically-execute-scripts-in-externalwfstubs-workflows-with-powershell/
# Machine is the currently processed virtual machine
# Path is a default path where the scripts are located
# ScriptName is the name of the PowerShell script passed from the custom properties
# htScriptParam is a hastable containing parameter name and raw expression
$ScriptName = Join-Path -Path $Path -ChildPath $ScriptName;
if( !(Test-Path -Path $ScriptName) ) {
Write-Error ("ScriptName '{0}' does not exist." -f $ScriptName);
return $null;
} # if
$Cmd = Get-Command $ScriptName;
$ScriptParams = '';
foreach($k in $htScriptParam.Keys) {
if(!$Cmd.Parameters.ContainsKey($k)) {
Write-Error ("'{0}' does not contain specified parameter '{1}'. Skipping ..." -f
$ScriptName, $k);
continue;
} # if
$ScriptParam = $htScriptParam.$k;
$ScriptParam = $ScriptParam.Replace('#Machine', '$Machine');
if($ScriptParam -match "#Properties\.'([^\']+)'") {
$p = $Machine.VirtualMachineProperties |? PropertyName -eq $Matches[1];
if(!$p) {
Write-Error ("Resolving '{0}' with ScriptParam '{1}' [{2}] FAILED." -f
$ScriptName, $k, $ScriptParam);
continue;
} # if
$ScriptParam = $p.PropertyValue;
} # if
if($ScriptParam.StartsWith('$')) {
Write-Debug ("ScriptParam in Invoke-Expression: '{0}'." -f $ScriptParam)
$ScriptParam = Invoke-Expression -Command $ScriptParam;
} # if
$ScriptParams = "{0} -{1} '{2}'" -f $ScriptParams, $k, $ScriptParam;
} # foreach
$ScriptCommandline = "{0}{1}" -f $ScriptName, $ScriptParams;
PS > $ScriptCommandline;
C:\data\scripts\Set-VcacVirtualMachineName.ps1 -Name 'myNewVMName' -Fqdn 'example.com'
|
PowerShellCorpus/GithubGist/mbrownnycnyc_6877244fdfc095625549_raw_11eb4ca858250cb0ddf86b2c8b269af478b3896c_make-achart.ps1
|
mbrownnycnyc_6877244fdfc095625549_raw_11eb4ca858250cb0ddf86b2c8b269af478b3896c_make-achart.ps1
|
Import-Module .\charting.psm1 -Force
# Create simple dataset
$simpleDataset = @{
"Microsoft" = 800
"Apple" = 250
"Google" = 400
"RIM" = 0
}
# Create chart and show it
New-Chart -Dataset $simpleDataset | Show-Chart
# Create ordered hashmap
$osloTemperature = [ordered]@{}
# Request weather data for Oslo, and put into dataset
[xml]$weather = (Invoke-WebRequest -Uri http://www.yr.no/place/Norway/Oslo/Oslo/Oslo/varsel.xml).Content
$weather.weatherdata.forecast.tabular.time | foreach {
$osloTemperature[$_.from] = $_.temperature.value
}
# Create chart, add dataset and show
New-Chart -Title "Temperature in Oslo" -XInterval 4 -YInterval 2 -Width 1200 |
Add-ChartDataset -Dataset $osloTemperature -DatasetName "Temperature" -SeriesChartType Spline -OutVariable tempChart |
Show-Chart
# Save the chart as a PNG to the desktop
$tempChart.SaveImage($Env:USERPROFILE + "\Desktop\Chart.png", "PNG")
|
PowerShellCorpus/GithubGist/callemall_6123574_raw_ba3e772f12fed49821eaefd93224f119115e39fc_PowerShell%20-%20CheckAccount.ps1
|
callemall_6123574_raw_ba3e772f12fed49821eaefd93224f119115e39fc_PowerShell%20-%20CheckAccount.ps1
|
# ======================================================
# Programming Example on how to check account balance
# ======================================================
function CheckAccount
(
[String] $username,
[String] $pin
)
{
$URL = "http://staging-api.call-em-all.com/webservices/ceaapi_v2.asmx"
$Action = "http://call-em-all.com/CheckAccount"
[XML] $SOAPRequest = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<CheckAccount xmlns="http://call-em-all.com/">
<myRequest>
<username>' + $username +'</username>
<pin>' + $pin + '</pin>
</myRequest>
</CheckAccount>
</soap:Body>
</soap:Envelope>'
write-host "Sending SOAP Request To Server: $URL"
write-host "SOAP Request : " + $SOAPRequest
$soapWebRequest = [System.Net.WebRequest]::Create($URL)
$soapWebRequest.Headers.Add("SOAPAction", $Action)
$soapWebRequest.ContentType = "text/xml;charset=`"utf-8`""
$soapWebRequest.Accept = "text/xml"
$soapWebRequest.Method = "POST"
write-host "Initiating Send."
$requestStream = $soapWebRequest.GetRequestStream()
$SOAPRequest.Save($requestStream)
$requestStream.Close()
write-host "Send Complete, Waiting For Response."
$resp = $soapWebRequest.GetResponse()
$responseStream = $resp.GetResponseStream()
$soapReader = [System.IO.StreamReader]($responseStream)
$ReturnXml = [Xml] $soapReader.ReadToEnd()
$responseStream.Close()
write-host "============================================"
write-host "errorCode " $ReturnXml.Envelope.Body.CheckAccountResponse.CheckAccountResult.errorCode
write-host "errorMessage " $ReturnXml.Envelope.Body.CheckAccountResponse.CheckAccountResult.errorMessage
write-host "Call Balance " $ReturnXml.Envelope.Body.CheckAccountResponse.CheckAccountResult.CallBalance
write-host "CallerID " $ReturnXml.Envelope.Body.CheckAccountResponse.CheckAccountResult.CallerID
write-host "============================================"
return [xml] $ReturnXml
}
|
PowerShellCorpus/GithubGist/ctrlbold_04f743910541591443d4_raw_a3a44eb900cec369221c0e0459da136cb263482d_sp_help_revlogin2.ps1
|
ctrlbold_04f743910541591443d4_raw_a3a44eb900cec369221c0e0459da136cb263482d_sp_help_revlogin2.ps1
|
$source = "sqlserver"
$destination = "sqlcluster"
$smo = [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
$smoext = [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMOExtended")
$sourceserver = New-Object Microsoft.SqlServer.Management.Smo.Server $source
$destserver = New-Object Microsoft.SqlServer.Management.Smo.Server $destination
foreach ($sourcelogin in $sourceserver.logins) {
$destserver.refresh()
$destserver.logins.refresh()
$username = $sourcelogin.name
if ($destserver.logins[$username] -eq $null -and $sourcelogin.IsSystemObject -ne $true) {
$destlogin = New-Object Microsoft.SqlServer.Management.Smo.Login($destserver, $username)
$destlogin.set_Sid($sourcelogin.get_Sid())
if ($sourcelogin.PasswordPolicyEnforced) { $destlogin.PasswordPolicyEnforced = $true }
if ($sourcelogin.PasswordExpirationEnabled) { $destlogin.PasswordExpirationEnabled = $true }
$defaultdb = $sourcelogin.DefaultDatabase
if ($destserver.databases[$defaultdb] -eq $null) { $defaultdb = "master" }
$destlogin.DefaultDatabase = $defaultdb
if ($sourcelogin.LoginType -eq "SqlLogin") {
$sql = "SELECT CAST(CONVERT(varchar(256), CAST(LOGINPROPERTY(name,'PasswordHash')
AS varbinary (256)), 1) AS nvarchar(max)) as hashedpass FROM sys.server_principals
WHERE principal_id = $($sourcelogin.id)"
$destlogin.LoginType = "SqlLogin"
$hashedpass = ($sourceserver.databases['master'].ExecuteWithResults($sql)).Tables.hashedpass
$destlogin.Create($hashedpass, [Microsoft.SqlServer.Management.Smo.LoginCreateOptions]::IsHashed)
}
elseif ($sourcelogin.LoginType -eq "WindowsUser") {
$destlogin.LoginType = "WindowsUser"
$destlogin.Create()
}
else { Write-Warning "$($sourcelogin.LoginType) logins not supported. $($sourcelogin.name) skipped."; continue}
$destlogin.refresh()
if ($sourcelogin.DenyWindowsLogin) { $destlogin.DenyWindowsLogin = $true }
if ($sourcelogin.IsDisabled) { $destlogin.Disable() }
$destlogin.alter()
# Server Roles: sysadmin, bulkadmin, etc
foreach ($role in $sourceserver.roles) {
if ($role.EnumMemberNames() -contains $sourcelogin.name) {
if ($destserver.roles[$role.name] -ne $null) { $destlogin.AddToRole($role.name)}}
}
# Securables: Connect SQL, View any database, Administer Bulk Operations, etc.
$perms = $sourceserver.EnumServerPermissions($username)
foreach ($perm in $perms) {
$permstate = $perm.permissionstate
if ($permstate -eq "GrantWithGrant") { $grantwithgrant = $true; $permstate = "grant" } else { $grantwithgrant = $false }
$permset = New-Object Microsoft.SqlServer.Management.Smo.ServerPermissionSet($perm.permissiontype)
$destserver.$permstate($permset,$username,$grantwithgrant)
}
# Credential mapping
$logincredentials = $sourceserver.credentials | Where-Object {$_.Identity -eq $sourcelogin.name}
foreach ($credential in $logincredentials) {
if ($destserver.Credentials[$credential.name] -eq $null) {
$newcred = New-Object Microsoft.SqlServer.Management.Smo.Credential($destserver, $credential.name)
$newcred.identity = $sourcelogin.name
$newcred.Create()
} else {
$destlogin.AddCredential($credential.name)
}
}
# Database mappings are unnecessary because they're handled by the db migration.
}
}
|
PowerShellCorpus/GithubGist/cornfred_8966124_raw_43a8c40413c95891918f0082cfd45d07019609af_cryptoLocker.ps1
|
cornfred_8966124_raw_43a8c40413c95891918f0082cfd45d07019609af_cryptoLocker.ps1
|
# Credit due to www.reddit.com/user/Zendainc
#
# What this does:
# Finds out if CryptoLocker has infected pc's on the network by looking for a registery in the HKEY_USER hive. Maybe able to use for terminal servers too.
# If you find it:
# Go to the machine and extract the registry [HKEY_CURRENT_USER\Software\CryptoLocker\Files]. This gives you a list of files that have been encrypted.
# Use combo fix to clean it
# Recover files that have been affected from backups.
#
# How to use this script:
# Create a file called C:\listofcomputers.txt with a list of pc names
# You need to be an administrator on the pc's
# Remote Registry service needs to be running on the PC
#
# Output:
# Computer name, Status
# Status Values
# Null - Machine is not available
# True - Machine has the register entry we are looking for
# False - Changes are we are safe.
#
#
# Tested on:
# Windows 7
#
# To Clean up an Exported list of Computers
# Find: (^.+?)\s.*$
# Replace With: \1
#
# This will keep all characters until the first white space
$Type = [Microsoft.Win32.RegistryHive]::Users
$ComputerNames = Get-content C:\listofcomputers.txt
foreach($ComputerName in $ComputerNames)
{
$Status = $null #if machine is not available
if(Test-Connection $ComputerName -Quiet)
{
$Status = $false
$SubKeyNames = $null
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Type, $ComputerName)
$subKeys = $regKey.GetSubKeyNames()
$subKeys | %{
$key = "$_\software"
Try
{
$regSubKey = $regKey.OpenSubKey($key)
$SubKeyNames = $regSubKey.GetSubKeyNames()
if($SubKeyNames -match "CryptoLocker")
{
$Status = $true
}
}
Catch{}
}
}
$log = New-Object PSObject -Property @{
ComputerName = $ComputerName
if($Status == )
Status = $Status
}
$log
}
|
PowerShellCorpus/GithubGist/dfch_d598378f8a162a9bdf5b_raw_7628c70bd519cf607dd8097ce2f803d140b2b1c2_SignalrClient.ps1
|
dfch_d598378f8a162a9bdf5b_raw_7628c70bd519cf607dd8097ce2f803d140b2b1c2_SignalrClient.ps1
|
$eventName = "receiveMessage";
Add-Type -Path ".\SignalRClient.dll"
$s = New-Object SignalRClient.Connection("http://localhost/", "commandhub");
$s.Start($eventName);
while($true) {
$s.TryDequeue($eventName)
Start-Sleep -seconds 1
}
# string TryDequeue(string eventName)
# string Dequeue(string eventName)
# string Dequeue(string eventName, int dwMillisecondsTotalWaitTime)
# string Dequeue(string eventName, int dwMillisecondsTotalWaitTime, int dwMilliSecondsWaitIntervall)
# System.Collections.Generic.List[string] DequeueAll(string eventName)
|
PowerShellCorpus/GithubGist/mitchelldavis_464878813f87e7f1caab_raw_4c021e0833d3fb727838970fe27c591e3fc3cc86_Base64Conversions.ps1
|
mitchelldavis_464878813f87e7f1caab_raw_4c021e0833d3fb727838970fe27c591e3fc3cc86_Base64Conversions.ps1
|
function Convert-ToBase64
{
param( [Parameter(Mandatory=$true)][String]$target )
$b = [System.Text.Encoding]::UTF8.GetBytes($target)
[System.Convert]::ToBase64String($b)
}
function Convert-FromBase64
{
param( [Parameter(Mandatory=$true)][String]$target )
$b = [System.Convert]::FromBase64String($target)
[System.Text.Encoding]::UTF8.GetString($b)
}
|
PowerShellCorpus/GithubGist/kurukurupapa_7297327_raw_c6d8e0603f5536844bbc6b1ee0d18ac4f09d272a_OdbcCommand003.ps1
|
kurukurupapa_7297327_raw_c6d8e0603f5536844bbc6b1ee0d18ac4f09d272a_OdbcCommand003.ps1
|
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$WarningPreference = "Continue"
$VerbosePreference = "Continue"
$DebugPreference = "Continue"
# ライブラリ読み込み
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Data")
######################################################################
### 関数定義
######################################################################
# Updateの件数を取得するテスト
function U-Test-UpdateCount() {
# コマンド実行(UPDATE)
$odbcCmd.CommandText = "UPDATE TEST SET NAME='りんご類' WHERE name like 'りんご%'"
$count = $odbcCmd.ExecuteNonQuery()
Write-Debug "Update文の更新件数:$count"
}
# Deleteの件数を取得するテスト
function U-Test-DeleteCount() {
# コマンド実行(DELETE)
$odbcCmd.CommandText = "DELETE TEST WHERE name like 'りんご%'"
$count = $odbcCmd.ExecuteNonQuery()
Write-Debug "Delete文の削除件数:$count"
}
######################################################################
### 処理実行
######################################################################
# DB接続
$connectionString = "DSN=H2TestDsn;uid=sa;pwd=sa;"
$odbcCon = New-Object System.Data.Odbc.OdbcConnection($connectionString)
$odbcCon.Open()
# コマンドオブジェクト作成
$odbcCmd = New-Object System.Data.Odbc.OdbcCommand
$odbcCmd.Connection = $odbcCon
# コマンド実行(テーブル作成)
$odbcCmd.CommandText = "CREATE TABLE TEST (ID INT PRIMARY KEY, NAME VARCHAR(255))"
$odbcCmd.ExecuteNonQuery() | Out-Null
# コマンド実行(INSERT)
$odbcCmd.CommandText = "INSERT INTO TEST (ID, NAME) VALUES (100, 'りんご')"
$odbcCmd.ExecuteNonQuery() | Out-Null
$odbcCmd.CommandText = "INSERT INTO TEST (ID, NAME) VALUES (101, 'りんご2')"
$odbcCmd.ExecuteNonQuery() | Out-Null
$odbcCmd.CommandText = "INSERT INTO TEST (ID, NAME) VALUES (102, 'りんご3')"
$odbcCmd.ExecuteNonQuery() | Out-Null
# テスト
U-Test-UpdateCount
U-Test-DeleteCount
# コマンド実行(SELECT)
$odbcCmd.CommandText = "SELECT * FROM TEST ORDER BY ID"
$odbcReader = $odbcCmd.ExecuteReader()
while ($odbcReader.Read()) {
$odbcReader["ID"].ToString() + " " + $odbcReader["NAME"].ToString()
}
$odbcReader.Dispose()
# コマンド実行(テーブル削除)
$odbcCmd.CommandText = "DROP TABLE TEST"
$odbcCmd.ExecuteNonQuery() | Out-Null
# コマンドオブジェクト破棄
$odbcCmd.Dispose()
# DB切断
$odbcCon.Close()
$odbcCon.Dispose()
|
PowerShellCorpus/GithubGist/Kurt-P_6287165_raw_0cbaee627b9fa708ba2afd721b8143aeec81bae9_GropuAndSum.ps1
|
Kurt-P_6287165_raw_0cbaee627b9fa708ba2afd721b8143aeec81bae9_GropuAndSum.ps1
|
$gdata = $printsLogs | Group-Object -Property userId
$test = @()
$test += foreach($item in $gdata){
$item.Group | Select -Unique userId,
@{Name = 'PageTotal';Expression = {(($item.Group) | measure -Property pages -sum).Sum}}
}
|
PowerShellCorpus/GithubGist/rsalmond_10312091_raw_8e90491118820366eaa1be34e925c67346da4ec2_gistfile1.ps1
|
rsalmond_10312091_raw_8e90491118820366eaa1be34e925c67346da4ec2_gistfile1.ps1
|
function Test-Port{
<#
.SYNOPSIS
Tests port on computer.
.DESCRIPTION
Tests port on computer.
.PARAMETER computer
Name of server to test the port connection on.
.PARAMETER port
Port to test
.PARAMETER tcp
Use tcp port
.PARAMETER udp
Use udp port
.PARAMETER UDPTimeOut
Sets a timeout for UDP port query. (In milliseconds, Default is 1000)
.PARAMETER TCPTimeOut
Sets a timeout for TCP port query. (In milliseconds, Default is 1000)
.NOTES
Name: Test-Port.ps1
Author: Boe Prox
DateCreated: 18Aug2010
List of Ports: http://www.iana.org/assignments/port-numbers
To Do:
Add capability to run background jobs for each host to shorten the time to scan.
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Test-Port -computer 'server' -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
'server' | Test-Port -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
Test-Port -computer @("server1","server2") -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
Test-Port -comp dc1 -port 17 -udp -UDPtimeout 10000
Server : dc1
Port : 17
TypePort : UDP
Open : True
Notes : "My spelling is Wobbly. It's good spelling but it Wobbles, and the letters
get in the wrong places." A. A. Milne (1882-1958)
Description
-----------
Queries port 17 (qotd) on the UDP port and returns whether port is open or not
.EXAMPLE
@("server1","server2") | Test-Port -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
(Get-Content hosts.txt) | Test-Port -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port @(1..59)
Checks a range of ports from 1-59 on all servers in the hosts.txt file
#>
[cmdletbinding(
DefaultParameterSetName = '',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[array]$computer,
[Parameter(
Position = 1,
Mandatory = $True,
ParameterSetName = '')]
[array]$port,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$TCPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$UDPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$TCP,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$UDP
)
Begin {
If (!$tcp -AND !$udp) {$tcp = $True}
#Typically you never do this, but in this case I felt it was for the benefit of the function
#as any errors will be noted in the output of the report
$ErrorActionPreference = "SilentlyContinue"
$report = @()
}
Process {
ForEach ($c in $computer) {
ForEach ($p in $port) {
If ($tcp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$tcpobject = new-Object system.Net.Sockets.TcpClient
#Connect to remote machine's port
$connect = $tcpobject.BeginConnect($c,$p,$null,$null)
#Configure a timeout before quitting
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
#If timeout
If(!$wait) {
#Close connection
$tcpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
} Else {
$error.Clear()
$tcpobject.EndConnect($connect) | out-Null
#If error
If($error[0]){
#Begin making error more readable in report
[string]$string = ($error[0].exception).message
$message = (($string.split(":")[1]).replace('"',"")).TrimStart()
$failed = $true
}
#Close connection
$tcpobject.Close()
#If unable to query port to due failure
If($failed){
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "$message"
} Else{
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "True"
$temp.Notes = ""
}
}
#Reset failed value
$failed = $Null
#Merge temp array with report
$report += $temp
}
If ($udp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$udpobject = new-Object system.Net.Sockets.Udpclient
#Set a timeout on receiving message
$udpobject.client.ReceiveTimeout = $UDPTimeout
#Connect to remote machine's port
Write-Verbose "Making UDP connection to remote server"
$udpobject.Connect("$c",$p)
#Sends a message to the host to which you have connected.
Write-Verbose "Sending message to remote host"
$a = new-object system.text.asciiencoding
$byte = $a.GetBytes("$(Get-Date)")
[void]$udpobject.Send($byte,$byte.length)
#IPEndPoint object will allow us to read datagrams sent from any source.
Write-Verbose "Creating remote endpoint"
$remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
Try {
#Blocks until a message returns on this socket from a remote host.
Write-Verbose "Waiting for message return"
$receivebytes = $udpobject.Receive([ref]$remoteendpoint)
[string]$returndata = $a.GetString($receivebytes)
If ($returndata) {
Write-Verbose "Connection Successful"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "True"
$temp.Notes = $returndata
$udpobject.close()
}
} Catch {
If ($Error[0].ToString() -match "\bRespond after a period of time\b") {
#Close connection
$udpobject.Close()
#Make sure that the host is online and not a false positive that it is open
If (Test-Connection -comp $c -count 1 -quiet) {
Write-Verbose "Connection Open"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "True"
$temp.Notes = ""
} Else {
<#
It is possible that the host is not online or that the host is online,
but ICMP is blocked by a firewall and this port is actually open.
#>
Write-Verbose "Host maybe unavailable"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Unable to verify if port is open or if host is unavailable."
}
} ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) {
#Close connection
$udpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
} Else {
$udpobject.close()
}
}
#Merge temp array with report
$report += $temp
}
}
}
}
End {
#Generate Report
$report
}
}
Test-Port -comp localhost -port 7831 -udp
Test-Port -comp localhost -port 7831 -tcp
Test-Port -comp collector.tracelytics.com -port 2222 -tcp
|
PowerShellCorpus/GithubGist/Tallmaris_10984688_raw_c624a0a82feb3bfb80098476367414707dcc4df1_Install-Puppet.ps1
|
Tallmaris_10984688_raw_c624a0a82feb3bfb80098476367414707dcc4df1_Install-Puppet.ps1
|
# Install Puppet
$MsiUrl = "https://downloads.puppetlabs.com/windows/puppet-3.5.1.msi"
$PuppetInstalled = $false
try {
$ErrorActionPreference = "Stop";
Get-Command puppet | Out-Null
$PuppetInstalled = $true
$PuppetVersion=&puppet "--version"
Write-Host "Puppet $PuppetVersion is installed. This process does not ensure the exact version or at least version specified, but only that puppet is installed. Exiting..."
Exit 0
} catch {
Write-Host "Puppet is not installed, continuing..."
}
if (!($PuppetInstalled)) {
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (! ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) {
Write-Host -ForegroundColor Red "You must run this script as an administrator."
Exit 1
}
# Install it - msiexec will download from the url
$install_args = @("/qn", "/norestart","/i", $MsiUrl)
Write-Host "Installing Puppet. Running msiexec.exe $install_args"
$process = Start-Process -FilePath msiexec.exe -ArgumentList $install_args -Wait -PassThru
if ($process.ExitCode -ne 0) {
Write-Host "Installer failed."
Exit 1
}
# Stop the service that it autostarts
Write-Host "Stopping Puppet service that is running by default..."
Start-Sleep -s 5
Stop-Service -Name puppet
Write-Host "Puppet successfully installed."
}
|
PowerShellCorpus/GithubGist/aplocher_31d9888a0cb6e634fafd_raw_d5b55e30920a1f018c23e228caffaee44ddb3df8_ClearVisualStudioExpHive.ps1
|
aplocher_31d9888a0cb6e634fafd_raw_d5b55e30920a1f018c23e228caffaee44ddb3df8_ClearVisualStudioExpHive.ps1
|
param (
[string]$fullName = "", # Example: "12.0Exp" is VS v12.0 (2013) hive name "Exp"
[switch]$listHives = $false,
[switch]$force = $false
)
$vsAppDataRoot = Join-Path $env:APPDATA "Microsoft\VisualStudio"
$vsRegKeyRoot = "hkcu:\Software\Microsoft\VisualStudio"
if (-not $fullName -and -not $listHives) {
Write-Warning 'Must provide a hive name with the -fullName switch. To get a list of hive names, run with -listHives switch.'
exit
}
if ($listHives) {
Join-Path $env:APPDATA "Microsoft\VisualStudio" | Get-ChildItem | Select-Object -Property `
@{ Name="Full Name"; Expression={$_.Name}},
@{ Name="VS Version"; Expression={
switch($_.Name | Select-String -pattern "^[0-9]+\.[0-9]" -AllMatches | %{$_.Matches[0].Value }) {
"14.0"{"VS 2015"}
"12.0"{"VS 2013"}
"11.0"{"VS 2012"}
"10.0"{"VS 2010"}
"9.0"{"VS 2008"}
"8.0"{"VS 2005"}
"7.1"{"VS 2003"}
"7.0"{"VS 2002 (.NET)"}
default {"(unknown)"}
}
}
},
@{ Name="Hive Name"; Expression={
$hiveName = $_.Name | Select-string -pattern "^[0-9]+\.[0-9]([A-Za-z0-9]+)$" -AllMatches | %{$_.Matches[0].Groups[1].Value }
if (-not $hiveName) {
"(default or unknown)"
} else {
$hiveName
}
}
}
} else {
if (-not $fullName) {
Write-Error "Invalid parameters"
exit
}
$regKey = Join-Path $vsRegKeyRoot $fullName
$regConfigKey = Join-Path $vsRegKeyRoot "$($fullName)_Config"
$folder = Join-Path $vsAppDataRoot $fullName
if (-not ($vsAppDataRoot | Get-ChildItem | Where name -eq $fullName)) {
Write-Warning "Folder doesn't seem to exist: $($folder)"
if (-not $force) {
Write-Warning "Use -force switch to attempt cleanup anyway"
exit
} else {
Write-Host
}
}
Write-Host "Removing registry key $($regKey)"
if (Test-Path $regKey) {
Remove-Item -path $regKey -Recurse -Force
Write-Host "Done"
} else {
Write-Warning "path not found"
}
Write-Host
Write-Host "Removing registry key $($regConfigKey)"
if (Test-Path $regConfigKey) {
Remove-Item -path $regConfigKey -Recurse -Force
Write-Host "Done"
} else {
Write-Warning "path not found"
}
Write-Host
Write-Host "Removing folder $($folder)"
if (Test-Path $folder) {
Remove-Item -path $folder -Recurse -Force
Write-Host "Done"
} else {
Write-Warning "path not found"
}
Write-Host
}
|
PowerShellCorpus/GithubGist/PaulDMurphy_b1efce81d31b70b135a1_raw_15fcbebb7536a4b7b46c4b5390c45c50da8e35ad_bootstrap.ps1
|
PaulDMurphy_b1efce81d31b70b135a1_raw_15fcbebb7536a4b7b46c4b5390c45c50da8e35ad_bootstrap.ps1
|
# Boxstarter options
$Boxstarter.RebootOk =$true # Allow reboots?
$Boxstarter.AutoLogin =$true # Save my password securely and auto-login after a reboot
$Boxstarter.NoPassword =$false # Is this a machine with no login password?
# Set the execution policy
Update-ExecutionPolicy Unrestricted
# Configure Windows
Set-CornerNavigationOptions -DisableUpperRightCornerShowCharms -DisableUpperLeftCornerSwitchApps -EnableUsePowerShellOnWinX
Set-ExplorerOptions -hideHiddenFilesFoldersDrives -showFileExtensions
Set-StartScreenOptions -EnableBootToDesktop -DisableDesktopBackgroundOnStart -DisableSearchEverywhereInAppsView
Set-TaskbarOptions -Dock Bottom -Size Small -Lock
Enable-RemoteDesktop
winrm qc -force
# Always check for patches
Install-WindowsUpdate -AcceptEula
if (Test-PendingReboot) { Invoke-Reboot }
# adjust windows
#choco windowsfeatures Dedupe-Core
#choco windowsfeatures WirelessNetworking
#choco windowsfeatures DesktopExperience
#choco windowsfeature File-Services-Search-Service
# General
choco install VLC
choco install 7Zip
choco install Firefox
choco install GoogleChrome
choco install AdobeReader
choco install uTorrent
choco install DotNet3.5
choco install WinDirStat
# Development
choco install tortoisegit
choco install tortoisehg
choco install tortoisesvn
choco install sourcetree
|
PowerShellCorpus/GithubGist/toddb_1138132_raw_29219b1f0ed5befb90134e3d724089b5983719f2_db-setup.psake.ps1
|
toddb_1138132_raw_29219b1f0ed5befb90134e3d724089b5983719f2_db-setup.psake.ps1
|
Task Db-Setup -Description "Adds the current user for access to SharePoint schemas - DEV only" {
$userToAdd = Read-Host -Prompt 'User to add to Farm Admin group <DOMAIN>\<USERNAME>'
$db_env = Read-Host -Prompt 'Environment suffix of the database to setup'
Write-Host "If this script has a problem then you don't have login access - please sort this out first"
Write-Host "see http://www.sharepointassist.com/2010/01/29/the-local-farm-is-not-accessible-cmdlets-with-featuredependencyid-are-not-registered/"
$whoami = [Environment]::UserName
Write-Host "Adding dev user to database: $whoami"
Write-Host "Enter the password for the user $site_owner"
exec { sqlcmd -i .\dev-powershell-access.sql -U $whoami -v user=$userToAdd -v db_env=$db_env }
}
<#
dev-powershell-access.sql
USE [SP_Admin_Content_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Admin_Content_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_Admin_Content_DB_$(db_env)]
GO
EXEC sp_addrolemember N'SharePoint_Shell_Access', N'$(user)'
GO
USE [SP_Config_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Config_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_Config_DB_$(db_env)]
GO
EXEC sp_addrolemember N'SharePoint_Shell_Access', N'$(user)'
GO
#>
<#
USE [master]
GO
CREATE LOGIN [$(user)] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO
USE [SP_Admin_Content_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Admin_Content_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_BCServiceDB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_BCServiceDB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_Config_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Config_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_Content_Portal_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Content_Portal_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_MetaDataService_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_MetaDataService_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_Search_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Search_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_Search_DB_$(db_env)_CrawlStore]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Search_DB_$(db_env)_CrawlStore]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_Search_DB_$(db_env)_PropertyStore]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_Search_DB_$(db_env)_PropertyStore]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_SecureStoreServiceApp_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_SecureStoreServiceApp_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_StateService_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_StateService_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_UPSProfile_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_UPSProfile_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_UPSSocial_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_UPSSocial_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_UPSSync_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_UPSSync_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_UsageService_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_UsageService_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_WebReporting_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_WebReporting_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_WebStage_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_WebStage_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_WordAutomation_DB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_WordAutomation_DB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
USE [SP_WSS_SearchDB_$(db_env)]
GO
CREATE USER [$(user)] FOR LOGIN [$(user)]
GO
USE [SP_WSS_SearchDB_$(db_env)]
GO
EXEC sp_addrolemember N'db_owner', N'$(user)'
GO
#>
|
PowerShellCorpus/GithubGist/gravejester_0ef473ded31e06fae9e2_raw_bf05f682d6148f3e1d38140c8f6afe23b271cb18_spotify.ps1
|
gravejester_0ef473ded31e06fae9e2_raw_bf05f682d6148f3e1d38140c8f6afe23b271cb18_spotify.ps1
|
function Search-Spotify {
<#
.SYNOPSIS
Search Spotify.
.DESCRIPTION
This function uses the public web API of Spotify to let you query their database for information about
artists, albums, tracks and popular playlists.
.EXAMPLE
Search-Spotify 'Madonna'
Will search for 'Madonna' among all artists in the Spotify database.
.EXAMPLE
Search-Spotify 'Tania*'
Uses wildcard to search for all artists that starts with 'Tania'.
.EXAMPLE
Search-Spotify 'album:arrival artist:abba' -Type 'Album'
Will search for album with name matching 'Arrival' and artist matching 'Abba'
.EXAMPLE
Search-Spotify 'Madonna' -Type 'Album','Artis'
Will return both album and tracks with 'Madonna' in their name.
.NOTES
Author: Øyvind Kallstad
Date: 27.11.2014
Version: 1.0
#>
[CmdletBinding()]
param (
# Search query. Supports wildcard (*, max 2 per query) and operators (NOT/OR, must be in uppercase).
# By default, results are returned when a match is found in any field of the target object type.
# Searches can be made more specific by specifying an album, artist or track field filter.
# Field names must be entered in lower-case.
[Parameter(Position = 0)]
[ValidateNotNullorEmpty()]
[string] $Query,
# Type of information to search for. Valid choices are 'Artist','Album','Playlist' or 'Track'
[Parameter()]
[ValidateSet('Album','Artist','PlayList','Track')]
[string[]] $Type = 'Artist',
# Filter the results to only show results available in the supplied market.
# Defaults to the current region of the machine you are running the command from.
[Parameter()]
[string] $Market = [System.Globalization.RegionInfo]::CurrentRegion.TwoLetterISORegionName,
# The maximum number of objects to return. Defaults to 20.
[Parameter()]
[int] $Limit = 20,
# The index of the first object to return. Defaults to 0.
[Parameter()]
[int] $Offset = 0
)
$endPoint = 'https://api.spotify.com/v1/search'
$queryString = "?q=$([uri]::EscapeUriString($Query))&type=$($Type -Join ',')"
[uri]$uri = $endPoint + $queryString
try {
$result = Invoke-RestMethod -Uri $uri
}
catch {
Write-Warning $_.Exception.Message
break
}
switch ($Type) {
'Artist' {
foreach ($artist in $result.artists.items) {
Write-Output (,([PSCustomObject] [Ordered] @{
Name = $artist.name
Popularity = $artist.popularity
Genres = $artist.genres
ID = $artist.id
Uri = $artist.uri
ExternalUrl = $artist.external_urls | Select-Object -ExpandProperty 'spotify'
}))
}
}
'Album' {
foreach ($album in $result.albums.items) {
Write-Output (,([PSCustomObject] [Ordered] @{
Name = $album.name
Type = $album.album_type
ID = $album.id
Uri = $album.uri
ExternalUrl = $album.external_urls | Select-Object -ExpandProperty 'spotify'
}))
}
}
'Track' {
foreach ($track in $result.tracks.items) {
Write-Output (,([PSCustomObject] [Ordered] @{
Name = $track.name
Album = $track.album | Select-Object -ExpandProperty 'Name'
Artists = ($track.artists | Select-Object -ExpandProperty 'Name')
DurationMS = $track.duration_ms
Explicit = $track.explicit
Popularity = $track.popularity
DiskNo = $track.disc_number
TrackNo = $track.track_number
ID = $track.id
Uri = "spotify:track:$($track.id)"
ExternalUrl = $track.external_urls | Select-Object -ExpandProperty 'spotify'
}))
}
}
'PlayList' {
foreach ($playlist in $result.playlists.items) {
Write-Output (,([PSCustomObject] [Ordered] @{
Name = $playlist.name
OwnerID = $playlist.owner | Select-Object -ExpandProperty 'id'
Collaborative = $playlist.collaborative
Tracks = $playlist.tracks.total
ID = $playlist.id
Uri = $playlist.uri
ExternalUrl = $playlist.external_urls | Select-Object -ExpandProperty 'spotify'
}))
}
}
}
}
function Out-Spotify {
<#
.SYNOPSIS
Open Spotify with the specified Uri.
.EXAMPLE
Search-Spotify 'Love' -Type 'Track' | Select -First 1 | Out-Spotify
.NOTES
Author: Øyvind Kallstad
Date: 27.11.2014
Version: 1.0
#>
[CmdletBinding()]
param (
# Spotify Uri
[Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName)]
[ValidateNotNullorEmpty()]
[string] $Uri
)
$spotifyPath = "$($env:APPDATA)\spotify\spotify.exe"
if (Test-Path $spotifyPath) {
if (Get-Process 'spotify' -ErrorAction SilentlyContinue) {
& $spotifyPath $Uri
}
else {
Write-Warning 'Spotify not running'
$userInput = Read-Host -Prompt 'Do you want to start Spotify? [y/n] '
if ($userInput.ToLower() -eq 'y') {
Start-Process $spotifyPath
Start-Sleep -Seconds 4
& $spotifyPath $Uri
}
}
}
else {
Write-Warning 'Invalid path to spotify!'
}
}
|
PowerShellCorpus/GithubGist/rhysparry_1678878_raw_285c8b4073bc1b53fcfbb8118185fac41c9b55f4_Get-TotalPrivateBytes.ps1
|
rhysparry_1678878_raw_285c8b4073bc1b53fcfbb8118185fac41c9b55f4_Get-TotalPrivateBytes.ps1
|
function Get-TotalPrivateBytes($Name)
{
Get-Process $Name | Measure-Object -Sum -Maximum -Minimum -Average PrivateMemorySize64
}
|
PowerShellCorpus/GithubGist/thorade_04a4eaa0a4047c523112_raw_61015ee5f7b55e9f7206f873fd50d3a98f21170c_TeX_cleanup.ps1
|
thorade_04a4eaa0a4047c523112_raw_61015ee5f7b55e9f7206f873fd50d3a98f21170c_TeX_cleanup.ps1
|
# This Windows PowerShell script
# recursively deletes LaTeX temporary files
# from all folder below itself
# get current directory
$curDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Host $curDir
# delete files
get-childitem $curDir -include *.aex, *.aux, *.auxlock, *.bcf, *.blg, *.dpth, *.ilg, *.lof, *.log, *.lol, *.lot, *.nlo, *.nls, *.out, *.pyg, *.run.xml, *.synctex.gz, *.toc, *.xdv -recurse | foreach ($_) {remove-item $_.fullname}
|
PowerShellCorpus/GithubGist/MyITGuy_9708116_raw_295d83eb1153fdb9dd670b489ad4343f7d9778e0_javacpl.ps1
|
MyITGuy_9708116_raw_295d83eb1153fdb9dd670b489ad4343f7d9778e0_javacpl.ps1
|
<#
.SYNOPSIS
Add and remove Java Control Panel applet entries in the Windows Control Panel.
.DESCRIPTION
The JavaCPL function collects control panel applet information from the registry. It uses this information to analyze currently visible entries and their status. Based on this information entries can be removed, added or modified.
.PARAMETER Add
Add available Java Control Panel applets to the Windows Control Panel. Existing Java Control Panel applets will not be affected.
.PARAMETER Remove
Remove Java Control Panel applets that are not installed from the Windows Control Panel. Available Java Control Panel applets will remain.
.PARAMETER All
Used with the Remove parameter; Remove all Java Control Panel applets, available and unavailable, from the Windows Control Panel.
.PARAMETER Reset
Remove all Java Control Panel applets from, then add all available Java Control Panel applets to, the Windows Control Panel.
.EXAMPLE
javacpl.ps1 -Verbose
View Java and Windows Control Panel information verbose logging.
.EXAMPLE
javacpl.ps1 -Remove -Verbose
Removes Java Control Panel applets from the Windows Control Panel that are not installed with verbose logging.
.EXAMPLE
javacpl.ps1 -Remove -All -Verbose
Removes all known Java Control Panel applets from the Windows Control Panel with verbose logging.
.EXAMPLE
javacpl.ps1 -Add -Verbose
Adds Java Control Panel applets to the Windows Control Panel that are installed, but not available, with verbose logging.
.EXAMPLE
javacpl.ps1 -Reset -Verbose
Performs a '-Remove -All' then a Java Control Panel applets from the Windows Control Panel with verbose logging.
.INPUTS
.OUTPUTS
.NOTES
The validation of Java Control Panel applets consists of 3 areas:
NotInstalled: The Java Control Panel exists in the registry, but not on the file system.
NotAvailable: The Java Control Panel exists in the registry and file system, but not in the Windows Control Panel.
Available : The Java Control Panel exists in the registry, file system and Windows Control Panel.
.LINK
#>
[CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName="None")]
param (
[Parameter(ParameterSetName="Add",Mandatory=$false)]
[switch]$Add,
[Parameter(ParameterSetName="Remove",Mandatory=$false)]
[switch]$Remove,
[Parameter(ParameterSetName="Remove",Mandatory=$false)]
[switch]$All,
[Parameter(ParameterSetName="Reset",Mandatory=$false)]
[switch]$Reset
)
# Validation of parameters
if (($All) -and !($Remove)) {
Write-Host "All parameter without Remove parameter prohibited." -ForegroundColor Yellow
return
}
# Add, Remove and Reset require Adminsitrator role
if (($Remove) -or ($Add) -or ($Reset)) {
$CurrentWindowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$CurrentWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($CurrentWindowsIdentity)
$IsAdministratorWindowsBuiltInRole = $CurrentWindowsPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
if ($IsAdministratorWindowsBuiltInRole -eq $false) {
Write-Host "Access is denied. The requested operation requires elevation." -ForegroundColor Red
exit 0x000002E4
}
}
$ParamSetName = $PsCmdLet.ParameterSetName
Write-Verbose "ParamSetName: $ParamSetName"
function Get-FileVersion {
param(
[string]$FilePath
)
$FilePath = $FilePath.Replace('"','')
if ((Test-Path -Path $FilePath -PathType Leaf) -eq $true) {
[System.Diagnostics.FileVersionInfo]::GetVersionInfo($FilePath).FileVersion
}
}
function Get-ProductVersion {
param(
[string]$FilePath
)
$FilePath = $FilePath.Replace('"','')
if ((Test-Path -Path $FilePath -PathType Leaf) -eq $true) {
[System.Diagnostics.FileVersionInfo]::GetVersionInfo($FilePath).ProductVersion
}
}
$OutputObjects = New-Object -TypeName PSObject
$OutputObjects = @()
function Add-OutputObject {
param (
[string]$ControlPanelName,
[string]$ControlPanelPath,
[string]$CLSIDPath,
[string]$CLSID,
[string]$CLSIDName,
[string]$InfoTip,
[string]$SystemControlPanelCategory,
[string]$DefaultIcon,
[string]$Command,
[string]$JavaVersion,
[string]$JavaVersionFriendlyName,
[string]$Status
)
$OutputObject = New-Object -TypeName PSObject -Property @{
ControlPanelName = $ControlPanelName
ControlPanelPath = $ControlPanelPath
CLSIDPath = $CLSIDPath
CLSID = $CLSID
CLSIDName = $CLSIDName
InfoTip = $InfoTip
SystemControlPanelCategory = $SystemControlPanelCategory
DefaultIcon = $DefaultIcon
Command = $Command
JavaVersion = $JavaVersion
JavaVersionFriendlyName = $JavaVersionFriendlyName
Status = $Status
};
$script:OutputObjects += $OutputObject
}
function Remove-Applet {
param (
$Applet,
$Verbose = $PSBoundParameters['Verbose']
)
try {
Remove-Item -Path "$($Applet.ControlPanelPath)" -Recurse -ErrorAction SilentlyContinue | Out-Null
Remove-Item -Path "$($Applet.CLSIDPath)" -Recurse -ErrorAction SilentlyContinue | Out-Null
} catch {}
if (((Test-Path -Path "$($Applet.ControlPanelPath)") -eq $false) -and ((Test-Path -Path "$($Applet.CLSIDPath)") -eq $false)) {
if ($Verbose) {Write-Host "VERBOSE: Removed $($Applet.ControlPanelName)" -ForegroundColor Green}
return $true
} else {
if ($Verbose) {Write-Host "VERBOSE: Could not remove: $($Applet.ControlPanelName)" -ForegroundColor Red}
return $false
}
}
function Add-Applet {
param (
$Applet,
$Verbose = $PSBoundParameters['Verbose']
)
try {
New-Item -Path "$($Applet.ControlPanelPath)" -Value "$($Applet.JavaVersionFriendlyName)" -ErrorAction SilentlyContinue | Out-Null
New-Item -Path "$($Applet.CLSIDPath)" -Value "$($Applet.JavaVersionFriendlyName)" -ErrorAction SilentlyContinue | Out-Null
Set-ItemProperty -Path "$($Applet.CLSIDPath)" -Name "InfoTip" -Value "$($Applet.InfoTip)" -ErrorAction SilentlyContinue | Out-Null
Set-ItemProperty -Path "$($Applet.CLSIDPath)" -Name "System.ControlPanel.Category" -Value "$($Applet.SystemControlPanelCategory)" -ErrorAction SilentlyContinue | Out-Null
New-Item -Path "$($Applet.CLSIDPath)\DefaultIcon" -Value "$($Applet.DefaultIcon)" -ErrorAction SilentlyContinue | Out-Null
New-Item -Path "$($Applet.CLSIDPath)\Shell\Open\Command" -Value "$($Applet.Command)" -Force -ErrorAction SilentlyContinue | Out-Null
} catch {}
if (((Test-Path -Path "$($Applet.ControlPanelPath)") -eq $true) -and ((Test-Path -Path "$($Applet.CLSIDPath)") -eq $true)) {
if ($Verbose) {Write-Host "VERBOSE: Added $($Applet.ControlPanelName)" -ForegroundColor Green}
return $true
} else {
if ($Verbose) {Write-Host "VERBOSE: Could not add: $($Applet.ControlPanelName)" -ForegroundColor Red}
return $false
}
}
# Create object for entries
$CLSIDs = @()
# Get 64-bit entries
$CLSIDs += (Get-ChildItem -Path "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace" -ErrorAction SilentlyContinue | ? {$_.PSChildName -match("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$")} | Select @{Name="CLSID";Expression={$_.PSChildName}},@{Name="ControlPanelPath";Expression={$_.PSPath}})
# Add 32-bit entries
$CLSIDs += (Get-ChildItem -Path "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace" -ErrorAction SilentlyContinue | ? {($_.PSChildName -match("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$") -eq $true) -and (($CLSIDs | Select CLSID) -notmatch $_.PSChildName)} | Select @{Name="CLSID";Expression={$_.PSChildName}},@{Name="ControlPanelPath";Expression={$_.PSPath}})
$CLSIDs += (Get-ChildItem -Path "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\ControlPanelWOW64\NameSpace" -ErrorAction SilentlyContinue | ? {($_.PSChildName -match("^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$") -eq $true) -and (($CLSIDs | Select CLSID) -notmatch $_.PSChildName)} | Select @{Name="CLSID";Expression={$_.PSChildName}},@{Name="ControlPanelPath";Expression={$_.PSPath}})
$CLSIDs = $CLSIDs | Sort-Object -Property CLSID -Unique
if ($PSBoundParameters['Verbose']) {Write-Verbose "Discoverd Control Panel Applets:`t`t`t`t`t`t`t$(($CLSIDs | Measure).Count)"}
foreach ($CLSID In $CLSIDs) {
$CLSIDPath = "Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CLSID\$($CLSID.CLSID)"
$Path = "$($CLSIDPath)\Shell\Open\Command"
$Status = "NotInstalled"
if ((Test-Path -Path $Path) -eq $false) {
$CLSIDPath = "Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\Wow6432Node\CLSID\$($CLSID.CLSID)"
$Path = "$($CLSIDPath)\Shell\Open\Command"
}
if ((Test-Path -Path $Path) -eq $true) {
$Command = (Get-ItemProperty -Path $Path -Name "" -ErrorAction SilentlyContinue | Where-Object {($_."(default)").Replace('"','').ToLower().EndsWith("javacpl.exe") -eq $true} | Select -ExpandProperty "(default)")
}
if ($Command) {
$JavaVersion = Get-ProductVersion -FilePath $Command
if ($JavaVersion) {
$JavaVersionFriendlyName = "Java $($JavaVersion.Split('.')[0]) Update $(($JavaVersion.Split('.')[2]).TrimEnd('0'))"
$Status = "NotAvailable"
}
$ControlPanelPath = $CLSID.ControlPanelPath
$ControlPanelName = (Get-ItemProperty -Path $ControlPanelPath -Name "" -ErrorAction SilentlyContinue | Select -ExpandProperty "(default)")
$CLSIDName = (Get-ItemProperty -Path $CLSIDPath -Name "" -ErrorAction SilentlyContinue | Select -ExpandProperty "(default)")
$InfoTip = (Get-ItemProperty -Path $CLSIDPath -Name "InfoTip" -ErrorAction SilentlyContinue | Select -ExpandProperty "InfoTip")
$SystemControlPanelCategory = (Get-ItemProperty -Path $CLSIDPath -Name "System.ControlPanel.Category" -ErrorAction SilentlyContinue | Select -ExpandProperty "System.ControlPanel.Category")
$Path = "$($CLSIDPath)\DefaultIcon"
if ((Test-Path -Path $Path) -eq $true) {
$DefaultIcon = (Get-ItemProperty -Path $Path -Name "" -ErrorAction SilentlyContinue | Select -ExpandProperty "(default)")
}
Add-OutputObject -ControlPanelName $ControlPanelName -ControlPanelPath $ControlPanelPath -CLSIDPath $CLSIDPath -CLSID "$($CLSID.CLSID)" -CLSIDName $CLSIDName -InfoTip $InfoTip -SystemControlPanelCategory $SystemControlPanelCategory -DefaultIcon $DefaultIcon -Command $Command -JavaVersion $JavaVersion -JavaVersionFriendlyName $JavaVersionFriendlyName -Status $Status
}
Clear-Variable CLSID -ErrorAction SilentlyContinue
Clear-Variable Path -ErrorAction SilentlyContinue
Clear-Variable ControlPanelPath -ErrorAction SilentlyContinue
Clear-Variable ControlPanelName -ErrorAction SilentlyContinue
Clear-Variable CLSIDPath -ErrorAction SilentlyContinue
Clear-Variable CLSIDName -ErrorAction SilentlyContinue
Clear-Variable InfoTip -ErrorAction SilentlyContinue
Clear-Variable SystemControlPanelCategory -ErrorAction SilentlyContinue
Clear-Variable DefaultIcon -ErrorAction SilentlyContinue
Clear-Variable Command -ErrorAction SilentlyContinue
}
# Java Control Panel applet locations from registry
$DiscoverdCPLs = @()
if ([IntPtr]::Size -eq 8) {
# 64-bit OS
$DiscoverdCPLs += (Get-ChildItem -Path "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment" -ErrorAction SilentlyContinue | % {Get-ItemProperty -Path $_.PSPath -Name JavaHome -ErrorAction SilentlyContinue} | Select @{Name="JavaCplFile";Expression={"$($_.JavaHome)\bin\javacpl.exe"}},@{Name="Version";Expression={$_.PSChildName}},@{Name="Architecture";Expression={[int]64}} | Sort JavaCplFile -Unique)
$DiscoverdCPLs += (Get-ChildItem -Path "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment" -ErrorAction SilentlyContinue | % {Get-ItemProperty -Path $_.PSPath -Name JavaHome -ErrorAction SilentlyContinue} | Select @{Name="JavaCplFile";Expression={"$($_.JavaHome)\bin\javacpl.exe"}},@{Name="Version";Expression={$_.PSChildName}},@{Name="Architecture";Expression={[int]32}} | Sort JavaCplFile -Unique)
} elseif ([IntPtr]::Size -eq 4) {
# 32-bit OS
$DiscoverdCPLs += (Get-ChildItem -Path "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment" -ErrorAction SilentlyContinue | % {Get-ItemProperty -Path $_.PSPath -Name JavaHome -ErrorAction SilentlyContinue} | Select @{Name="JavaCplFile";Expression={"$($_.JavaHome)\bin\javacpl.exe"}},@{Name="Version";Expression={$_.PSChildName}},@{Name="Architecture";Expression={[int]32}} | Sort JavaCplFile -Unique)
}
$DiscoverdCPLs = $DiscoverdCPLs | Sort-Object -Property JavaCplFile -Unique | ? {(Test-Path -Path "$($_.JavaCplFile)" -PathType Leaf) -eq $true}
foreach ($DiscoverdCPL In $DiscoverdCPLs) {
$Command = ($DiscoverdCPL.JavaCplFile)
$JavaVersion = Get-ProductVersion -FilePath $Command
$Status = "NotInstalled"
if ($JavaVersion) {
$MajorVersion = [int]$JavaVersion.Split('.')[0]
$UpdateVersion = [int]$DiscoverdCPL.Version.Split('_')[1]
if ($UpdateVersion -ne 0) {
$JavaVersionFriendlyName = "Java $($MajorVersion) Update $($UpdateVersion)"
} else {
$JavaVersionFriendlyName = "Java $($MajorVersion)"
}
$Status = "NotAvailable"
}
$CommandEscaped = [regex]::escape($Command)
$Commands = ($OutputObjects | Select Command)
if ($Commands -match $CommandEscaped) {
foreach ($OutputObject In $OutputObjects) {
if ($OutputObject.Command.Replace('"','') -eq $Command) {
$OutputObject.JavaVersionFriendlyName = $JavaVersionFriendlyName
$OutputObject.Status = "Available"
}
}
} else {
$CLSID = "{$([guid]::NewGuid().ToString().ToUpper())}"
if (([IntPtr]::Size -eq 8) -and ($DiscoverdCPL.Architecture -eq 64)) {
# 64-bit OS/64-bit App
$CLSIDPath = "Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CLSID\$($CLSID)"
$ControlPanelPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace\$($CLSID)"
} elseif (([IntPtr]::Size -eq 8) -and ($DiscoverdCPL.Architecture -eq 32)) {
# 64-bit OS/32-bit App
$CLSIDPath = "Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\Wow6432Node\CLSID\$($CLSID)"
$ControlPanelPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\ControlPanelWOW64\NameSpace\$($CLSID)"
} elseif (([IntPtr]::Size -eq 4) -and ($DiscoverdCPL.Architecture -eq 32)) {
# 32-bit OS/32-bit App
$CLSIDPath = "Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CLSID\$($CLSID)"
$ControlPanelPath = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ControlPanel\NameSpace\$($CLSID)"
}
Add-OutputObject -ControlPanelName $JavaVersionFriendlyName -ControlPanelPath $ControlPanelPath -CLSIDPath $CLSIDPath -CLSID $CLSID -CLSIDName $JavaVersionFriendlyName -InfoTip "@$($Command),-2" -SystemControlPanelCategory 8 -DefaultIcon $Command -Command $Command -JavaVersion $JavaVersion -JavaVersionFriendlyName $JavaVersionFriendlyName -Status $Status
}
}
$OutputObjects = $OutputObjects | Sort JavaVersionFriendlyname
"Java Control Panel Applets (Total):`t`t$(($OutputObjects | Measure).Count)"
$NotInstalledJavaCPLApplets = $OutputObjects | Where {$_.Status -eq "NotInstalled"}
$Count = ($NotInstalledJavaCPLApplets | Measure).Count
"Java Control Panel Applets (NotInstalled):`t$($Count)"
if (($PSBoundParameters['Verbose']) -and ($Count)) {$NotInstalledJavaCPLApplets.JavaVersionFriendlyName | % {Write-Verbose "NotInstalled: $($_)"}}
$NotAvailableJavaCPLApplets = $OutputObjects | Where {$_.Status -eq "NotAvailable"}
$Count = ($NotAvailableJavaCPLApplets | Measure).Count
"Java Control Panel Applets (NotAvailable):`t$($Count)"
if (($PSBoundParameters['Verbose']) -and ($Count)) {$NotAvailableJavaCPLApplets.JavaVersionFriendlyName | % {Write-Verbose "NotAvailable: $($_)"}}
$AvailableJavaCPLApplets = $OutputObjects | Where {$_.Status -eq "Available"}
$Count = ($AvailableJavaCPLApplets | Measure).Count
"Java Control Panel Applets (Available):`t`t$($Count)"
if (($PSBoundParameters['Verbose']) -and ($Count)) {$AvailableJavaCPLApplets.JavaVersionFriendlyName | % {Write-Verbose "Available: $($_)"}}
#Remove Java Control Panel Applets
$Applets = @()
if ($Remove) {$Applets = $NotInstalledJavaCPLApplets}
if (($All) -or ($Reset)) {$Applets = $OutputObjects}
if (($Reset) -or ($Remove)) {
$Count = 0
$AppletCount = ($Applets | Measure).Count
"Java Control Panel Applets (Remove):`t`t$($AppletCount)"
if ($AppletCount -gt 0) {
foreach ($Applet In $Applets) {
if ((Remove-Applet -Applet $Applet) -eq $true) {$Count += 1}
}
}
"Java Control Panel Applets (Removed):`t`t$($Count)"
}
#Add Java Control Panel Applets
$Applets = @()
if (($Reset) -or ($Add)) {$Applets = $NotAvailableJavaCPLApplets}
if ($Reset) {$Applets += $AvailableJavaCPLApplets}
if (($Reset) -or ($Add)) {
$Count = 0
$AppletCount = ($Applets | Measure).Count
"Java Control Panel Applets (Add):`t`t$($AppletCount)"
if ($AppletCount -gt 0) {
foreach ($Applet In $Applets) {
if ((Add-Applet -Applet $Applet) -eq $true) {$Count += 1}
}
}
"Java Control Panel Applets (Added):`t`t$($Count)"
}
|
PowerShellCorpus/GithubGist/ned1313_3d5b87583aaff901c1bc_raw_61b6defc01c9263e3cc9d5da915aac17c59e249c_Get-VMStatistics.ps1
|
ned1313_3d5b87583aaff901c1bc_raw_61b6defc01c9263e3cc9d5da915aac17c59e249c_Get-VMStatistics.ps1
|
# Horizon View VM Data Collection Script
param(
#Log file location (uses current directory by default)
[string] $logfilelocation=".\",
#CSV file location (uses current directory by default)
[string] $csvfilelocation=".\",
#PoolID (leave blank for all pools)
[string] $poolID
)
#Create Export filename
$filename = Join-Path -Path $csvfilelocation -ChildPath "ViewVMStats_$(Get-date -f yyyy-MM-dd-hh-mm-ss).csv"
#Create log file
$logFile = Join-Path -Path $logfilelocation -ChildPath "VMStatisticsCollection_$(Get-date -f yyyy-MM-dd-hh-mm-ss).log"
#Get all VMs in all Pools or Pools specificed by ID
if($poolID){
$vms = get-pool -Pool_id $poolID | get-desktopVM
}
else{
$vms = get-pool | get-desktopVM
}
Add-Content $logFile -value ("$(get-date -f s) VMs loaded from all pools") -PassThru | Write-Host -ForegroundColor Yellow
#create stats variable
$vmstats = @()
Add-Content $logFile -value ("$(get-date -f s) Beginning Statistics retrieval") -PassThru | Write-Host -ForegroundColor Yellow
$prog = 0
$base = $vms.length
#get the statistics for each vm
foreach($vm in $vms){
Write-Progress -Activity "Collecting..." -PercentComplete (($prog/$base)*100) -CurrentOperation "$prog of $base complete" -Status "Please wait."
try{
$vmstats += Get-WmiObject -Namespace "root\cimv2" -ComputerName $vm.Name -Class Win32_PerfRawData_TeradiciPerf_PCoIPSessionNetworkStatistics -ErrorAction Stop
}
catch{
Add-Content $logFile -value ("$(get-date -f s) $($vm.Name) Collection Failed with Error $_") -PassThru | Write-Host -ForegroundColor Red
}
$prog++
}
#finish progress bar
Write-Progress -Activity "Collecting..." -Completed -Status "VM Stats collection complete."
#export results
Add-Content $logFile -value ("$(get-date -f s) Exporting Data to $filename") -PassThru | Write-Host -ForegroundColor Yellow
$vmstats | Export-Csv -Path $filename -NoTypeInformation
Add-Content $logFile -value ("$(get-date -f s) Quick Content") -PassThru | Write-Host -ForegroundColor Yellow
#show some quick stats on worst offenders
$topRXLoss = $vmstats | Sort-Object -Property RXPacketLossPercent -Descending | select __Server,RXPacketLossPercent,RXPacketLossPercent_Base -First 10
$topTXLoss = $vmstats | Sort-Object -Property TXPacketLossPercent -Descending | select __Server,TXPacketLossPercent,TXPacketLossPercent_Base -First 10
Write-Host -ForegroundColor Yellow "Top 10 RX Packet Loss"
$topRXLoss
Write-Host -ForegroundColor Yellow "`nTop 10 TX Packet Loss"
$topTXLoss
Write-Host -ForegroundColor Yellow "`nEnd of Script"
|
PowerShellCorpus/GithubGist/michaellwest_10010536_raw_43e7607ad66d7a95b594fd19b84f77c56f3ce5c7_UnusedMediaItems.ps1
|
michaellwest_10010536_raw_43e7607ad66d7a95b594fd19b84f77c56f3ce5c7_UnusedMediaItems.ps1
|
<#
.SYNOPSIS
Lists all media items that are not linked to other items.
.NOTES
Michael West
#>
# HasReference determines if the specified item is referenced by any other item.
function HasReference {
param(
$Item
)
$linkDb = [Sitecore.Globals]::LinkDatabase
$linkDb.GetReferrerCount($Item) -gt 0
}
<#
Get-MediaItemWithNoReference gets all the items in the media library
and checks to see if they have references. Each item that does not
have a reference is passed down the PowerShell pipeline.
#>
function Get-MediaItemWithNoReference {
$items = Get-ChildItem -Path "master:\sitecore\media library" -Recurse |
Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder }
foreach($item in $items) {
if(!(HasReference($item))) {
$item
}
}
}
# Setup a hashtable to make a more readable script.
$props = @{
InfoTitle = "Unused media items"
InfoDescription = "Lists all media items that are not linked to other items."
PageSize = 25
}
# Passing a hashtable to a command is called splatting. Call Show-ListView to produce
# a table with the results.
Get-MediaItemWithNoReference |
Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
@{Label="Updated"; Expression={$_.__Updated} },
@{Label="Updated by"; Expression={$_."__Updated by"} },
@{Label="Created"; Expression={$_.__Created} },
@{Label="Created by"; Expression={$_."__Created by"} },
@{Label="Path"; Expression={$_.ItemPath} }
Close-Window
|
PowerShellCorpus/GithubGist/kondratyev-nv_6906398_raw_b8a2789b4627adae0552b8413b642492b3f43adb_to-utf.ps1
|
kondratyev-nv_6906398_raw_b8a2789b4627adae0552b8413b642492b3f43adb_to-utf.ps1
|
[cmdletbinding()]
param(
[parameter(mandatory=$true, position=1)]
[string]$path,
[switch]$recurse,
[array]$include,
[array]$exclude,
[string]$filter
)
if( $recurse -eq $true )
{
$files = get-childitem -recurse `
-path $path `
-exclude $exclude `
-include $include `
-filter $filter `
| where { ! $_.PSIsContainer }
}
else
{
$files = get-childitem `
-path $path `
-exclude $exclude `
-include $include `
-filter $filter `
| where { ! $_.PSIsContainer }
}
foreach( $file in $files )
{
write-host $file.fullname
$data = get-content $file.fullname
$data | out-file -encoding utf8 -filepath $file.fullname
}
|
PowerShellCorpus/GithubGist/tricktrap_6799444_raw_5b2f57171114eaf5b621fa9b59de75424ddf03b2_vm_report.ps1
|
tricktrap_6799444_raw_5b2f57171114eaf5b621fa9b59de75424ddf03b2_vm_report.ps1
|
$prodvms | select -Property Name,@{Name='IPAddress';Expression={$_.Guest.IPAddress }},@{Name='OS';Expression={$_.Guest.OSFullName}},NumCpu,MemoryMB,@{Name='Disks';Expression={$_.Guest.Disks | % { $_.Path + ': ' + [Math]::Round($_.CapacityGB + $_.FreeSpaceGB, 2) }}} | out-gridview
|
PowerShellCorpus/GithubGist/peaeater_2d985fa25e575fffd2c6_raw_ef4b0fe4daf5ac3653d08cd0131e2a1298677d72_solr-dih-ingest-with-polling.ps1
|
peaeater_2d985fa25e575fffd2c6_raw_ef4b0fe4daf5ac3653d08cd0131e2a1298677d72_solr-dih-ingest-with-polling.ps1
|
<#
Trigger Solr update and poll for status.
- Writes events to Application Event Log; log source must already have been added
Peter Tyrrell
#>
param(
[Parameter(Mandatory=$false,Position=0)]
[string]$logsrc = "Andi Solr Update"
)
$triggerUrl = "http://localhost:8983/solr/core1/dataimport?command=full-import&clean=true&optimize=true&wt=xml"
$statusUrl = "http://localhost:8983/solr/core1/dataimport?command=status&wt=xml&indent=on"
[int]$interval = 5
function logError([string]$msg) {
# write error msg to Application EventLog
Write-EventLog -LogName Application -Source $logsrc -EventId 500 -EntryType Error -Message $msg -Category 0
Write-Host ("ERROR {0}" -f $msg)
}
function logInfo([string]$msg) {
# write info msg to Application EventLog
Write-EventLog -LogName Application -Source $logsrc -EventId 200 -EntryType Information -Message $msg -Category 0
Write-Host ("INFO {0}" -f $msg)
}
function logWarning([string]$msg) {
Write-EventLog -LogName Application -Source $logsrc -EventId 400 -EntryType Warning -Message $msg -Category 0
Write-Host ("WARNING {0}" -f $msg)
}
<#
Trigger Solr ingest and poll status.
#>
try {
$triggerReply = (new-object System.Net.WebClient).DownloadString($triggerUrl)
Write-Host ("Triggered Solr [{0}]:" -f $triggerUrl)
# Force at least one ping after interval. Immediate reply to trigger may relate to a former job status.
$status = "busy"
$statusReply
$xml
while ($status -eq "busy") {
# wait
Start-Sleep -Seconds $interval
# poll status
$statusReply = (new-object System.Net.WebClient).DownloadString($statusUrl)
# convert to XmlDocument and read status message: (busy/idle)
$xml = [xml]$statusReply
$status = ($xml.response.str | where { $_.name -eq "status"}).InnerText
# provide some feedback
if ($status -eq "busy") {
$docsFetched = $xml.SelectSingleNode("response/lst[@name = ""statusMessages""]/str[@name = ""Total Rows Fetched""]").InnerText
$docsProcessed = $xml.SelectSingleNode("response/lst[@name = ""statusMessages""]/str[@name = ""Total Documents Processed""]").InnerText
$docsSkipped = $xml.SelectSingleNode("response/lst[@name = ""statusMessages""]/str[@name = ""Total Documents Skipped""]").InnerText
Write-Host ("Reply from Solr: fetched={0} processed={1} skipped={2}" -f $docsFetched, $docsProcessed, $docsSkipped)
}
}
# Solr is done. Success or failure?
if ($status -eq "idle") {
$statusMsg = $xml.SelectSingleNode("response/lst[@name = ""statusMessages""]/str[@name = """"]").InnerText
if ($statusMsg.StartsWith("Indexing failed")) {
logError(("{0}`r`n`r`n{1}" -f $statusMsg, $statusReply))
}
elseif ($statusMsg.StartsWith("Indexing completed")) {
[int]$docsFailed = $xml.SelectSingleNode("response/lst[@name = ""statusMessages""]/str[@name = ""Total Documents Failed""]").InnerText
if ($docsFailed -eq 0) {
logInfo(("{0}`r`n`r`n{1}" -f $statusMsg, $statusReply))
}
else {
logWarning(("{0}`r`n`r`n{1}" -f $statusMsg, $statusReply))
}
}
else {
logWarning(("Unable to read Solr status message. Indexing success is unknown. Review the included reply for more info.`r`n`r`n{0}" -f $statusReply))
}
}
else {
logWarning(("Unable to read Solr status. Indexing may or may not have finished. Review the included reply for more info.`r`n`r`n{0}" -f $statusReply))
}
exit 0
}
catch [Exception] {
logError($_.Exception)
exit 1
}
|
PowerShellCorpus/GithubGist/guitarrapc_e7285c3c66e723e6d8cb_raw_a801a8d762d3219e4a3b09b1f78c2e00a7f47d20_MS14-045CheckPipeline.ps1
|
guitarrapc_e7285c3c66e723e6d8cb_raw_a801a8d762d3219e4a3b09b1f78c2e00a7f47d20_MS14-045CheckPipeline.ps1
|
$message = "font '{0}' found! Your environmet will trouble with MS14-045. See https://support.microsoft.com/kb/2982791"
$fontregistory = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts\'
(Get-Item -Path $fontregistory).Property | % {(Get-ItemProperty -path $fontregistory).$_ | where {$_.EndsWith('.otf')} | where {Test-Path $_} | %{ Write-Host ($message -f $_) -ForegroundColor Red;return}}
Write-Host 'Your environment is OK.'
|
PowerShellCorpus/GithubGist/giseongeom_5439927_raw_cbc159883022f56034da5ddc0b1bf088fa0a6b34_stacklimit-testing.ps1
|
giseongeom_5439927_raw_cbc159883022f56034da5ddc0b1bf088fa0a6b34_stacklimit-testing.ps1
|
function myfunc([int]$n)
{
if ($n -gt 0) { Write-Host $n ; myfunc($n-1) }
}
|
PowerShellCorpus/GithubGist/sweeneyrobb_bdeef74630a38086e3b3_raw_110d1e37a3daaee997dbd6bcc23455859d617e0c_New-Zip.ps1
|
sweeneyrobb_bdeef74630a38086e3b3_raw_110d1e37a3daaee997dbd6bcc23455859d617e0c_New-Zip.ps1
|
function New-Zip ( $zipFile, $file ) {
if ($file -is [string]) {
$file = Get-Item $file
}
set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
$zipFile = Get-Item $zipFile
$zipFile.IsReadOnly = $false
$zip = (New-Object -ComObject shell.application).NameSpace($zipFile.FullName)
if ($file.PSIsContainer) {
$file | get-childitem -exclude $zipFile.Name | foreach-object {
if ($_.Name -ne $zipFile.Name) {
$zip.CopyHere($_.FullName)
# not exactly sure why the wait is needed. prompts dialogs if not here.
Start-Sleep -Milliseconds 200
}
}
} else { $zip.CopyHere($file.FullName) }
}
|
PowerShellCorpus/GithubGist/Schweinehund_7345552_raw_6457a78a3d0243f457903f69e31f7b90b3238aaa_New-Function.ps1
|
Schweinehund_7345552_raw_6457a78a3d0243f457903f69e31f7b90b3238aaa_New-Function.ps1
|
Function New-Function
{
<#
#>
[CmdletBinding()]
PARAM
(
[Parameter(Mandatory=$true)]
[String]
$Parameter
)
BEGIN{}
PROCESS{}
END{}
}
|
PowerShellCorpus/GithubGist/mjul_5831679_raw_1be98260875a008dcf5a69a5352b52a05f011d30_Microsoft.PowerShell_profile.ps1
|
mjul_5831679_raw_1be98260875a008dcf5a69a5352b52a05f011d30_Microsoft.PowerShell_profile.ps1
|
#
# Set environment variables for Visual Studio Command Prompt
# http://stackoverflow.com/questions/2124753/how-i-can-use-powershell-with-the-visual-studio-command-prompt
#
pushd 'c:\Program Files (x86)\Microsoft Visual Studio 11.0\VC'
cmd /c "vcvarsall.bat&set" |
foreach {
if ($_ -match "=") {
$v = $_.split("="); set-item -force -path "ENV:\$($v[0])" -value "$($v[1])"
}
}
popd
write-host "`nVisual Studio 2012 Command Prompt variables set." -ForegroundColor Yellow
# Enable git support via GitHub client
. (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1")
|
PowerShellCorpus/GithubGist/guitarrapc_ded2a6118d7582a1b5ea_raw_79babbeee38c4cc2a4f27b500dc5c7e4ac6a755d_ConfiguraionServiceSample.ps1
|
guitarrapc_ded2a6118d7582a1b5ea_raw_79babbeee38c4cc2a4f27b500dc5c7e4ac6a755d_ConfiguraionServiceSample.ps1
|
Configuration Service
{
Service WinRM
{
Name = "WinRM"
State = "Running"
StartupType = "Automatic"
}
Service Winmgmt
{
Name = "Winmgmt"
State = "Running"
StartupType = "Automatic"
}
}
|
PowerShellCorpus/GithubGist/atifaziz_5779884_raw_921cb3035504189b8f4555584d8690b5ddc263a7_TimeStamp-Item.ps1
|
atifaziz_5779884_raw_921cb3035504189b8f4555584d8690b5ddc263a7_TimeStamp-Item.ps1
|
function TimeStamp-Item
{
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true,
HelpMessage = "Specifies the path to the item to timestamp")]
[string[]]$Path,
[switch]$Force = $false
)
PROCESS
{
ForEach ($path In $path)
{
$file = Get-Item $path -ea Stop | ? { (-not $_.PSIsContainer) }
if ($file -eq $null)
{
Write-Verbose "Skipping directory: $path"
continue
}
$ext = $file.Extension
$baseName = [IO.Path]::GetFileNameWithoutExtension($file.Name)
if ($baseName -match '^(.+?)_[0-9]{8}_[0-9]{6}$')
{
if (-not $force)
{
Write-Verbose "Skipping file that already appears time-stamped: $path"
continue
}
$baseName = $matches[1]
}
$newName = "$($baseName)_$($file.LastWriteTimeUtc.ToString('yyyyMMdd_HHmmss'))$ext"
Rename-Item $file $newName
}
}
}
|
PowerShellCorpus/GithubGist/cromwellryan_4657224_raw_ecd0ef4e434f4f185327a3325ae111896ad3b5a5_Get-Shelveset.ps1
|
cromwellryan_4657224_raw_ecd0ef4e434f4f185327a3325ae111896ad3b5a5_Get-Shelveset.ps1
|
[Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Common")
$script:tpcUrl "your tpc"
function Get-ShelvsetUrl {
<#
.Synopsis
Determines the url for a TFS Shelveset.
.Description
Determine the url for a TFS Shelveset and, optionally, copy or open the result.
.Parameter Name
The name of the Shelvset.
.Parameter Owner
The username of the Shelveset Owner.
.Parameter Launch
When true, the shelveset url will be opened in the default browser. Default: False.
.Parameter Copy
When true, the shelveset url will be placed in clipboard. Default: True.
.Example
get-shelveseturl -Shelveset "RDS - Profiling" -Owner "dev\\rcromwell"
Gets the shelvset url and places it in the clipboard.
.Example
get-shelveset "RDS - Profiling" "dev\\rcromwell" -Launch -Copy $false
Gets the shelvset url and places it in the clipboard. Uses position relative parameters for -Name and -Owner
Publishing a public Gist
#>
Param(
[Parameter(Position=0)]
$Name = (read-host "Shelveset"),
[Parameter(Position=1)]
$Owner = (read-host "Owner"),
[switch]$Launch = $false,
[switch]$Copy = $true
)
PROCESS {
$tpc = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection $tpcUrl
$hlsvc = $tpc.GetService([Microsoft.TeamFoundation.Client.TswaClientHyperlinkService])
$details = $hlsvc.GetShelvesetDetailsUrl($Name, $Owner)
$url = $details.AbsoluteUri
if($Launch) { start $url }
if($Copy) { $url | clip }
$url
}
}
|
PowerShellCorpus/GithubGist/rossnz_8519986_raw_ded0c74256f5db6547a8209ecb52dbf9c619d50a_gistfile1.ps1
|
rossnz_8519986_raw_ded0c74256f5db6547a8209ecb52dbf9c619d50a_gistfile1.ps1
|
Function Convert-ToUnixDate ($PSdate) {
$epoch = [timezone]::CurrentTimeZone.ToLocalTime([datetime]'1/1/1970')
(New-TimeSpan -Start $epoch -End $PSdate).TotalSeconds
}
|
PowerShellCorpus/GithubGist/timbodv_850037ec80251c58b7f8_raw_e5df9fe8d00a8bbe39aaafca01e18e1807942116_O365BulkLicenseAssignment.ps1
|
timbodv_850037ec80251c58b7f8_raw_e5df9fe8d00a8bbe39aaafca01e18e1807942116_O365BulkLicenseAssignment.ps1
|
# get a list of licenses and plans
Get-MsolAccountSku | foreach { Write-Output "$($_.AccountSkuId)"; foreach ($status in $_.ServiceStatus) { Write-Output $status } }
# example to modify a user
$license = New-MsolLicenseOptions -AccountSkuId "tenant:STANDARDPACK" -DisabledPlans "MCOSTANDARD,EXCHANGE_S_STANDARD"
(Get-MsolUser)[1] | Set-MsolUserLicense -AddLicenses "tenant:STANDARDPACK"
(Get-MsolUser)[1] | Set-MsolUserLicense -LicenseOptions $license
|
PowerShellCorpus/GithubGist/josheinstein_5355916_raw_9211dc870206150b242ac471ed244e0b1de43fce_Disable-TemporaryRules.ps1
|
josheinstein_5355916_raw_9211dc870206150b242ac471ed244e0b1de43fce_Disable-TemporaryRules.ps1
|
##############################################################################
#.SYNOPSIS
# Scans your Outlook rules (Outlook must be running) and disables any rules
# whose name matches a specific pattern such as:
# Move Stuff (Until 4/10/2013 5:00 PM)
# Ignore Stuff (Until 4/11/2013)
#
#.DESCRIPTION
#
# To create temporary rules in Outlook, just create rules as you would
# normally, but name them such that they end in " (Until date)" or
# " Until (date time)".
#
# The script should be run using the Windows Task scheduler or some other
# mechanism that will periodically run it so that rules will be disabled when
# they are set to expire.
##############################################################################
[CmdletBinding(DefaultParameterSetName='Run', SupportsShouldProcess=$true)]
param(
# When this switch is present, Outlook will be started if it is not
# already running. Otherwise the script will return an error if
# Outlook is not running.
[Parameter(ParameterSetName='Run')]
[Switch]$Force,
# When this switch is present, the job will be scheduled with Windows
# Task Scheduler to run hourly at 5 minutes past the hour.
# Note that no precautions are taken to prevent multiple jobs being
# scheduled so that's on you.
[Parameter(ParameterSetName='Schedule')]
[Switch]$Schedule
)
##############################################################################
# PRIVATE FUNCTIONS
# Get a running COM object from the running object table
function Get-ComObject([String]$ComObject, [Switch]$Force) {
try {
[System.Runtime.InteropServices.Marshal]::GetActiveObject($ComObject)
}
catch [System.Management.Automation.MethodInvocationException] {
if ( $Force ) { New-Object -ComObject $ComObject }
else { Write-Error "An active object of type $ComObject is not available." }
}
}
# Decrement (or zero out if -Force) the reference count of the RCW
function Release-ComObject([Object[]]$Object, [Switch]$Force) {
foreach ($O in $Object) {
if ($O -eq $Null) { continue; }
[Int32]$Remaining = 0
do {
$Remaining = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($O)
} while ($Force -and $Remaining -gt 0)
Write-Verbose "Release COM Object: $Remaining remaining"
}
}
# Pulls off the expiration date from the name of a rule and stores
# it as an extended property on the Rule object
filter ParseExpirationDate {
$Expires = $Null
if ($_.Name -match " \(Until (.*)\)$") {
try {
$Expires = [DateTime]::Parse($Matches[1])
}
catch {
Write-Warning "Couldn't parse $($Matches[1]) as a date. Skipping."
}
}
if ($Expires) {
Add-Member NoteProperty Expires $Expires -InputObject:$_ -PassThru
}
}
# END FUNCTIONS
##############################################################################
switch ($PSCmdlet.ParameterSetName) {
# Scheduling mode registers with Windows Task Schedule to
# run every hour at 5 minutes past the hour
'Schedule' {
Import-Module PSScheduledJob
$JobArgs = @{
Name = Split-Path $MyInvocation.MyCommand.Path -Leaf
FilePath = $MyInvocation.MyCommand.Path
Trigger = @(
@{Frequency='Daily'; At='12:05 AM'; RepetitionInterval='01:00:00'; RepetitionDuration='1.00:00:00'}
)
}
Register-ScheduledJob @JobArgs
}
# Run mode runs the script on demand
# This is the default mode if the -Schedule switch is not provided
'Run' {
# Reserve these in scope so we can safely release
# them later without trouncing on a higher scope
$Outlook = $Null
$OutlookSession = $Null
$OutlookStore = $Null
$OutlookRules = $Null
try {
# Any of these could fail because, well... Outlook. Yeah.
# So the finally block will take care of releasing whatever
# was acquired.
$Outlook = Get-ComObject Outlook.Application -Force:$Force
$OutlookSession = $Outlook.Session
$OutlookStore = $OutlookSession.DefaultStore
$OutlookRules = $OutlookStore.GetRules()
$NeedsSave = $False
$OutlookRules |
ParseExpirationDate |
Where { $_.Enabled } |
Where { $_.Expires -lt [DateTime]::Now } |
ForEach {
# If the -WhatIf switch was used, this will return
# false after writing a message to the host
if ($PSCmdlet.ShouldProcess($_.Name)) {
$_.Enabled = $False
$NeedsSave = $True
Write-Host "Disabled expired rule: $($_.Name)"
}
}
if ($NeedsSave) {
$OutlookRules.Save()
}
}
finally {
# Zeroes out the reference count of the runtime-callable wrappers
Release-ComObject -Force (
$OutlookRules,
$OutlookStore,
$OutlookSession,
$Outlook
)
}
}
}
|
PowerShellCorpus/GithubGist/joshtransient_5984697_raw_f67285a1eee7a859068eca9a09437ace1cc16863_Find-WebPartsById.ps1
|
joshtransient_5984697_raw_f67285a1eee7a859068eca9a09437ace1cc16863_Find-WebPartsById.ps1
|
param([string] $webconfigpath = 'c:\path\to\web.config')
$apppath = new-object System.IO.FileInfo $webconfigpath
$binpath = [System.IO.Path]::Combine($apppath.Directory.FullName, 'bin\')
$wpClassAspNet = [System.Type]::GetType('System.Web.UI.WebControls.WebParts.WebPart, System.Web, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a')
#$wpClassSharePoint = [System.Reflection.Assembly]::LoadFrom('C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll').GetType('Microsoft.SharePoint.WebPartPages.WebPart')
function Get-AssemblyWebparts([Parameter(ValueFromPipeline=$True)][string] $assemblyName){
if ($assemblyName -match 'Microsoft.SharePoint' -or $assemblyName -match 'System.Web' -or [string]::IsNullOrEmpty($assemblyName)) {
return
}
try {
$a = [System.Reflection.Assembly]::Load($assemblyname)
} catch {
$idx = $assemblyname.IndexOf(',')
if ($idx -ge 0){ $path = $assemblyname.Substring(0, $idx) }
else { $path = $assemblyname }
$a = [System.Reflection.Assembly]::LoadFrom($binpath + $path+'.dll')
}
if ($a -eq $null) {
write-host "Unable to resolve assembly $assemblyName"
return
}
$a.GetTypes() | where-object {$_.IsSubclassOf($wpClassAspNet)}
}
function Get-WebpartTypeId([System.Type] $wpType){
$prov = new-object System.Security.Cryptography.MD5CryptoServiceProvider
[Guid]$prov.ComputeHash( [System.Text.Encoding]::Unicode.GetBytes( $wpType.Assembly.FullName + "|" + $wpType.FullName ) )
}
function New-Tuple() {
param ( [object[]]$list= $(throw "Please specify the list of names and values") )
$tuple = new-object psobject
for ( $i= 0 ; $i -lt $list.Length; $i = $i+2) {
$name = [string]($list[$i])
$value = $list[$i+1]
$tuple | add-member NoteProperty $name $value
}
return $tuple
}
[xml]$config = gc $webconfigpath
$assemblies = $config.SelectNodes('//SafeControl') | where-object {$_.Safe -ieq 'True' } | group-object -Property Assembly | %{$_.Name.ToString()}
$f = @{Expression={$_.Assembly.FullName};Label='Assembly'},@{Expression={$_.FullName};Label='Type'},@{Expression={Get-WebpartTypeId $_};Label='ID'}
#Get-AssemblyWebparts 'PS.WebParts.Rollup, Version=12.0.0.0, Culture=neutral, PublicKeyToken=90e3045b123af1c3' | format-table $f
$types = $assemblies | foreach-object { Get-AssemblyWebparts $_ }
$types | foreach-object { $id = Get-WebpartTypeId $_; new-tuple Assembly,$_.Assembly.FullName,Type,$_.FullName,Id,$id}
|
PowerShellCorpus/GithubGist/techraf_68cf5d8ec6b0ae0062f4_raw_f8b07348c204919a1483d19c17a7cbb98e14567c_profile.ps1
|
techraf_68cf5d8ec6b0ae0062f4_raw_f8b07348c204919a1483d19c17a7cbb98e14567c_profile.ps1
|
# This is intended to be a profile for PowerShell user
# The location of the file can be displayed by using the following command:
# $profile
# Default is:
# C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# It can be edited with
# notepad $profile
# (however when creating a file this way, a parent directory must exist)
#
# re-read (source) just like in bash
# . $profile
###########################################################################
# Host output
# write-host "message"
# reference http://technet.microsoft.com/en-us/library/hh849877.aspx
# below are default PowerShell colors for PS console run through shortcut
# when powershell is executed from command.exe, the background does not
# change, ie. usually is black
# for some reason "darkyellow" is displayed as white, well whitish
# for reference see:
# http://www.leeholmes.com/blog/2008/06/01/powershells-noble-blue/
# http://stackoverflow.com/questions/21941606/why-does-powershell-display-darkyellow-text-improperly
# $host.UI.RawUI.BackgroundColor="darkmagenta"
# $host.UI.RawUI.ForegroundColor="darkyellow"
###########################################################################
# Error stream
# write-error "message"
# reference: http://technet.microsoft.com/en-us/library/hh849962.aspx
$host.PrivateData.ErrorBackgroundColor = $host.UI.RawUI.BackgroundColor
$host.PrivateData.ErrorForegroundColor = "yellow"
###########################################################################
# Warning message stream
# write-warning "message"
# reference: http://technet.microsoft.com/en-us/library/hh849931.aspx
$host.PrivateData.WarningBackgroundColor = $host.UI.RawUI.BackgroundColor
$host.PrivateData.WarningForegroundColor = "yellow"
###########################################################################
# Debug message stream
# write-debug "message"
# $DebugPreference='SilentlyContinue'
# $DebugPreference='Continue'
# reference: http://technet.microsoft.com/en-us/library/hh849969.aspx
$host.PrivateData.DebugBackgroundColor = $host.UI.RawUI.BackgroundColor
$host.PrivateData.DebugForegroundColor = "cyan"
###########################################################################
# Verbose message stream
# write-verbose "message"
# $VerbosePreference='SilentlyContinue'
# $VerbosePreference='Continue'
# reference: http://technet.microsoft.com/en-us/library/hh849951.aspx
$host.PrivateData.VerboseBackgroundColor = $host.UI.RawUI.BackgroundColor
$host.PrivateData.VerboseForegroundColor = "cyan"
###########################################################################
# Progress bar
# reference: http://technet.microsoft.com/en-us/library/hh849902.aspx
$host.PrivateData.ProgressBackgroundColor = $host.UI.RawUI.BackgroundColor
$host.PrivateData.ProgressForegroundColor = "cyan"
|
PowerShellCorpus/GithubGist/theerikandersson_ddd1da5833e467654659_raw_f442d7a11b45200aa1ea92b8f60dd0146c7ec383_gistfile1.ps1
|
theerikandersson_ddd1da5833e467654659_raw_f442d7a11b45200aa1ea92b8f60dd0146c7ec383_gistfile1.ps1
|
# -------- config-parameters ------------
# db config
$userid = "{uid}"
$password = "{pwd}"
$connstring = "Data Source={server};Initial Catalog={db};User Id={0};Password={1}" -f $userid,$password
# output file config
$outpath = "{output folder}"
$filprefix = "{prefix for saved file}"
# sql config
$sql = "{select query or sp or what not}"
# ----end of config parameters-------------
Add-Type -AssemblyName System.Data
$conn = New-Object System.Data.SqlClient.SqlConnection($connString)
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($sql,$conn)
$adapter.SelectCommand.CommandTimeout = 1800 # 30 min timeout
$dt = New-Object System.Data.DataTable
$adapter.Fill($dt)
$csv = $dt | Convertto-Csv -Delimiter ";" -NoTypeInformation
$csvstripped = $csv -Replace '"',""
$csvpath = [System.IO.Path]::Combine($outpath, "{0}_{1}.csv" -f @($filprefix, [DateTime]::Now.ToString("yyyyMMddHHmmss")))
$csvstripped | Set-Content -Path $csvpath
Write-Host "Done!"
|
PowerShellCorpus/GithubGist/zheref_9586910_raw_3b04db687fdf6f729d810babae140042017ee6f2_gistfile1.ps1
|
zheref_9586910_raw_3b04db687fdf6f729d810babae140042017ee6f2_gistfile1.ps1
|
# ==============================================================================
#
# Fervent Coder Copyright 2011 - Present - Released under the Apache 2.0 License
#
# Copyright 2007-2008 The Apache Software Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# ==============================================================================
# variables
$url = "http://chocolatey.org/api/v2/package/chocolatey/"
$chocTempDir = Join-Path $env:TEMP "chocolatey"
$tempDir = Join-Path $chocTempDir "chocInstall"
if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)}
$file = Join-Path $tempDir "chocolatey.zip"
function Download-File {
param (
[string]$url,
[string]$file
)
Write-Host "Downloading $url to $file"
$downloader = new-object System.Net.WebClient
$downloader.DownloadFile($url, $file)
}
# download the package
Download-File $url $file
# download 7zip
Write-Host "Download 7Zip commandline tool"
$7zaExe = Join-Path $tempDir '7za.exe'
Download-File 'https://github.com/chocolatey/chocolatey/blob/master/src/tools/7za.exe?raw=true' "$7zaExe"
# unzip the package
Write-Host "Extracting $file to $tempDir..."
Start-Process "$7zaExe" -ArgumentList "x -o`"$tempDir`" -y `"$file`"" -Wait
#$shellApplication = new-object -com shell.application
#$zipPackage = $shellApplication.NameSpace($file)
#$destinationFolder = $shellApplication.NameSpace($tempDir)
#$destinationFolder.CopyHere($zipPackage.Items(),0x10)
# call chocolatey install
Write-Host "Installing chocolatey on this machine"
$toolsFolder = Join-Path $tempDir "tools"
$chocInstallPS1 = Join-Path $toolsFolder "chocolateyInstall.ps1"
& $chocInstallPS1
write-host 'Ensuring chocolatey commands are on the path'
$chocInstallVariableName = "ChocolateyInstall"
$chocoPath = [Environment]::GetEnvironmentVariable($chocInstallVariableName, [System.EnvironmentVariableTarget]::User)
$chocoExePath = 'C:\Chocolatey\bin'
if ($chocoPath -ne $null) {
$chocoExePath = Join-Path $chocoPath 'bin'
}
if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower()) -eq $false) {
$env:Path = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine);
}
# update chocolatey to the latest version
#Write-Host "Updating chocolatey to the latest version"
#cup chocolatey
|
PowerShellCorpus/GithubGist/jbogard_4953697_raw_917870ca2c13f361bd12ff1a092cad289982a1de_DeleteAllPrivateQueues.ps1
|
jbogard_4953697_raw_917870ca2c13f361bd12ff1a092cad289982a1de_DeleteAllPrivateQueues.ps1
|
[Reflection.Assembly]::LoadWithPartialName("System.Messaging")
[System.Messaging.MessageQueue]::GetPrivateQueuesByMachine("localhost") | % { [System.Messaging.MessageQueue]::Delete($_.Path) }
|
PowerShellCorpus/GithubGist/alienone_e193806de56416aff829_raw_698380cea68fea077ce1c74666595be2b499b133_new_get_stats.ps1
|
alienone_e193806de56416aff829_raw_698380cea68fea077ce1c74666595be2b499b133_new_get_stats.ps1
|
$REMOTEREGISTRY = "C:\Temp\remote-registry.csv"
$REMOTEMASTERREGISTRY = "C:\Temp\remote-master-registry.csv"
Function ParseXMLConfig{
$timestamp = $((get-date).ToString("yyyyMMddThhmmss"))
$agenthostname = $env:computername
$processtable = (gwmi win32_service|?{$_.name -like "*arc_*"})
$process_array = $processtable.pathname
foreach ($process_path in $process_array) {
$str_array = $process_path.split(' ')[0]
$pos = $str_array.IndexOf("\current")
$processpath = $str_array.SubString(0, $pos) + "\current\"
$arc_home_path = $processpath + "user\agent\"
$path_hash = dir $arc_home_path *xml
$xml_file = $arc_home_path + $path_hash[0].Name
[xml]$xml_content = Get-Content $xml_file
$agentid = $xml_content.ExtendedConfig.AgentId
$agentlocation = $xml_content.ExtendedConfig.AgentLocation
$agentname = $xml_content.ExtendedConfig.AgentName
$agenttype = $xml_content.ExtendedConfig.AgentType
$agentversion = $xml_content.ExtendedConfig.AgentVersion
$devicelocation = $xml_content.ExtendedConfig.DeviceLocation
New-Object PsObject -Property @{TimeStamp = $timestamp; `
AgentHostName = $agenthostname; AgentId = $agentid; `
AgentName = $agentname; AgentType = $agenttype; `
AgentVersion = $agentversion; AgentLocation = $agentlocation; `
DeviceLocation = $devicelocation }
}
}
Function GetProcessState{
$processtable = (gwmi win32_service|?{$_.name -like "*arc_*"})
foreach ($process in $processtable) {
($process.State) -split "`n"
}
}
Function GetProcessName{
$processtable = (gwmi win32_service|?{$_.name -like "*arc_*"})
foreach ($process in $processtable) {
($process.Name) -split "`n"
}
}
Function Get-ComputerStats {
param(
[Parameter(Mandatory=$true, Position=0,
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[string[]]$ComputerName
)
foreach ($c in $ComputerName) {
$avg = Get-WmiObject win32_processor -computername $c |
Measure-Object -property LoadPercentage -Average |
Foreach {$_.Average}
$mem = Get-WmiObject win32_operatingsystem -ComputerName $c |
Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)}
$processtable = (gwmi win32_service|?{$_.name -like "*arc_*"})
$conn_process = $processtable | Measure-Object
$conn_count = $conn_process.Count
$xmlconfig = ParseXMLConfig
$process_name = GetProcessName
$process_state = GetProcessState
foreach ($hash in $xmlconfig){
Add-Member -InputObject $hash -MemberType NoteProperty -Name AvgCpuUtilization -Value $avg -Force
Add-Member -InputObject $hash -MemberType NoteProperty -Name AvgMemUtilization -Value $mem -Force
Add-Member -InputObject $hash -MemberType NoteProperty -Name ConnCount -Value $conn_count -Force
Add-Member -InputObject $hash -MemberType NoteProperty -Name ProcessName -Value $process_name -Force
Add-Member -InputObject $hash -MemberType NoteProperty -Name ProcessState -Value $process_state -Force
}
If (!(Test-Path $REMOTEREGISTRY)){New-Item $REMOTEREGISTRY -type file}
foreach ($hash in $xmlconfig){$hash | export-csv –Path $REMOTEREGISTRY -Append}
If (!(Test-Path $REMOTEMASTERREGISTRY)){New-Item $REMOTEMASTERREGISTRY -type file}
Import-Csv -Path $REMOTEREGISTRY | sort AgentId –Unique | Export-Csv –Path $REMOTEMASTERREGISTRY
}
}
Function MainFunction{
$env:COMPUTERNAME | Get-ComputerStats
}
MainFunction
|
PowerShellCorpus/GithubGist/rprouse_184f55de1e8cfe549d4b_raw_19ac1225a7ce29765dfdce77500c95c61235fc6e_ChocolateyInstall.ps1
|
rprouse_184f55de1e8cfe549d4b_raw_19ac1225a7ce29765dfdce77500c95c61235fc6e_ChocolateyInstall.ps1
|
#====================================================
# Setting up a new machine using BoxStarter
# 1.Install Windows 8.1 on a new machine.
# 2.Login.
# 3.Open a command prompt and enter the following:
# START http://boxstarter.org/package/nr/url?https://gist.githubusercontent.com/rprouse/184f55de1e8cfe549d4b/raw/eab3ea82ce33963e2222507c9802e9012f556b7c/ChocolateyInstall.ps1
#====================================================
#====================================================
# Boxstarter options
$Boxstarter.RebootOk=$true # Allow reboots?
$Boxstarter.NoPassword=$false # Is this a machine with no login password?
$Boxstarter.AutoLogin=$true # Save my password securely and auto-login after a reboot
#====================================================
# Basic Setup
#Update-ExecutionPolicy Unrestricted -Force
#Set-ExplorerOptions -showHidenFilesFoldersDrives -showFileExtensions
#Enable-RemoteDesktop
#Enable-MicrosoftUpdate
#Disable-InternetExplorerESC
#====================================================
# Power Configuration
#powercfg -x -standby-timeout-ac 0
#powercfg -x -standby-timeout-dc 0
#powercfg -x -monitor-timeout-ac 10
#powercfg -x -monitor-timeout-dc 10
#powercfg -x -hibernate-timeout-ac 0
#powercfg -x -hibernate-timeout-dc 0
#powercfg -x -disk-timeout-ac 20
#powercfg -x -disk-timeout-dc 20
#====================================================
# Programs and Tools
#cinst PowerShell
#cinst 7zip.commandline
#cinst 7zip.install
#cinst google-chrome-x64
#cinst filezilla
#cinst Gow
#cinst lockhunter
#cinst sysinternals
#cinst putty.install
#cinst notepadplusplus.install
#cinst ConsoleZ.WithPin
#cinst paint.net
#cinst vlc
#cinst cccp
#cinst dropbox
#cinst evernote
#cinst greenshot -Version 1.1.9.13
#cinst IcoFx
#cinst imgburn
#cinst javaruntime
#cinst markdownpad2
#cinst sumatrapdf.install
#cinst skype
#cinst truecrypt
#cinst windirstat
#cinst CCleaner
#cinst CutePDF
#cinst Silverlight
#====================================================
# Source Control
#cinst git.install
#cinst poshgit
#cinst SourceTree
#====================================================
# .NET Development
#cinst VisualStudioCommunity2013
#cinst VS2013.4
cinst VS2013.VSCommands
cinst visualstudio2013-sdk
cinst cloc
cinst expresso
cinst nunit
#cinst xunit
cinst dotpeek
cinst resharper
cinst WinMerge
#cinst cmake
#cinst tfs2013powertools
#====================================================
# Web Development
#cinst nodejs.install
#cinst Yeoman
cinst fiddler4
#====================================================
# Android Development
cinst java.jdk
cinst AndroidStudio
cinst android-sdk
#cinst xamarin-studio
#====================================================
# Python
cinst python
#cinst python2
#====================================================
# Ruby
cinst ruby
cinst ruby.devkit
cinst Compass
cinst sass
#====================================================
# File Associations
Install-ChocolateyFileAssociation ".txt" "${env:ProgramFiles(x86)}\Notepad++\Notepad++.exe"
Install-ChocolateyFileAssociation ".xml" "${env:ProgramFiles(x86)}\Notepad++\Notepad++.exe"
Install-ChocolateyFileAssociation ".nuspec" "${env:ProgramFiles(x86)}\Notepad++\Notepad++.exe"
Install-ChocolateyFileAssociation ".config" "${env:ProgramFiles(x86)}\Notepad++\Notepad++.exe"
#====================================================
# Pin to the taskbar
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles)\Google\Chrome\Application\chrome.exe"
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe"
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Evernote\Evernote\evernote.exe"
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Notepad++\Notepad++.exe"
#====================================================
# Install Visual Studio Extensions
#Install-ChocolateyVsixPackage add-empty-file https://visualstudiogallery.msdn.microsoft.com/3f820e99-6c0d-41db-aa74-a18d9623b1f3/file/140782/6/AddAnyFile.vsix
#Install-ChocolateyVsixPackage boost-test-adapter https://visualstudiogallery.msdn.microsoft.com/5f4ae1bd-b769-410e-8238-fb30beda987f/file/105652/19/BoostUnitTestAdapter.vsix
Install-ChocolateyVsixPackage web-essentials https://visualstudiogallery.msdn.microsoft.com/6ed4c78f-a23e-49ad-b5fd-369af0c2107f/file/50769/32/WebEssentials.vsix
#Install-ChocolateyVsixPackage chutzpah https://visualstudiogallery.msdn.microsoft.com/f8741f04-bae4-4900-81c7-7c9bfb9ed1fe/file/66979/28/Chutzpah.VS2012.vsix
Install-ChocolateyVsixPackage editor-config https://visualstudiogallery.msdn.microsoft.com/c8bccfe2-650c-4b42-bc5c-845e21f96328/file/75539/12/EditorConfigPlugin.vsix
#Install-ChocolateyVsixPackage file-nesting https://visualstudiogallery.msdn.microsoft.com/3ebde8fb-26d8-4374-a0eb-1e4e2665070c/file/123284/11/FileNesting.vsix
#Install-ChocolateyVsixPackage grunt-launcher https://visualstudiogallery.msdn.microsoft.com/dcbc5325-79ef-4b72-960e-0a51ee33a0ff/file/109075/17/GruntLauncher.vsix
Install-ChocolateyVsixPackage multi-editing https://visualstudiogallery.msdn.microsoft.com/2beb9705-b568-45d1-8550-751e181e3aef/file/93630/8/MultiEdit.vsix
Install-ChocolateyVsixPackage nunit-test-adapter https://visualstudiogallery.msdn.microsoft.com/6ab922d0-21c0-4f06-ab5f-4ecd1fe7175d/file/66177/15/NUnitVisualStudioTestAdapter-1.2.vsix
#Install-ChocolateyVsixPackage package-intellisense https://visualstudiogallery.msdn.microsoft.com/65748cdb-4087-497e-a394-2e3449c8e61e/file/138140/11/JSON%20Intellisense.vsix
#Install-ChocolateyVsixPackage side-waffle https://visualstudiogallery.msdn.microsoft.com/a16c2d07-b2e1-4a25-87d9-194f04e7a698/referral/110630
#Install-ChocolateyVsixPackage fsharp-power-tools https://visualstudiogallery.msdn.microsoft.com/136b942e-9f2c-4c0b-8bac-86d774189cff/file/124201/24/FSharpVSPowerTools.vsix
#Install-ChocolateyVsixPackage vs-installer-projects https://visualstudiogallery.msdn.microsoft.com/9abe329c-9bba-44a1-be59-0fbf6151054d/file/130817/3/VSI_bundle.exe
#Install-ChocolateyVsixPackage rebracer https://visualstudiogallery.msdn.microsoft.com/410e9b9f-65f3-4495-b68e-15567e543c58/file/120672/4/Rebracer.vsix
#====================================================
# Windows Features
#cinst Microsoft-Hyper-V-All -source windowsFeatures
cinst IIS-WebServerRole -source windowsfeatures
#====================================================
# Windows Update
Install-WindowsUpdate -getUpdatesFromMS -acceptEula -SuppressReboots
#====================================================
# Scaffold out folder system
if (!(Test-Path -Path C:\src )) {
mkdir C:\src
}
if (!(Test-Path -Path C:\src\nunit )) {
mkdir C:\src\nunit
}
if (!(Test-Path -Path C:\src\alteridem )) {
mkdir C:\src\alteridem
}
if (!(Test-Path -Path C:\src\3rdParty )) {
mkdir C:\src\3rdParty
}
if (!(Test-Path -Path C:\src\learning )) {
mkdir C:\src\learning
}
if (!(Test-Path -Path C:\src\spikes )) {
mkdir C:\src\spikes
}
if (!(Test-Path -Path C:\bin )) {
mkdir C:\bin
}
if (!(Test-Path -Path C:\tmp )) {
mkdir C:\tmp
}
#====================================================
# Last because they won't auto-install
#cinst uTorrent
if (Test-PendingReboot) { Invoke-Reboot }
|
PowerShellCorpus/GithubGist/chgeuer_4127323_raw_440c8f454e43da3661673147638cfba1f663436a_rename-iplusplus.ps1
|
chgeuer_4127323_raw_440c8f454e43da3661673147638cfba1f663436a_rename-iplusplus.ps1
|
function Rename-ItemsPrepend {
[CmdletBinding()]
param
(
[Parameter(Mandatory=$True,
ValueFromPipeline=$False,
ValueFromPipelineByPropertyName=$True,
HelpMessage='Which number should be first prefixed')]
[int]$start
)
begin {
write-verbose "Renaming files"
}
process {
write-verbose "Beginning process loop"
$i = $start
Get-ChildItem | Sort-Object -Property CreationTime | foreach ($_) {
$nn = [System.String]::Format("{0:d2}__{1}", $i++, $_.Name)
Rename-Item -Path $_.FullName -NewName $nn
}
}
}
Set-Alias -Name renumber -Value Rename-ItemsPrepend
|
PowerShellCorpus/GithubGist/mortenya_3ce1abd86b84ad3038fe_raw_46d4335f4e3f2a1681519ee593fc28912a06d66b_Parse-DHCPLog.ps1
|
mortenya_3ce1abd86b84ad3038fe_raw_46d4335f4e3f2a1681519ee593fc28912a06d66b_Parse-DHCPLog.ps1
|
Function Get-FileName($initialDirectory) {
Add-Type -Assembly System.windows.forms | Out-Null
$initialDirectory = "C:\"
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $initialDirectory
$OpenFileDialog.Filter = "Log files (*.Log)| DhcpSrvLog-*.log"
$OpenFileDialog.Multiselect = $false
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.FileName
} #end function Get-FileName
# *** Entry Point to Script ***
$log = Get-FileName
$logdate = (Get-ItemProperty $log).LastWriteTime.AddDays(-1) -split ' '
$namedate = $logdate[0] -split '/' -join '-'
$events = Get-Content $log
$csvhead = "ID","Date","Time","Description","IP Address","Host Name","MAC Address","User Name","TransactionID","QResult","Probationtime",`
"CorrelationID","Dhcid","VendorClass(Hex)","VendorClass(ASCII)","UserClass(Hex)","UserClass(ASCII)","RelayAgentInformation","DnsRegError"
$lines = $events | Select-String -Pattern "\b(?:\d{1,3}\.){3}\d{1,3}\b" | ConvertFrom-Csv -Header $csvhead
$csvfile = $lines | where { $_.ID -eq '10' } | select -Unique 'MAC Address','Host Name','IP Address'
$Pre = "<h1>DHCP Log ""$($log.Split('\.')[-2])"" from ""$($logdate[0])""</h1> <h2>There were $($csvfile.Length) unique leases.</h2>"
#Create the HTML formating
$Header = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
</style>
<Title>
New IP Address Leases
</Title>
"@
#And create HTML file...
$csvfile | sort-object 'MAC Address' | ConvertTo-HTML -PreContent $Pre -head $Header | Out-File -Append "$env:USERPROFILE\Documents\$($log.Split('\.')[-2])-$namedate.html"
|
PowerShellCorpus/GithubGist/andreaswasita_37a0ab92353a93751e2f_raw_14c3f64297b3ec9b5c362cc74cfa03569f8d58ce_SetAzureVNETGWKey.ps1
|
andreaswasita_37a0ab92353a93751e2f_raw_14c3f64297b3ec9b5c362cc74cfa03569f8d58ce_SetAzureVNETGWKey.ps1
|
Set-AzureVNetGatewayKey -VNetName USVNET -LocalNetworkSiteName SEVNET -SharedKey mypresharedkeysevnet9876
Set-AzureVNetGatewayKey -VNetName SEVNET -LocalNetworkSiteName UVNET -SharedKey mypresharedkeysevnet9876
|
PowerShellCorpus/GithubGist/CSharpFan_3466695_raw_025e02ba98cdf82e399cd8e0b4950b20c5e93a66_MyAwesomeFunction.ps1
|
CSharpFan_3466695_raw_025e02ba98cdf82e399cd8e0b4950b20c5e93a66_MyAwesomeFunction.ps1
|
function MyAwesomeFunction
{
param
(
[string] $foo,
[string] $bar,
[switch] $someVariable
)
Write-Host "someVariable = $someVariable"
if($someVariable)
{
Write-Host $foo
}
else
{
Write-Host $bar
}
}
MyAwesomeFunction -foo "Foo" -Bar "Bar"
|
PowerShellCorpus/GithubGist/GuruAnt_5442438_raw_51d1118c3b913d8f6fcf6a18a215ef8673afacf8_PowerCLIScriptExample1.ps1
|
GuruAnt_5442438_raw_51d1118c3b913d8f6fcf6a18a215ef8673afacf8_PowerCLIScriptExample1.ps1
|
# Get the name of the machine from the user
$strVM = Read-Host "Please enter the VM name"
# Attempt to get a machine-object with that name, continue silently if no machine found
$objectVM = Get-VM -Name $strVM -ErrorAction SilentlyContinue
# If there is a machine found
If ($objectVM) {
# Display the machine object name on screen
Write-Host "Machine object name:" $objectVM.Name
# Display the power state on screen
Write-Host "Power State:" $objectVM.PowerState
# Attempt to get the object representing the virtual machine's guest
$objVMGuest = Get-VMGuest -VM $objectVM -ErrorAction SilentlyContinue
# If that object is retreived (i.e., if VMWare tools has been running)
If ($objVMGuest){
# Display the guest hostname on screen
Write-Host "Hostname:" $objVMGuest.Hostname
# Get the IP address(es), and write them to screen
$objVMGuest.IPAddress | ForEach-Object {
# If more than one IP address is found, this will write each one to screen on a seperate line
Write-Host "IP Address:" $_
}
}
}
# If there is no machine found with the name
Else {
# Display an error message
Write-Host "ERROR No machine found with the name:" $strVM
}
|
PowerShellCorpus/GithubGist/petermreid_573da2b83ccca9f92be8_raw_e6e61f99b3b5f8a4eb5c21f59d305cafcd7d0c3d_gistfile1.ps1
|
petermreid_573da2b83ccca9f92be8_raw_e6e61f99b3b5f8a4eb5c21f59d305cafcd7d0c3d_gistfile1.ps1
|
"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\makecert" -pe -n "CN=tenant.sharepointonline.com" -a sha1 -sky Exchange -eku 1.3.6.1.5.5.7.3.1 -ic CA.cer -iv CA.pvk -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 -sv tenant.sharepointonline.com.pvk tenant.sharepointonline.com.cer
"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\pvk2pfx" -pvk tenant.sharepointonline.com.pvk -spc tenant.sharepointonline.com.cer -pfx tenant.sharepointonline.com.pfx
|
PowerShellCorpus/GithubGist/michaelherndon_11165733_raw_bcd5eed1cf384e1c35bde5418a21654209401aaa_install-cmder.ps1
|
michaelherndon_11165733_raw_bcd5eed1cf384e1c35bde5418a21654209401aaa_install-cmder.ps1
|
<#
The Cmder chocolatey package is a hot mess.
This is a shame, because Cmder finally brings a decent tabbed console
interface to windows.
This script wraps the install of Cmder from Chocolatey:
* installs a start menu shortcut, which can be pinned
* removes all the batch files that automatically created from the vendor folder
* adds git-bash as a Cmder Task. Powershell & cmd already exist.
The MIT License (MIT)
Copyright (c) 2014 Michael Herndon dev.michaelherndon.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#>
#install chocolatey first
#https://gist.github.com/michaelherndon/11100457
if($env:ChocolateyInstall -eq "" -or $env:ChocolateyInstall -eq $null)
{
setx ChocolateyInstall "c:\opt\apps\chocolatey"
$env:ChocolateyInstall = "c:\opt\apps\chocolatey"
echo "path set"
}
if(! (Test-Path "$env:ChocolateyInstall\lib\Cmder.*"))
{
cinst Cmder
}
$test = gci "$env:ChocolateyInstall\lib\Cmder.*"
$folders = gci "$env:ChocolateyInstall\lib\Cmder.*" | ?{ $_.PSIsContainer -and -not $_.Name.Contains(".portable.") } | Sort-Object {$_.Name } -Descending
$cmder = $folders[0].FullName
$version = $cmder.Replace("Cmder.", "")
$version = $version.Substring($version.LastIndexOf("\") +1)
echo $version
# start menu shortcut
$shortCutPath = "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Cmder.lnk"
if(! (Test-Path $shortCutPath))
{
echo "Adding Start Menu Shortcut"
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($shortCutPath)
$Shortcut.TargetPath = 'cmd'
$Shortcut.Arguments = "/C ""$env:ChocolateyInstall\lib\cmder.portable.$version\tools\cmder\Cmder.bat"""
$Shortcut.IconLocation = "$env:ChocolateyInstall\lib\cmder.portable.$version\tools\cmder\icons\cmder.ico"
$Shortcut.WorkingDirectory = "$env:SystemDrive\opt\"
$Shortcut.Save()
}
# clean up all the clutter
$executables = gci "$env:ChocolateyInstall\lib\cmder.portable.$version\*.exe" -Recurse
$bin = "$env:ChocolateyInstall\bin"
if($executables.Length -gt 0)
{
echo "Cleaning up bat files"
}
foreach($exe in $executables)
{
$file = "$bin\" + $exe.Name.Replace(".exe", "")
$bat = $file + ".bat"
if(Test-Path ($file))
{
Remove-Item $file -Force
}
if(Test-Path ($file))
{
Remove-Item $bat -Force
}
}
# ConEmu config
$conEmuConfig = "$env:ChocolateyInstall\lib\cmder.portable.$version\tools\cmder\config\ConEmu.xml"
# Backup the configuration
if(! (Test-Path ($conEmuConfig + ".bck")))
{
Copy-Item $conEmuConfig ($conEmuConfig + ".bck")
}
[xml]$cfg = New-Object XML
$cfg.Load($conEmuConfig)
$xpath = "//key[@name=""Task3""]"
<#
<key name="Task3" modified="2014-01-07 12:14:38" build="131107">
<value name="Name" type="string" data="{git-bash}"/>
<value name="Hotkey" type="dword" data="00000000"/>
<value name="GuiArgs" type="string" data=""/>
<value name="Active" type="dword" data="00000000"/>
<value name="Count" type="dword" data="00000001"/>
<value name="Cmd1" type="string" data=""C:\opt\apps\chocolatey\lib\cmder.portable.1.1.1\tools\cmder\vendor\msysgit\bin\sh.exe" --login -i"/>
#>
$node = $cfg.key.key.key.key | Where-Object { $_.name -eq "Tasks" }
echo $node.ChildNodes.Count
$ns = $cfg.DocumentElement.NamespaceURI
Function CreateAttr($n, $value)
{
$attr = $cfg.CreateAttribute($n);
$attr.Value = $value
return $attr
}
# Add Git-Bash
if($node.ChildNodes.Count -eq 3)
{
echo "children"
# update count
$node.ChildNodes[0].SetAttribute("data", "00000003")
$task = $cfg.CreateElement("key", $ns)
$at = CreateAttr "name" "Task3"
$task.Attributes.Append($at)
$task.Attributes.Append((CreateAttr "modified" "2014-01-07 12:14:38"))
$task.Attributes.Append((CreateAttr "build" "131107" ))
$attr = $cfg.CreateElement("value", $cfg.DocumentElement.NamespaceURI)
$attr.Attributes.Append((CreateAttr "name" "Name"))
$attr.Attributes.Append((CreateAttr "type" "string"))
$attr.Attributes.Append((CreateAttr "data" "{git-bash}"))
$task.AppendChild($attr);
$hk = $cfg.CreateElement("value", $cfg.DocumentElement.NamespaceURI)
$hk.Attributes.Append((CreateAttr "name" "HotKey" ))
$hk.Attributes.Append((CreateAttr "type" "dword"))
$hk.Attributes.Append((CreateAttr "data" "00000000" ))
$task.AppendChild($hk);
$gui = $cfg.CreateElement("value", $cfg.DocumentElement.NamespaceURI)
$gui.Attributes.Append((CreateAttr "name" "GuiArgs"))
$gui.Attributes.Append((CreateAttr "type" "string"))
$gui.Attributes.Append((CreateAttr "data" ""))
$task.AppendChild($gui);
$act = $cfg.CreateElement("value",$cfg.DocumentElement.NamespaceURI)
$act.Attributes.Append((CreateAttr "name" "Active"))
$act.Attributes.Append((CreateAttr "type" "dword"))
$act.Attributes.Append((CreateAttr "data" "00000000"))
$task.AppendChild($act);
$ct = $cfg.CreateElement("value", $cfg.DocumentElement.NamespaceURI)
$ct.Attributes.Append((CreateAttr "name" "Count"))
$ct.Attributes.Append((CreateAttr "type" "dword"))
$ct.Attributes.Append((CreateAttr "data" "00000001"))
$task.AppendChild($ct);
$cm = $cfg.CreateElement("value", $cfg.DocumentElement.NamespaceURI)
$cm.Attributes.Append((CreateAttr "name" "Cmd1"))
$cm.Attributes.Append((CreateAttr "type" "string"))
$cm.Attributes.Append((CreateAttr "data" """$env:ChocolateyInstall\lib\cmder.portable.$version\tools\cmder\vendor\msysgit\bin\sh.exe"" --login -i"))
$task.AppendChild($cm);
$node.AppendChild($task);
}
$cfg.Save($conEmuConfig)
|
PowerShellCorpus/GithubGist/nobodyguy_9950375_raw_a47c28727c8646b96be87989a5c09541af0c230c_http_server.ps1
|
nobodyguy_9950375_raw_a47c28727c8646b96be87989a5c09541af0c230c_http_server.ps1
|
$ServerThreadCode = {
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add('http://+:8008/')
$listener.Start()
while ($listener.IsListening) {
$context = $listener.GetContext() # blocks until request is received
$request = $context.Request
$response = $context.Response
$message = "Testing server"
# This will terminate the script. Remove from production!
if ($request.Url -match '/end$') { break }
[byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message)
$response.ContentLength64 = $buffer.length
$response.StatusCode = 500
$output = $response.OutputStream
$output.Write($buffer, 0, $buffer.length)
$output.Close()
}
$listener.Stop()
}
$serverJob = Start-Job $ServerThreadCode
Write-Host "Listening..."
Write-Host "Press Ctrl+C to terminate"
[console]::TreatControlCAsInput = $true
# Wait for it all to complete
while ($serverJob.State -eq "Running")
{
if ([console]::KeyAvailable) {
$key = [system.console]::readkey($true)
if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C"))
{
Write-Host "Terminating..."
$serverJob | Stop-Job
Remove-Job $serverJob
break
}
}
Start-Sleep -s 1
}
# Getting the information back from the jobs
Get-Job | Receive-Job
|
PowerShellCorpus/GithubGist/sidewinder12s_39e83fc5542d818bc6f0_raw_4cc96284ebee82a48117fc8f2165ba8f3d63c755_pydio-dsc.ps1
|
sidewinder12s_39e83fc5542d818bc6f0_raw_4cc96284ebee82a48117fc8f2165ba8f3d63c755_pydio-dsc.ps1
|
# Powershell DSC configuration script for Pydio
# Be sure to set the $timezone and $repo variables
# The $repo location requires two folders - "installers" and "pydio-files"
# installers has php.zip (the latest PHP VC11 non-threadsafe zip), phpmanager.msi (the latest PHP Manager for IIS x64) and vcredist_x86.exe (VC++ Redistributable x86 11.0.61030)
# pydio-files has the latest Pydio zip unzipped to the base folder. This is done because unzip performance on DSC is rubbish
Configuration Pydio
{
param ($MachineName)
Node $MachineName
{
$timezone = "America/New_York"
$repo = "C:\pydio"
WindowsFeature IIS
{
#Installs IIS
Ensure = "Present"
Name = "Web-Server"
}
WindowsFeature CGI
{
#Enables CGI feature of IIS
Ensure = "Present"
Name = "Web-CGI"
}
WindowsFeature RequestFiltering
{
#Enables requesting filtering feature of IIS
Ensure = "Present"
Name = "Web-Filtering"
}
WindowsFeature URLAuthorization
{
#Enables requesting filtering feature of IIS
Ensure = "Present"
Name = "Web-Url-Auth"
}
WindowsFeature IISMC
{
#Enables IIS management console - not needed but useful for diagnosing issues
Ensure = "Present"
Name = "Web-Mgmt-Console"
}
Registry ComponentSource
{
#Sets Windows to download optional features directly from Windows update, not WSUS
#Useful for installing .net 3.5
Ensure = "Present"
Key = "hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Servicing"
ValueName = "RepairContentServerSource"
ValueData = "2"
ValueType = "Dword"
}
WindowsFeature DotNet35
{
#Installs .net Framework 3.5 for PHP Manager for IIS
Ensure = "Present"
Name = "Net-Framework-Core"
}
File CopyFiles
{
#Copies installer files from a network share to the local computer
Ensure = "Present"
Type = "Directory"
Recurse = $true
SourcePath = "$repo\installers"
DestinationPath = "C:\dsc\"
}
Package VS2010-32
{
#Install VC++ Redistributable x86 11.0.61030
DependsOn = "[File]CopyFiles"
Ensure = "Present"
Name = "Microsoft Visual C++ 2012 Redistributable (x86) - 11.0.61030"
Path = "C:\dsc\vcredist_x86.exe"
Arguments = "/install /quiet"
ProductId = ""
}
Package UrlRewrite
{
#Install URL Rewrite module for IIS
DependsOn = "[File]CopyFiles"
Ensure = "Present"
Name = "IIS URL Rewrite Module 2"
Path = "C:\dsc\urlrewrite.msi"
Arguments = "/quiet"
ProductId = "EB675D0A-2C95-405B-BEE8-B42A65D23E11"
}
Archive PHP
{
#Extracts PHP to C:\PHP
DependsOn = "[File]CopyFiles"
Ensure = "Present"
Path = "C:\dsc\php.zip"
Destination = "C:\PHP"
}
File PydioFiles
{
#Copies Pydio to C:\inetpub\wwwroot\Pydio
Ensure = "Present"
Type = "Directory"
Recurse = $true
SourcePath = "$repo\pydio-files\"
DestinationPath = "C:\inetpub\wwwroot\Pydio"
}
Package PHPManager
{
#Installs PHP Manager for IIS
DependsOn = "[File]CopyFiles"
Ensure = "Present"
Name = "PHP Manager 1.2 for IIS 7"
Arguments = "/quiet"
ProductId = "E851486F-1FE2-44F0-85ED-F969088A68EE"
Path = "C:\dsc\phpmanager.msi"
}
File PhpIni
{
#Copies php.ini-production to php.ini
DependsOn = "[Archive]PHP"
Ensure = "Present"
SourcePath = "C:\PHP\php.ini-production"
DestinationPath = "C:\PHP\php.ini"
}
Script PhpEntensionDir
{
#Sets PHP extension directory
DependsOn = "[File]PhpIni"
SetScript = {
$content = Get-Content "C:\PHP\php.ini" | %{ if ($_ -match '; extension_dir = "ext"') { $_ -replace '; extension_dir = "ext"','extension_dir = "C:\PHP\ext"' } else { $_ } }
if (!($content | ?{$_ -match "extension_dir = .+"})) { $content += "extension=php_sqlite3.dll" }
Set-Content -Path "C:\PHP\php.ini" -Value $content
}
TestScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq 'extension_dir = "C:\PHP\ext"'}
if ($config) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq 'extension_dir = "C:\PHP\ext"'}
return $config
}
}
Script PhpTimezone
{
#Sets time zone for PHP
DependsOn = "[File]PhpIni"
SetScript = {
$content = Get-Content "C:\PHP\php.ini" | %{ if ($_ -match ';date.timezone =.+') { $_ -replace ';date.timezone =.+','date.timezone = "$($timezone)"' } else { $_ } }
if (!($content | ?{$_ -match "date.timezone = .+"})) { $content += 'date.timezone = "$($timezone)"' }
Set-Content -Path "C:\PHP\php.ini" -Value $content
}
TestScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq 'date.timezone = "$($timezone)"'}
if ($config) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq 'date.timezone = "$($timezone)"'}
return $config
}
}
Script PhpOutputBuffering
{
#Disables PHP output buffering, as per best practice
DependsOn = "[File]PhpIni"
SetScript = {
$content = Get-Content "C:\PHP\php.ini" | %{ if ($_ -match "output_buffering = .+") { $_ -replace "output_buffering = .+","output_buffering = off" } else { $_ } }
Set-Content -Path "C:\PHP\php.ini" -Value $content
}
TestScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "output_buffering = off"}
if ($config) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "output_buffering = off"}
return $config
}
}
Script PhpSQLite
{
#Enables SQLite for inbuilt database
DependsOn = "[File]PhpIni"
SetScript = {
$content = Get-Content "C:\PHP\php.ini" | %{ if ($_ -match ";extension=php_sqlite3.dll") { $_ -replace ";","" } else { $_ } }
if (!($content | ?{$_ -eq "extension=php_sqlite3.dll"})) { $content += "extension=php_sqlite3.dll" }
Set-Content -Path "C:\PHP\php.ini" -Value $content
}
TestScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_sqlite3.dll"}
if ($config) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_sqlite3.dll"}
return $config
}
}
Script PhpExif
{
#Enables EXIF support in PHP
DependsOn = "[File]PhpIni"
SetScript = {
$content = Get-Content "C:\PHP\php.ini" | %{ if ($_ -match ";extension=php_mbstring.dll") { $_ -replace ";","" } else { $_ } }
if (!($content | ?{$_ -eq "extension=php_mbstring.dll"})) { $content += "extension=php_mbstring.dll" }
$content | %{ if ($_ -match ";extension=php_exif.dll") { $_ -replace ";","" } else { $_ } }
if (!($content | ?{$_ -eq "extension=php_exif.dll"})) { $content += "extension=php_exif.dll" }
Set-Content -Path "C:\PHP\php.ini" -Value $content
}
TestScript = {
$config1 = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_mbstring.dll"}
$config2 = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_exif.dll"}
if ($config1 -and $config2) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_mbstring.dll"}
$config += Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_exif.dll"}
return $config
}
}
Script PhpGd
{
#Enables GD support in PHP
DependsOn = "[File]PhpIni"
SetScript = {
$content = Get-Content "C:\PHP\php.ini" | %{ if ($_ -match ";extension=php_gd2.dll") { $_ -replace ";","" } else { $_ } }
if (!($content | ?{$_ -eq "extension=php_sqlite3.dll"})) { $content += "extension=php_gd2.dll" }
Set-Content -Path "C:\PHP\php.ini" -Value $content
}
TestScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_gd2.dll"}
if ($config) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\PHP\php.ini" | ?{$_ -eq "extension=php_gd2.dll"}
return $config
}
}
Environment PathPhp
{
#Sets PHP path environmental variable
DependsOn = "[Archive]PHP"
Ensure = "Present"
Name = "Path"
Value = ";C:\PHP"
Path = $true
}
Script PHPHandler
{
#Adds a handler for *.php to use PHP-CGI
DependsOn = "[Archive]PHP"
SetScript = { New-WebHandler -Name "PHP" -Path "*.php" -Verb "GET,POST" -Modules FastCgiModule -PSPath "IIS:\" -ScriptProcessor "C:\PHP\php-cgi.exe" -ResourceType "Either" }
TestScript = {
$handler = Get-WebHandler -Name "PHP" -PSPath "IIS:\" | ?{$_.path -eq "*.php" -and $_.verb -eq "GET,POST" -and $_.modules -eq "FastCgiModule" -and $_.scriptprocessor -eq "C:\PHP\php-cgi.exe" -and $_.resourcetype -eq "Either"}
if ($handler) { return $true }
else { return $false }
}
GetScript = {
$handler = Get-WebHandler -Name "PHP" -PSPath "IIS:\" | ?{$_.path -eq "*.php" -and $_.verb -eq "GET,POST" -and $_.modules -eq "FastCgiModule" -and $_.scriptprocessor -eq "C:\PHP\php-cgi.exe" -and $_.resourcetype -eq "Either"}
return $handler
}
}
Script PHPFastCgi
{
#Adds a FastCGI application for PHP-CGI
DependsOn = "[Archive]PHP"
SetScript = { Add-WebConfiguration "/system.webserver/fastcgi" -PSPath "IIS:\" -atIndex 0 -Value @{fullpath="C:\PHP\php-cgi.exe"} }
TestScript = {
$fastcgi = Get-WebConfiguration "/system.webserver/fastcgi" -PSPath "IIS:\" | select -expandproperty collection | ?{$_.fullpath -eq "C:\PHP\php-cgi.exe"}
if ($fastcgi) { return $true }
else { return $false }
}
GetScript = {
$fastcgi = Get-WebConfiguration "/system.webserver/fastcgi" -PSPath "IIS:\" | select -expandproperty collection | ?{$_.fullpath -eq "C:\PHP\php-cgi.exe"}
return $fastcgi
}
}
Script DefaultDocument
{
#Adds index.php as default document option on the default website
SetScript = { Add-WebConfiguration "/system.webserver/defaultdocument/files" -PSPath "IIS:\" -Location "Default Web Site" -atIndex 0 -Value @{value="index.php"} }
TestScript = {
$defaultdocument = Get-WebConfiguration "/system.webserver/defaultdocument/files" -PSPath "IIS:\" -Location "Default Web Site" | select -expandproperty collection | ?{$_.value -eq "index.php"}
if ($defaultdocument) { return $true }
else { return $false }
}
GetScript = {
$defaultdocument = Get-WebConfiguration "/system.webserver/defaultdocument/files" -PSPath "IIS:\" -Location "Default Web Site" | select -expandproperty collection | ?{$_.value -eq "index.php"}
return $defaultdocument
}
}
Script PydioFolders
{
#Creates /tmp/sessions folder for later use
DependsOn = "[File]PydioFiles"
SetScript = {
New-Item "C:\inetpub\wwwroot\Pydio\data\tmp\sessions" -ItemType "Directory"
}
TestScript = {
$folder = Test-Path "C:\inetpub\wwwroot\Pydio\data\tmp\sessions"
if ($folder) { return $true }
else { return $false }
}
GetScript = {
$folder = Test-Path "C:\inetpub\wwwroot\Pydio\data\tmp\sessions"
return $folder
}
}
Script PydioFolderPermissions
{
#Gives IIS_IUSRS (IIS) full access to data folder
DependsOn = "[Script]PydioFolders"
SetScript = {
$acl = (Get-Item "C:\inetpub\wwwroot\Pydio\data").GetAccessControl('Access')
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule("IIS_IUSRS", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.AddAccessRule($accessrule)
Set-Acl -ACLObject $acl "C:\inetpub\wwwroot\Pydio\data"
}
TestScript = {
$aclaccess = (Get-Acl "C:\inetpub\wwwroot\Pydio\data").access
$access = $aclaccess | ?{$_.identityreference -eq "BUILTIN\IIS_IUSRS" -and $_.filesystemrights -like "*FullControl*"}
if ($access) { return $true }
else { return $false }
}
GetScript = {
$aclaccess = (Get-Acl "C:\inetpub\wwwroot\Pydio\data").access
$access = $aclaccess | ?{$_.identityreference -eq "BUILTIN\IIS_IUSRS" -and $_.filesystemrights -like "*FullControl*"}
return $access
}
}
Script PydioConfigTmp
{
#Changes /tmp path from PHP default to C:\inetpub\wwwroot\Pydio\data\tmp
DependsOn = "[File]PydioFiles"
SetScript = {
$content = Get-Content "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" | %{ if ($_ -eq '//define("AJXP_TMP_DIR", AJXP_DATA_PATH."/tmp");') { $_ -replace "//","" } else { $_ } }
Set-Content -Path "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" -Value $content
}
TestScript = {
$config = Get-Content "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" | ?{$_ -eq 'define("AJXP_TMP_DIR", AJXP_DATA_PATH."/tmp");'}
if ($config) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" | ?{$_ -eq 'define("AJXP_TMP_DIR", AJXP_DATA_PATH."/tmp");'}
return $config
}
}
Script PydioConfigTmpSessions
{
#Changes /tmp/sessions path from PHP default to C:\inetpub\wwwroot\Pydio\data\tmp\sessions
DependsOn = "[File]PydioFiles"
SetScript = {
$content = Get-Content "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" | %{ if ($_ -eq '//$AJXP_INISET["session.save_path"] = AJXP_DATA_PATH."/tmp/sessions";') { $_ -replace "//","" } else { $_ } }
Set-Content -Path "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" -Value $content
}
TestScript = {
$config = Get-Content "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" | ?{$_ -eq '$AJXP_INISET["session.save_path"] = AJXP_DATA_PATH."/tmp/sessions";'}
if ($config) { return $true }
else { return $false }
}
GetScript = {
$config = Get-Content "C:\inetpub\wwwroot\Pydio\conf\bootstrap_conf.php" | ?{$_ -eq '$AJXP_INISET["session.save_path"] = AJXP_DATA_PATH."/tmp/sessions";'}
return $config
}
}
Script PydioConfigHiddenSegments
{
#Adds /data as a hidden segment, as per best practices
DependsOn = "[File]PydioFiles"
SetScript = { Add-WebConfiguration "/system.webserver/security/requestFiltering/hiddenSegments" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Value @{segment="data"} }
TestScript = {
$defaultdocument = Get-WebConfiguration "/system.webserver/security/requestFiltering/hiddenSegments" -PSPath "IIS:\" -Location "Default Web Site/Pydio" | select -expandproperty collection | ?{$_.segment -eq "data"}
if ($defaultdocument) { return $true }
else { return $false }
}
GetScript = {
$defaultdocument = Get-WebConfiguration "/system.webserver/security/requestFiltering/hiddenSegments" -PSPath "IIS:\" -Location "Default Web Site/Pydio" | select -expandproperty collection | ?{$_.segment -eq "data"}
return $defaultdocument
}
}
Script PydioRewriteWebDAV
{
#Adds rewrite rule to root web.config for WebDAV
DependsOn = "[Package]UrlRewrite"
SetScript = {
Add-WebConfigurationProperty "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Name "." -Value @{name='Pydio WebDAV';patternSyntax='ECMAScript';stopProcessing='True'}
Set-WebConfigurationProperty "/system.webserver/rewrite/rules/rule[@name='Pydio WebDAV']/match" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Name "." -Value @{url='^shares';ignoreCase='False'}
Add-WebConfiguration "/system.webserver/rewrite/rules/rule[@name='Pydio WebDAV']/conditions" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Value @{input='{REQUEST_FILENAME}';matchType='IsFile';ignoreCase='False';negate='True'}
Add-WebConfiguration "/system.webserver/rewrite/rules/rule[@name='Pydio WebDAV']/conditions" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Value @{input='{REQUEST_FILENAME}';matchType='IsDirectory';ignoreCase='False';negate='True'}
Set-WebConfigurationProperty "/system.webserver/rewrite/rules/rule[@name='Pydio WebDAV']/action" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Name "." -Value @{type='Rewrite';url='./dav.php'}
}
TestScript = {
$rule = Get-WebConfiguration "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio" | select -ExpandProperty collection | ?{$_.name -eq "Pydio WebDAV"}
if ($rule) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio" | select -ExpandProperty collection | ?{$_.name -eq "Pydio WebDAV"}
return $rule
}
}
Script PydioRewriteAPI
{
#Adds rewrite rule to root web.config for REST API
DependsOn = "[Package]UrlRewrite"
SetScript = {
Add-WebConfigurationProperty "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Name "." -Value @{name='Pydio API_REST';patternSyntax='ECMAScript';stopProcessing='True'}
Set-WebConfigurationProperty "/system.webserver/rewrite/rules/rule[@name='Pydio API_REST']/match" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Name "." -Value @{url='^api';ignoreCase='False'}
Set-WebConfigurationProperty "/system.webserver/rewrite/rules/rule[@name='Pydio API_REST']/action" -PSPath "IIS:\Sites\Default Web Site\Pydio" -Name "." -Value @{type='Rewrite';url='./rest.php'}
}
TestScript = {
$rule = Get-WebConfiguration "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio" | select -ExpandProperty collection | ?{$_.name -eq "Pydio API_REST"}
if ($rule) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio" | select -ExpandProperty collection | ?{$_.name -eq "Pydio API_REST"}
return $rule
}
}
Script PydioRewritePixlr
{
#Adds rewrite rule to Pixlr
DependsOn = "[Package]UrlRewrite"
SetScript = {
Add-WebConfigurationProperty "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.pixlr" -Name "." -Value @{name='PixlrSave';patternSyntax='ECMAScript';stopProcessing='True'}
Set-WebConfigurationProperty "/system.webserver/rewrite/rules/rule[@name='PixlrSave']/match" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.pixlr" -Name "." -Value @{url='^fake_save_pixlr_(.*).php$'}
Set-WebConfigurationProperty "/system.webserver/rewrite/rules/rule[@name='PixlrSave']/action" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.pixlr" -Name "." -Value @{type='Rewrite';url='fake_save_pixlr.php'}
}
TestScript = {
$rule = Get-WebConfiguration "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.pixlr" | select -ExpandProperty collection | ?{$_.name -eq "PixlrSave"}
if ($rule) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/rewrite/rules" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.pixlr" | select -ExpandProperty collection | ?{$_.name -eq "PixlrSave"}
return $rule
}
}
Script PydioDenyConf
{
#Adds deny rule to /conf/web.config for users
DependsOn = "[WindowsFeature]URLAuthorization"
SetScript = {
while ((Get-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\conf" -Name "." | select -ExpandProperty collection).count -ne 0) {
Remove-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\conf" -Name "." -AtIndex 0
}
Add-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\conf" -Name "." -Value @{accessType='Deny';users='*'}
}
TestScript = {
$rules = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\conf" | select -ExpandProperty collection
if ($rules.count -eq 1 -and (($rules | ?{$_.accesstype -eq "Deny" -and $_.users -eq "*"}).count -eq 1)) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\conf" | select -ExpandProperty collection | ?{$_.accesstype -eq "Deny" -and $_.users -eq "*"}
return $rule
}
}
Script PydioDenyData
{
#Adds deny rule to /data/web.config for users
DependsOn = "[WindowsFeature]URLAuthorization"
SetScript = {
while ((Get-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data" -Name "." | select -ExpandProperty collection).count -ne 0) {
Remove-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data" -Name "." -AtIndex 0
}
Add-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data" -Name "." -Value @{accessType='Deny';users='*'}
}
TestScript = {
$rules = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data" | select -ExpandProperty collection
if ($rules.count -eq 1 -and (($rules | ?{$_.accesstype -eq "Deny" -and $_.users -eq "*"}).count -eq 1)) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data" | select -ExpandProperty collection | ?{$_.accesstype -eq "Deny" -and $_.users -eq "*"}
return $rule
}
}
Script PydioDenyZoho
{
#Adds deny rule to /plugins/editor.zoho/agent/files/web.config for users
DependsOn = "[WindowsFeature]URLAuthorization"
SetScript = {
while ((Get-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.zoho\agent\files" -Name "." | select -ExpandProperty collection).count -ne 0) {
Remove-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.zoho\agent\files" -Name "." -AtIndex 0
}
Add-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.zoho\agent\files" -Name "." -Value @{accessType='Deny';users='*'}
}
TestScript = {
$rules = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.zoho\agent\files" | select -ExpandProperty collection
if ($rules.count -eq 1 -and (($rules | ?{$_.accesstype -eq "Deny" -and $_.users -eq "*"}).count -eq 1)) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\plugins\editor.zoho\agent\files" | select -ExpandProperty collection | ?{$_.accesstype -eq "Deny" -and $_.users -eq "*"}
return $rule
}
}
Script PydioAllowPublic
{
#Adds allow rule to /data/public/web.config for users
DependsOn = "[WindowsFeature]URLAuthorization"
SetScript = {
while ((Get-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" -Name "." | select -ExpandProperty collection).count -ne 0) {
Remove-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" -Name "." -AtIndex 0
}
Add-WebConfigurationProperty "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" -Name "." -Value @{accessType='Allow';users='*'}
}
TestScript = {
$rules = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" | select -ExpandProperty collection
if ($rules.count -eq 1 -and (($rules | ?{$_.accesstype -eq "Allow" -and $_.users -eq "*"}).count -eq 1)) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/security/authorization" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" | select -ExpandProperty collection | ?{$_.accesstype -eq "Allow" -and $_.users -eq "*"}
return $rule
}
}
Script PydioDenyPublicAjxp
{
#Adds request filter rule to /data/public/web.config to block access to .ajxp_
DependsOn = "[WindowsFeature]RequestFiltering"
SetScript = {
Add-WebConfigurationProperty "/system.webserver/security/requestfiltering/filteringrules" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" -Name "." -Value @{name='Pydio Public';scanUrl='True';scanQueryString='false'}
Set-WebConfigurationProperty "/system.webserver/security/requestfiltering/filteringrules/filteringrule[@name='Pydio Public']/denyStrings" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" -Name "." -Value @{string='.ajxp_'}
}
TestScript = {
$rule = Get-WebConfiguration "/system.webserver/security/requestfiltering/filteringrules" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" | select -ExpandProperty collection | ?{$_.name -eq "Pydio Public"}
if ($rule) { return $true }
else { return $false }
}
GetScript = {
$rule = Get-WebConfiguration "/system.webserver/security/requestfiltering/filteringrules" -PSPath "IIS:\Sites\Default Web Site\Pydio\data\public" | select -ExpandProperty collection | ?{$_.name -eq "Pydio Public"}
return $rule
}
}
}
}
#Gets local computer name
$servername = $env:computername
#Converts DSC to an MOF file
Pydio -MachineName $servername
#Applies MOF file to machine
$session = New-CimSession -ComputerName $servername -Authentication Kerberos
Start-DscConfiguration -Path .\Pydio -CimSession $session -Wait -Force
|
PowerShellCorpus/GithubGist/RhysC_849264_raw_9cc2b1dc1385ce6ffa5586ba1db89a1feed4f585_VersionTest.ps1
|
RhysC_849264_raw_9cc2b1dc1385ce6ffa5586ba1db89a1feed4f585_VersionTest.ps1
|
#Version checks
#Version type
function Test-VersionIsGreaterThanOrEqualTo()
{
param ([string] $versionA, [string] $versionB)
"versionA $versionA"
"versionB $versionB"
$version1 = New-Version $versionA
$version2 = New-Version $versionb
if($version1.Major -lt $version2.Major)
{
Write-Verbose "Major is less than ($version1 vs $version2)"
return $false
}
if($version1.Minor -lt $version2.Minor)
{
Write-Verbose "Minor is less than ($version1 vs $version2)"
return $false
}
if($version1.Release -lt $version2.Release)
{
Write-Verbose "Release is less than ($version1 vs $version2)"
return $false
}
if($version1.Build -lt $version2.Build)
{
Write-Verbose "Build is less than ($version1 vs $version2)"
return $false
}
Write-Verbose "All are equal or greater than"
return $true
}
function Test-VersionIsEqualTo()
{
param ([string] $versionA, [string] $versionB)
"versionA $versionA"
"versionB $versionB"
$version1 = New-Version $versionA
$version2 = New-Version $versionb
if($version1.Major -ne $version2.Major)
{
Write-Verbose "Major is not equal ($version1 vs $version2)"
return $false
}
if($version1.Minor -ne $version2.Minor)
{
Write-Verbose "Minor is not equal ($version1 vs $version2)"
return $false
}
if($version1.Release -ne $version2.Release)
{
Write-Verbose "Release is not equal ($version1 vs $version2)"
return $false
}
if($version1.Build -ne $version2.Build)
{
Write-Verbose "Build is not equal ($version1 vs $version2)"
return $false
}
Write-Verbose "All properties are equal"
return $true
}
function New-Version()
{
param ([string] $version)
$versionArray = $version.Replace("v","").Split(".")
if($versionArray.Count -lt 1)
{
throw "Version should be in the format [Major].[Minor].[Release].[Build] eg 1.2.3.123 (input provided was : $version)"
}
if($versionArray.Count -ne 4)
{
Write-Warning "Version should be in the format [Major].[Minor].[Release].[Build] eg 1.2.3.123 (input provided was : $version)"
if($versionArray.Count -lt 4)
{
$newArray = @(0,0,0,0)
$index = 0
while($index -lt $versionArray.Count)
{
$newArray[$index] = $versionArray[$index];
$index = $index+1;
}
$versionArray = $newArray;
}
}
$Major = [int]$versionArray[0]
$Minor = [int]$versionArray[1]
$Release = [int]$versionArray[2]
$Build = [int]$versionArray[3]
$versionObj = New-Object PSObject
$versionObj | add-member Noteproperty Major $Major
$versionObj | add-member Noteproperty Minor $Minor
$versionObj | add-member Noteproperty Release $Release
$versionObj | add-member Noteproperty Build $Build
return $versionObj;
}
#Tests
if((Test-VersionIsGreaterThanOrEqualTo "0.0.0.1" "0.0.0.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "1.0.0.0" "1.0.0.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "1.0.0.1" "1.0.0.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "1.0.1.0" "1.0.0.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "1.1.0.0" "1.0.0.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "1.0.0.0" "1.0.0.1") -eq $true)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "1.0.0.0" "1.0.1.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "1.0.0.0" "1.1.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsGreaterThanOrEqualTo "0.0.0.0" "1.0.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.0.0" "1.0.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.0.0" "0.1.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.0.0" "0.0.1.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.0.0" "0.0.0.1") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "1.0.0.0" "0.0.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.1.0.0" "0.0.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.1.0" "0.0.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.0.1" "0.0.0.0") -eq $true)
{
throw "fail"
}
if((Test-VersionIsEqualTo "1.0.0.0" "1.0.0.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.1.0.0" "0.1.0.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.1.0" "0.0.1.0") -eq $false)
{
throw "fail"
}
if((Test-VersionIsEqualTo "0.0.0.1" "0.0.0.1") -eq $false)
{
throw "fail"
}
|
PowerShellCorpus/GithubGist/sunnyone_8071456_raw_92ca9d1a45ef154baf32d6fbeae833ad42c87d89_gistfile1.ps1
|
sunnyone_8071456_raw_92ca9d1a45ef154baf32d6fbeae833ad42c87d89_gistfile1.ps1
|
function Get-MyService {
Get-Service | Select-Object -First 5 | Format-List
}
function Get-MyProcess {
Get-Process | Select-Object -First 5 | Format-List
}
|
PowerShellCorpus/GithubGist/pranavkm_4287384_raw_ad11570f0f3a6ff838bfd29ffb8b6484b899b52a_gistfile1.ps1
|
pranavkm_4287384_raw_ad11570f0f3a6ff838bfd29ffb8b6484b899b52a_gistfile1.ps1
|
function Get-ProjectFiles {
Process {
if ($_.Kind -eq "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}" -or $_.Kind -eq "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}") {
$_.ProjectItems | Get-ProjectFiles
}
else {
$_
}
}
}
function Get-ProjectFilePath {
param(
$file
)
($.file.Properties | Where { $_.Name -eq "FullPath" }).Value
}
function Get-RazorFiles {
param(
[parameter(ValueFromPipelineByPropertyName = $true)]
[string]$ProjectName
)
(Resolve-ProjectName $ProjectName).ProjectItems | Get-ProjectFiles | Where {
$_.Name.EndsWith('.cshtml') -and !(Get-ChildItem (Get-ProjectFilePath $_)).IsReadOnly
}
}
function Redo-RazorGenerator {
param(
[parameter(ValueFromPipelineByPropertyName = $true)]
[string]$ProjectName
)
Process {
Get-RazorFiles $ProjectName | % {
if ($_.Properties.Item("CustomTool")) {
$_.Object.RunCustomTool()
}
}
}
}
|
PowerShellCorpus/GithubGist/posaunehm_3753744_raw_c75f52409a601c092ddc4b8bc7206ee2378eeafc_gistfile1.ps1
|
posaunehm_3753744_raw_c75f52409a601c092ddc4b8bc7206ee2378eeafc_gistfile1.ps1
|
Get-Clipboard -Image | %{$_.Save((Get-Date -Format "MMddhhmmss") + ".bmp")}
|
PowerShellCorpus/GithubGist/seraphy_6399082_raw_835d07663590a8a612b70cb5879f37548d95cef3_ConcatTextFiles.ps1
|
seraphy_6399082_raw_835d07663590a8a612b70cb5879f37548d95cef3_ConcatTextFiles.ps1
|
# 第一引数として、対象となるファイルまたは親ディレクトリを指定する.
# 省略時はカレントディレクトリ以下のすべてのファイルを対象とする.
param($searchPath = $(pwd))
# 指定したフォルダ以下の全てのファイルを取得する.
# (ファイルが指定された場合はファイル自身を返す)
function GetFilesRecurse([string] $path)
{
Get-ChildItem $path -Recurse |
Where-Object -FilterScript {
# ディレクトリ以外のみ (ディレクトリのビットマスク値は16)
($_.Attributes -band 16) -eq 0
}
}
# ファイル名とファイルの内容を出力するフィルタ
function PutFileContents
{
process {
[System.IO.FileInfo] $file = $_;
Write-Output ">>>>>>>>>>>>>>>>>>>>>>>";
Write-Output "[$file]";
Write-Output "";
Get-Content $file.FullName;
Write-Output "<<<<<<<<<<<<<<<<<<<<<<<";
Write-Output "";
Write-Output "";
}
}
GetFilesRecurse $searchPath | PutFileContents
|
PowerShellCorpus/GithubGist/angel-vladov_9482676_raw_1d590ce6f456eea37503ac32aca4f28e3f0bac5c_powershell-net.ps1
|
angel-vladov_9482676_raw_1d590ce6f456eea37503ac32aca4f28e3f0bac5c_powershell-net.ps1
|
function Read-HtmlPage {
param ([Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)][String] $Uri)
# Invoke-WebRequest and Invoke-RestMethod can't work properly with UTF-8 Response so we need to do things this way.
[Net.HttpWebRequest]$WebRequest = [Net.WebRequest]::Create($Uri)
[Net.HttpWebResponse]$WebResponse = $WebRequest.GetResponse()
$Reader = New-Object IO.StreamReader($WebResponse.GetResponseStream())
$Response = $Reader.ReadToEnd()
$Reader.Close()
# Create the document class
[mshtml.HTMLDocumentClass] $Doc = New-Object -com "HTMLFILE"
$Doc.IHTMLDocument2_write($Response)
# Returns a HTMLDocumentClass instance just like Invoke-WebRequest ParsedHtml
$Doc
}
|
PowerShellCorpus/GithubGist/snowe2010_8178631_raw_8fc4fc0ad0aefcdde59113c422ca45d857eb6ed5_box40.ps1
|
snowe2010_8178631_raw_8fc4fc0ad0aefcdde59113c422ca45d857eb6ed5_box40.ps1
|
Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions
Enable-RemoteDesktop
cinst GoogleChrome
cinst javaruntime
cinst firefox
cinst ccleaner
cinst skype
cinst dropbox
cinst windirstat
cinst launchy
cinst utorrent
cinst sumatrapdf
cinst steam
cinst mousewithoutborders
cinst teracopy
cinst everything
cinst f.lux
cinst markdownpad2
cinst lastpass
cinst mpc-hc
cinst cutepdf
cinst malwarebytes
cinst recuva
cinst listary
cinst powergui
cinst poshgit
cinst consolez
cinst gow
cinst ansicon
cinst ruby
cinst ruby -version 1.9.3.48400
cinst putty
cinst sysinternals
cinst git
cinst 7zip
cinst nodejs
cinst winscp
cinst sublimetext3
cinst sublimetext3.packagecontrol
cinst dotpeek
|
PowerShellCorpus/GithubGist/rhysparry_1673670_raw_325fa0c6e63a28c2870f9b1a826f25c730e290d4_GetMoreMemoryThanVisualStudio.ps1
|
rhysparry_1673670_raw_325fa0c6e63a28c2870f9b1a826f25c730e290d4_GetMoreMemoryThanVisualStudio.ps1
|
function Get-MoreMemoryThanVisualStudio()
{
$d = (Get-Process devenv | Measure-Object -Sum PrivateMemorySize64);
Get-Process | Where-Object {$_.PrivateMemorySize64 -gt $d.Sum}
}
|
PowerShellCorpus/GithubGist/siggibjarna_0da65bd0d3f2b82d3752_raw_6001e65e02a1c31dc74cf1c72a737908434da3c8_powerssh.ps1
|
siggibjarna_0da65bd0d3f2b82d3752_raw_6001e65e02a1c31dc74cf1c72a737908434da3c8_powerssh.ps1
|
# Script Name: powerssh
# Version: 1.0.0 (24. June, 2014)
# Author: Sveinn Steinarsson
# Description: Use Powershell to connect to a remote server via SSH and run a shell script/command
# Prerequisite:
# plink.exe in script path (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html)
# Examples:
# With key file (*.ppk) and script file
# .\powerssh.ps1 -server hostname -login username -key keyfile.ppk -script task.sh
# With key file and command
# .\powerssh.ps1 -server hostname -login username -key keyfile.ppk -cmd "ls; pwd"
# With password and no output
# .\powerssh.ps1 -server hostname -login username -pw password -quiet -script task.sh
Param (
[string]$server = $(Throw "Please provide a server hostname/ip"),
[string]$login = $(Throw "Please provide a login username"),
[string]$key,
[string]$pw,
[string]$script,
[string]$cmd,
[string]$log = "powerssh.log",
[switch]$quiet = $false,
[switch]$noBatch = $false,
[switch]$agentForwarding = $true,
[switch]$verbose = $false,
[switch]$acceptHostKey = $true # For convenient. Make sure the server is the computer you think it is.
)
$plinkPath = Join-Path -Path $PSScriptRoot -Childpath "Plink.exe"
if (-not (Test-Path $plinkPath)){
Write-Host "Missing Plink.exe in script path. Please download it from http://the.earth.li/~sgtatham/putty/latest/x86/plink.exe"
exit 1
}
if ($key -eq "" -and $pw -eq "") {
Write-Host "You must supply either a password or key file."
exit 1
}
if ($script -eq "" -and $cmd -eq "") {
Write-Host "You must supply either a shell script file or command."
exit 1
}
if ($key -ne "" -and $pw -ne "") {
Write-Host "Notice: Only password or key file is required. Using key file."
}
if ($script -ne "" -and $cmd -ne "") {
Write-Host "Notice: Only script file or command is required. Using script file."
}
if ($acceptHostKey -eq $true) {
$command = "echo Y|" + $plinkPath
} else {
$command = $plinkPath
}
$command += " -ssh " + $server + " -l " + $login
if ($key -ne "") {
$command += " -i " + $key
} else {
$command += " -pw " + $pw
}
if ($noBatch -ne $true) {
$command += " -batch"
}
if ($agentForwarding -eq $true) {
$command += " -a"
}
if ($verbose -eq $true) {
$command += " -v"
}
if ($script -ne "") {
$command += " -m " + $script
} else {
$command += ' "' + $cmd + '"'
}
if ($quiet -eq $true) {
$command += " > " +$log
} elseif ($log -ne "") {
$command += " | tee-object -filepath " +$log
}
if ($verbose -eq $true) {
Write-Host "Command to Plink:"
Write-Host $command # Write out the command for debugging
Write-Host ""
}
Invoke-Expression $command
exit 0
|
PowerShellCorpus/GithubGist/pnowosie_5231580_raw_bf8d070a56f4b9a34b88a5c2029a65a93977c615_gistfile1.ps1
|
pnowosie_5231580_raw_bf8d070a56f4b9a34b88a5c2029a65a93977c615_gistfile1.ps1
|
# Script creates local git repository linked with bare "remote" copy in dropbox directory,
# so you gain cloud backups ater pushing changes.
# Add following function to you PS Profile (don't forget to restart the shell)
#-----------------------------------------------------------------
# Git-Init
#-----------------------------------------------------------------
$boxRepoPath = '{PATH_TO_DROPBOX_DIR where repos will be stored}'
function Git-Init($repoName $(throw "Parameter repoName is required.")) { # run inside directory where you want working copy to put
# TODO:
## if not repoName : show_usage_and_break
## if repo exist : show_usage_and_break
## if repo is path : extract filename
Push-Location
cd "$boxRepoPath"
mkdir $repoName
cd $repoName
$remoteRepo = pwd
git init --bare
Pop-Location ##TODO: if given repoName is path, go to baseDir(repoName) and clone repo there
git clone "$remoteRepo"
# check that above command succeds and new directory is created
cd $repoName
# Make initial commit and push to link branches in both repos
New-Item -Type file .gitignore
New-Item -Type file README.md
git add .
git commit -am "Repository bootstrap"
git push -u origin master
}
|
PowerShellCorpus/GithubGist/lantrix_904c7703b4c66c271149_raw_59b4e7c8d55773bfd827ee6b9e1cf1f65be79908_vol_to_del.ps1
|
lantrix_904c7703b4c66c271149_raw_59b4e7c8d55773bfd827ee6b9e1cf1f65be79908_vol_to_del.ps1
|
#method 1
$f = New-Object Amazon.EC2.Model.Filter
$f.Name = "attachment.instance-id"
$f.Value.Add("i-a005239e")
$voltodel = Get-EC2Volume -Filters $f
#method 2
$voltodel = Get-EC2Volume -Filters @{Name="attachment.instance-id"; Value="i-a005239e"}
|
PowerShellCorpus/GithubGist/PatrickMcDonald_531c5ca15de82787d9be_raw_817ec5cb36e0640028e8f9743be1ad3275e47a15_ps-ad.ps1
|
PatrickMcDonald_531c5ca15de82787d9be_raw_817ec5cb36e0640028e8f9743be1ad3275e47a15_ps-ad.ps1
|
Import-Module ActiveDirectory
# List members of a group
Get-ADGroupMember "Domain Admins" -recursive | Select-Object name
# list group memberships for user
Get-ADPrincipalGroupMembership "username" | Select-Object name
|
PowerShellCorpus/GithubGist/jonforums_5087235_raw_108177da36e54eb34656431dc59280e2fc7c36a8_build_libffi.ps1
|
jonforums_5087235_raw_108177da36e54eb34656431dc59280e2fc7c36a8_build_libffi.ps1
|
#requires -version 2.0
# Author: Jon Maken
# License: 3-clause BSD
# Revision: 2013-03-11 00:37:25 -0600
#
# TODO:
# - extract generics into a downloadable utils helper module
# - add proper try-catch-finally error handling
# - support x86 and x64 builds
param(
[parameter(Mandatory=$true,
Position=0,
HelpMessage='libffi version to build (eg - 3.0.12)')]
[alias('i')]
[validateset('3.0.10','3.0.11','3.0.12')]
[string] $ffi_ver,
[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
$libname = 'libffi'
$source = "${libname}-${ffi_ver}.tar.gz"
$repo_root = "ftp://sourceware.org/pub/${libname}/"
$archive = "${repo_root}${source}"
$hash_uri = "https://raw.github.com/jonforums/poshlab/master/hashery/${libname}.md5"
# download and verify
# TODO implement progress bar when extracted to util helper module
if(-not (Test-Path $source)) {
try {
Write-Host "[INFO] downloading ${archive}" -foregroundcolor $msg_color
[System.Net.FtpWebRequest]$request = [System.Net.WebRequest]::Create($archive)
$request.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$request.UseBinary = $true
$request.UsePassive = $true
$response = $request.GetResponse()
$response_stream = $response.GetResponseStream()
$fs = New-Object System.IO.FileStream "$PWD/$source", 'Create', 'Write'
[byte[]] $buffer = New-Object byte[] 4096
do {
$count = $response_stream.Read($buffer, 0, $buffer.Length)
$fs.Write($buffer, 0, $count)
} while ($count -gt 0) # EOS when Read returns 0 bytes
}
catch {
throw "[ERROR] Oops trying to download"
}
finally {
if ($fs) { $fs.Flush(); $fs.Close() }
if ($response_stream) { $response_stream.Close() }
if ($response) { $response.Close() }
}
}
# download hash data and validate downloaded source archive
Write-Host "[INFO] verifying $source" -foregroundcolor $msg_color
$client = New-Object System.Net.WebClient
$hash = ConvertFrom-StringData $client.DownloadString($hash_uri)
try {
$hasher = New-Object System.Security.Cryptography.MD5Cng
$fs = New-Object System.IO.FileStream "$PWD\$source", 'Open', 'Read'
$test_hash = [BitConverter]::ToString($hasher.ComputeHash($fs)).Replace('-','').ToLower()
} finally {
$fs.Close()
}
if ($test_hash -ne $hash[$ffi_ver].ToLower()) {
Write-Host "[ERROR] $source validation failed, exiting" -foregroundcolor red
break
}
# extract
Write-Host "[INFO] extracting $source" -foregroundcolor $msg_color
$tar_file = "$($source.Substring(0, $source.LastIndexOf('-')))*.tar"
(& "$7ZA" "x" $source) -and (& "$7ZA" "x" $tar_file) -and (rm $tar_file) | Out-Null
# patch, configure, build, archive
Push-Location "${libname}-${ffi_ver}"
# activate toolchain
Write-Host "[INFO] activating toolchain" -foregroundcolor $msg_color
. "$DEVKIT/devkitvars.ps1" | Out-Null
# configure
Write-Host "[INFO] configuring ${libname}-${ffi_ver}" -foregroundcolor $msg_color
$install_dir = "$($PWD.ToString().Replace('\','/'))/my_install"
sh -c "./configure --prefix=${install_dir}" | Out-Null
# build
Write-Host "[INFO] building ${libname}-${ffi_ver}" -foregroundcolor $msg_color
sh -c "make" | Out-Null
# install
sh -c "make install" | Out-Null
# post-install patch
Push-Location "$install_dir"
mv $(resolve-path lib\libffi-*\include) $PWD
rm $(resolve-path lib\libffi-*)
Pop-Location
# archive
Push-Location "$install_dir"
Write-Host "[INFO] creating binary archive for ${libname}-${ffi_ver}" -foregroundcolor $msg_color
$bin_archive = "${libname}-${ffi_ver}-x86-windows-bin.7z"
& "$7ZA" "a" "-mx=9" "-r" $bin_archive "*" | Out-Null
Pop-Location
Pop-Location
# hoist binary archive and cleanup
Write-Host "[INFO] cleaning up" -foregroundcolor $msg_color
mv "$install_dir/$bin_archive" "$PWD"
rm -recurse -force "${libname}-${ffi_ver}"
|
PowerShellCorpus/GithubGist/pieterjd_6280119_raw_8c9cf6246088d46bf6c92b1efe853219aa461aa7_printFiles.ps1
|
pieterjd_6280119_raw_8c9cf6246088d46bf6c92b1efe853219aa461aa7_printFiles.ps1
|
gci -Include *.doc,*.docx -Recurse | %{Start-Process -Verb Print -FilePath $_.fullname}
|
PowerShellCorpus/GithubGist/jonforums_5167198_raw_feaa175b525c8dd28ed1e817fe94f5663a833c1a_build_minised.ps1
|
jonforums_5167198_raw_feaa175b525c8dd28ed1e817fe94f5663a833c1a_build_minised.ps1
|
#requires -version 2.0
# Author: Jon Maken
# License: 3-clause BSD
# Revision: 2013-03-14 23:17:01 -0600
#
# TODO:
# - extract generics into a downloadable utils helper module
# - add proper try-catch-finally error handling
param(
[parameter(Mandatory=$true,
Position=0,
HelpMessage='minised version to build (eg - 1.14)')]
[validateset('1.14')]
[alias('v')]
[string] $version,
[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
$libname = 'minised'
$source = "${libname}-${version}.tar.gz"
$source_dir = "${libname}-${version}"
$repo_root = "http://dl.exactcode.de/oss/${libname}/"
$archive = "${repo_root}${source}"
$hash_uri = "https://raw.github.com/jonforums/poshlab/master/hashery/${libname}.sha1"
# download source archive
if(-not (Test-Path $source)) {
Import-Module BitsTransfer
Write-Host "[INFO] downloading ${archive}" -foregroundcolor $msg_color
Start-BitsTransfer $archive "$PWD\$source"
}
# download hash data and validate source archive
Write-Host "[INFO] validating $source" -foregroundcolor $msg_color
$client = New-Object System.Net.WebClient
$hash = ConvertFrom-StringData $client.DownloadString($hash_uri)
try {
$hasher = New-Object System.Security.Cryptography.SHA1Cng
$fs = New-Object System.IO.FileStream "$PWD\$source", 'Open', 'Read'
$test_hash = [BitConverter]::ToString($hasher.ComputeHash($fs)).Replace('-','').ToLower()
} finally {
$fs.Close()
}
if ($test_hash -ne $hash[$version].ToLower()) {
Write-Host "[ERROR] $source validation failed, exiting" -foregroundcolor red
break
}
# extract
Write-Host "[INFO] extracting $source" -foregroundcolor $msg_color
$tar_file = "$($source.Substring(0, $source.LastIndexOf('-')))*.tar"
(& "$7ZA" "x" $source) -and (& "$7ZA" "x" $tar_file) -and (rm $tar_file) | Out-Null
# patch, configure, build, archive
Push-Location "${source_dir}"
# activate toolchain
Write-Host "[INFO] activating toolchain" -foregroundcolor $msg_color
. "$DEVKIT/devkitvars.ps1" | Out-Null
# configure
Write-Host "[INFO] configuring ${source_dir}" -foregroundcolor $msg_color
$install_dir = "$($PWD.ToString().Replace('\','/'))/my_install"
mkdir "$install_dir" | Out-Null
# build
Write-Host "[INFO] building ${source_dir}" -foregroundcolor $msg_color
sh -c "make CC=gcc" | Out-Null
# install
strip -s minised.exe | Out-Null
cp minised.exe, README, LICENSE -destination "$install_dir" | Out-Null
# archive
Push-Location "$install_dir"
Write-Host "[INFO] creating binary archive for ${source_dir}" -foregroundcolor $msg_color
$bin_archive = "${source_dir}-x86-windows-bin.7z"
& "$7ZA" "a" "-mx=9" "-r" $bin_archive "*" | Out-Null
Pop-Location
Pop-Location
# hoist binary archive and cleanup
Write-Host "[INFO] cleaning up" -foregroundcolor $msg_color
mv "$install_dir/$bin_archive" "$PWD" -force
rm "${source_dir}" -recurse -force
|
PowerShellCorpus/GithubGist/tkmtmkt_8746621_raw_0481ad6415d5596055ce1736840d1fa5b932b168_CreatePackageInfo.ps1
|
tkmtmkt_8746621_raw_0481ad6415d5596055ce1736840d1fa5b932b168_CreatePackageInfo.ps1
|
<#
.SYNOPSIS
パッケージ情報ファイルを作成します。
#>
ls -dir -r | select -skip 3 | %{
$dir = $_.fullname
$packageInfoFile = "$dir\package-info.java"
$packageName = (resolve-path $dir -rel).substring(2).replace('\','.')
if (test-path $packageInfoFile) {
$result = " "
} else {
$content = @"
package $packageName;
/**
* TODO: パッケージの説明を記入する
* @since 1.0
*/
"@ -split "`r*`n"
[System.IO.File]::WriteAllLines($packageInfoFile, $content)
$result = "new "
}
write-host "$result $(resolve-path $packageInfoFile -rel)"
}
# vim: set ts=4 sw=4 et:
|
PowerShellCorpus/GithubGist/smasterson_9140983_raw_c854457b10ebe7adbadbc4c5bfa16481dccf1efa_VeeamUpdateJobs.ps1
|
smasterson_9140983_raw_c854457b10ebe7adbadbc4c5bfa16481dccf1efa_VeeamUpdateJobs.ps1
|
<#
.SYNOPSIS
Update Veeam Backup Job Details
.DESCRIPTION
This script will adjust settings across all Veeam backup jobs.
Individual settings can be added/removed as needed.
.NOTES
Author: Shawn Masterson
Created: December 2013
Version: 1.0
REQUIREMENTS
Intended to be run direct on the VBR server with Veeam Powershell addin installed
Powershell v2 or better
Veeam Backup and Replication v7
.EXAMPLE
.\VeeamUpdateJobs.ps1
.DISCLAIMER:
There is very little error catching built into this script
USE AT YOUR OWN RISK!
#>
#--------------------------------------------------------------------
# Parameters
#--------------------------------------------------------------------
# User Defined Variables
# Enable deduplication ($true/$false)
$dedupe = $true
# Compression Level (Auto=1,None=0,Dedupe=4,Optimal=5,High=6,Extreme=9)
$complvl = 5
# Block Size (KbBlockSize256/WAN Target=0,KbBlockSize512/LAN Target=1,KbBlockSize1024/Local Target=3,
# KbBlockSize2048=4,KbBlockSize4096=5,KbBlockSize8192/Local Target(16TB+ Files)=6,Auto=7)
$blocksize = 1
# Enable Integrity Check
$integcheck = $true
# Remove deleted VMs ($true/$false)
$removedeleted = $true
# Retain Deleted VMs (Days)
$retaindeleted = 14
#--------------------------------------------------------------------
# Static Variables
$scriptName = "VeeamUpdateJobs"
$scriptVer = "1.0"
$starttime = Get-Date -uformat "%m-%d-%Y %I:%M:%S"
#--------------------------------------------------------------------
# Load Snap-ins
# Add Veeam snap-in if required
If ((Get-PSSnapin -Name VeeamPSSnapin -ErrorAction SilentlyContinue) -eq $null) {add-pssnapin VeeamPSSnapin}
#--------------------------------------------------------------------
# Functions
#--------------------------------------------------------------------
# Main Procedures
Clear-Host
Write-Host "********************************************************************************"
Write-Host "$scriptName`tVer:$scriptVer`t`t`tStart Time:`t$starttime"
Write-Host "********************************************************************************`n"
# Get Backup Jobs
$jobs = Get-VBRJob | ?{$_.JobType -eq "Backup"}
# Loop through each job updating options
foreach ($job in $jobs) {
Write-Host "Setting job options on"$job.Name -ForegroundColor Yellow
$job | Set-VBRJobAdvancedStorageOptions -EnableDeduplication $dedupe -CompressionLevel $complvl -StorageBlockSize $blocksize | Out-Null
$job | Set-VBRJobAdvancedOptions -EnableIntegrityChecks $integcheck -RetainDays $retaindeleted | Out-Null
$jOptions = Get-VBRJobOptions $job
$jOptions.BackupStorageOptions.EnableDeletedVmDataRetention = $removedeleted
$job | Set-VBRJobOptions -Options $jOptions | Out-Null
}
#--------------------------------------------------------------------
# Outputs
Write-Host "`nProcessing Complete" -ForegroundColor Yellow
$finishtime = Get-Date -uformat "%m-%d-%Y %I:%M:%S"
Write-Host "`n`n"
Write-Host "********************************************************************************"
Write-Host "$scriptName`t`t`t`tFinish Time:`t$finishtime"
Write-Host "********************************************************************************"
# Prompt to exit script - This leaves PS window open when run via right-click
Write-Host "`n`n"
Write-Host "Press any key to continue ..." -foregroundcolor Gray
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
PowerShellCorpus/GithubGist/dfch_d5990fdb391fe1b84b76_raw_2c45aebbff6937cc16b673ab2b94657251aed7dd_Convert-Currency.ps1
|
dfch_d5990fdb391fe1b84b76_raw_2c45aebbff6937cc16b673ab2b94657251aed7dd_Convert-Currency.ps1
|
# http://d-fens.ch/2014/01/07/nobrainer-powershell-currency-converter/
Param (
[Parameter(Mandatory = $true, Position = 0)]
[string] $From
,
[Parameter(Mandatory = $true, Position = 1)]
[string] $To
,
[Parameter(Mandatory = $false, Position = 2)]
[Alias("Amount")]
[double] $Value = 1
,
[Parameter(Mandatory = $false, Position = 3)]
[Alias("When")]
[DateTime] $Date = [datetime]::Now
) # Param
$UrlTemplate = 'http://www.oanda.com/currency/converter/update?base_currency_0={0}"e_currency={1}&end_date={2}&view=details&id=1&action=C&';
[Uri] $Url = $UrlTemplate -f $From, $To, $Date.ToString('yyyy-MM-dd');
$r = Invoke-RestMethod -Uri $Url;
if($PSBoundParameters.ContainsKey('Value')) {
($r.data.bid_ask_data | gm -Type Properties).Name | % { $r.data.bid_ask_data.$_ *= $Value; };
for($c = 0; $c -lt $r.data.chart_data.Count; $c++) { $r.data.chart_data[$c][-1] *= $Value; };
} # if
$Currency = [Ordered] @{};
($r.data.bid_ask_data | gm -Type Properties).Name | % { $Currency.Add($_, $r.data.bid_ask_data.$_); };
# for($c = 0; $c -lt $r.data.chart_data.Count; $c++) {
# $dt = New-Object Datetime($r.data.chart_data[$c][0], $r.data.chart_data[$c][1], $r.data.chart_data[$c][2]);
# $Currency.Add($dt.ToString('yyyy-MM-dd'), $r.data.chart_data[$c][-1]);
# } # for
return $Currency;
|
PowerShellCorpus/GithubGist/jstangroome_2505593_raw_fadd181c115f6b7373118651a3106181bc840a1e_Positional.ps1
|
jstangroome_2505593_raw_fadd181c115f6b7373118651a3106181bc840a1e_Positional.ps1
|
function Get-Thing {
[CmdletBinding(DefaultParameterSetName='Default')]
param (
[Parameter(Mandatory=$true, ParameterSetName='Default', Position=0)]
$Default,
[Parameter(Mandatory=$true, ParameterSetName='Alternate')]
#[Parameter(Mandatory=$true, ParameterSetName='Alternate', Position=1)]
$Alternate,
[Parameter(Position=10)]
$Positional
)
Write-Output $PSBoundParameters
}
Get-Thing -?
#Get-Thing foo bar
#Get-Thing -Alternate foo bar
<#
With no Position value specified on the Alternate parameter, the syntax has the Alternate parameter in the wrong position:
Get-Thing [-Default] <Object> [[-Positional] <Object>] [<CommonParameters>]
Get-Thing [[-Positional] <Object>] -Alternate <Object> [<CommonParameters>]
With the Position value specified on the Altermate parameter, the syntax suggests the user can omit "-Alternate" when calling:
Get-Thing [-Default] <Object> [[-Positional] <Object>] [<CommonParameters>]
Get-Thing [-Alternate] <Object> [[-Positional] <Object>] [<CommonParameters>]
#>
|
PowerShellCorpus/GithubGist/ziqbalbh_7956710_raw_1723dabadf540a0e2f495766ff7b5a3e22b660ac_csv-split-trim.ps1
|
ziqbalbh_7956710_raw_1723dabadf540a0e2f495766ff7b5a3e22b660ac_csv-split-trim.ps1
|
$CSVData = @("One , Two , Three ")
#just split
$Data = $CSVData -split (",")
#first way of split and trim
$Data = $CSVData -split ',' | foreach {$_.Trim()}
#second way of split and trim
$CSVData.Split(",").Trim()
#third way of split and trim using regular expression
$Data = $CSVData -split '\s*,\s*'
|
PowerShellCorpus/GithubGist/kylesonaty_b35412907cca45754d8a_raw_5fe869b3532afc26198ef1eb263ccd3879fc8e79_gistfile1.ps1
|
kylesonaty_b35412907cca45754d8a_raw_5fe869b3532afc26198ef1eb263ccd3879fc8e79_gistfile1.ps1
|
param (
[string]$subscription = "Pay-As-You-Go",
[string]$service = $(throw "-service is required."),
[string]$storage = $(throw "-storage is required."),
[string]$slot = "staging", #staging or production
[string]$projectName = $(throw, "-projectName is required."),
[string]$buildConfig = $(throw, "-buildConfig is required."),
[string]$cloudConfig = "Cloud")
$package = "$projectName\bin\$buildConfig\app.publish\$projectName.cspkg"
$configuration = "$projectName\bin\$buildConfig\app.publish\ServiceConfiguration.$cloudConfig.cscfg"
$timeStampFormat = "g"
$deploymentLabel = "ContinuousDeploy to $service v%build.number%"
Write-Output "Running Azure Imports"
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\ServiceManagement\Azure\*.psd1"
Import-AzurePublishSettingsFile "C:\TeamCity\Azure\Pay-As-You-Go.publishsettings"
Set-AzureSubscription $subscription -CurrentStorageAccountName $storage
function Publish(){
$deployment = Get-AzureDeployment -ServiceName $service -Slot $slot -ErrorVariable a -ErrorAction silentlycontinue
if ($a[0] -ne $null) {
Write-Output "$(Get-Date -f $timeStampFormat) - No deployment is detected. Creating a new deployment. "
}
if ($deployment.Name -ne $null) {
#Update deployment inplace (usually faster, cheaper, won't destroy VIP)
Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment."
UpgradeDeployment
} else {
CreateNewDeployment
}
}
function CreateNewDeployment()
{
write-progress -id 3 -activity "Creating New Deployment" -Status "In progress"
Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: In progress"
$opstat = New-AzureDeployment -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service
$completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot
$completeDeploymentID = $completeDeployment.deploymentid
write-progress -id 3 -activity "Creating New Deployment" -completed -Status "Complete"
Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: Complete, Deployment ID: $completeDeploymentID"
}
function UpgradeDeployment()
{
write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress"
Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: In progress"
# perform Update-Deployment
$setdeployment = Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service -Force
$completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot
$completeDeploymentID = $completeDeployment.deploymentid
write-progress -id 3 -activity "Upgrading Deployment" -completed -Status "Complete"
Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: Complete, Deployment ID: $completeDeploymentID"
}
Write-Output "Create Azure Deployment"
Publish
|
PowerShellCorpus/GithubGist/CrawdadWarden_7560f0cfc3ff187a05cb_raw_9d17d2056a19c8b674d43dc6f5e13f9448e3850f_barnsley.ps1
|
CrawdadWarden_7560f0cfc3ff187a05cb_raw_9d17d2056a19c8b674d43dc6f5e13f9448e3850f_barnsley.ps1
|
[reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
[reflection.assembly]::LoadWithPartialName( "System.Drawing")
$form = New-Object Windows.Forms.Form
$Form.Width = 400
$Form.Height = 300
$formGraphics = $form.createGraphics()
function draw($x,$y,$color){
if($x -le $Form.Width -and $y -le $Form.Height){
$mypen = new-object Drawing.Pen $color
$formGraphics.DrawLine($mypen, $x, $y, $x+1, $y+1)
}
}
function fern(){
$pp = 20000
$x
$y
$px
$py
[double]$xn
[double]$yn
$color
for($p=0; $p -le $pp; $p++){
[int]$rand = Get-Random -Maximum 4
switch ($rand)
{
0
{
$color = "green"
$xn = 0;
$yn = .16*$y;
$x = $xn;
$y = $yn;
}
1
{
$color = "Yellow"
$xn = .2*$x-.26*$y;
$yn = .2*$x+0.23*$y+1.60;
$x = $xn;
$y = $yn;
}
2
{
$color = "Orange"
$xn = -.15*$x+.24*$y;
$yn = .26*$x+.24*$y+.44;
$x = $xn;
$y = $yn;
}
3
{
$color = "blue"
$xn = .85*$x+.04*$y;
$yn = -.004*$x+0.85*$y+1.6;
$x = $xn;
$y = $yn;
}
}
$px = $x*300/10+400/2;
$py = $y*400/10+400/15;
draw $px $py $color
draw ($px + 1) ($py -1) $color
draw $px ($py -1) $color
draw ($px + 1) $py $color
draw ($px - 1) ($py +1) $color
draw $px ($py + 1) $color
draw ($px -1) $py $color
}}
$form.add_paint(
{
fern
}
)
$form.ShowDialog()
|
PowerShellCorpus/GithubGist/xinmyname_11375560_raw_aa3b9789e7f1153748cb5550ad0acd0e064d956a_serveandwatch.ps1
|
xinmyname_11375560_raw_aa3b9789e7f1153748cb5550ad0acd0e064d956a_serveandwatch.ps1
|
Start-Process python.exe -argument '-m http.server'; Start-Process livereloadx.cmd
|
PowerShellCorpus/GithubGist/jschell_a13459151dd40111ff6b_raw_6f250b711a261f6f674d7aeb69319da1e7451e59_connect-azurePSSession.ps1
|
jschell_a13459151dd40111ff6b_raw_6f250b711a261f6f674d7aeb69319da1e7451e59_connect-azurePSSession.ps1
|
function connect-azurePSSession
{
<#
borrowed from : http://jrich523.wordpress.com/2010/07/21/update-creating-a-profile-for-a-remote-session/
#>
[cmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$hostName,
[Parameter(Mandatory=$True)]
[int]$portNumber,
[Parameter(Mandatory=$True)]
[PSCredential]$credentials,
[Parameter(Mandatory=$False)]
[string]$sessionName
)
$newSessionOptions = @{
computerName = "$hostName"
port = "$portNumber"
authentication = "Negotiate"
credential = $credentials
useSSL = $true
sessionOption = (New-PSSessionOption -SkipCACheck -SkipCNCheck)
}
if($sessionName)
{ $newSessionOptions += @{ name = $sessionName} }
$session = new-psSession @newSessionOptions
invoke-command -session $session -scriptBlock {
## Begin Remote Profile ##
function Prompt
{
#Put the ID of the command in, so we can get/invoke-history easier
#eg: "r 4" will re-run the command that has [4]: in the prompt
$nextCommandId = (Get-History -count 1).Id + 1
#Output prompt string
#Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host -ForegroundColor Yellow -NoNewLine "`n$env:computername."
Write-Host -ForegroundColor Gray -NoNewLine "$env:userdnsdomain"
Write-Host -ForegroundColor 03 "`n[$(Get-Location)]"
#Break up second prompt line to change color of history counter
Write-Host -ForegroundColor Yellow -NoNewLine "PS: ["
Write-Host -ForegroundColor Gray -NoNewLine "${nextCommandId}"
Write-Host -ForegroundColor Yellow -NoNewLine "] `n"
return " "
}
}
enter-psSession $session
} # end connect-azurePSSession
|
PowerShellCorpus/GithubGist/andrewgunn_5668952_raw_47c9faad6d9081503a7b72b8577d70e31b403167_Chocolatey.ps1
|
andrewgunn_5668952_raw_47c9faad6d9081503a7b72b8577d70e31b403167_Chocolatey.ps1
|
# - Install .NET Framework 4.0
# - Install Powershell 2.0
# - Open Powershell as administrator
# - Set-ExecutionPolicy RemoteSigned -Force
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
# Browsers
choco install Firefox
choco install GoogleChrome
choco install Opera
choco install Safari
# Development tools
choco install VisualStudio2013Professional
choco install NCrunch2.vs2013
choco install ReSharper
choco install SqlServer2014Express
choco install BeyondCompare
choco install dotPeek
choco install dotTrace
choco install fiddler
choco install ilspy
choco install procexp
choco install Console2
choco install Notepadplusplus
#choco install NServiceBus.PerfCounters.Install
# Git
choco install Git
choco install GitExtensions
choco install PoshGit
choco install SourceTree
# Social
choco install Skype
# Misc
choco install adobereader
choco install Dropbox
choco install f.lux
choco install handbrake
choco install paint.net
choco install VirtualCloneDrive
choco install 7zip
# Manual steps
# ------------
# - Configure Visual Studio for web development
# - Control Panel > Programs and Features > Microsoft Visual Studio
# - Right click > Change
# - Modify
# - Select "Nicrosoft SQL Server Data Tools" and "Microsoft Web Developer Tools"
# - Update
# - Install IIS7 and enable ASP.NET (http://www.gotknowhow.com/articles/how-to-install-iis7-and-enable-aspnet)
# - %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
# - Install Cropper (http://cropper.codeplex.com/)
|
PowerShellCorpus/GithubGist/HostileCoding_a62ca4ad2e2534d6e7f6_raw_653465d1553b4adfffc4b0756a0eae29c5456925_Tenants%20Mobile%20Reports.ps1
|
HostileCoding_a62ca4ad2e2534d6e7f6_raw_653465d1553b4adfffc4b0756a0eae29c5456925_Tenants%20Mobile%20Reports.ps1
|
#Variable declaration
$vCloudIPorFQDN="192.168.243.50"
$vCloudUsername="User1"
$vCloudPassword="mypassword"
$vCloudOrganization="HostileCoding"
$outputFile="C:\Users\Paolo\Desktop\mobilereport.html"
#Connecting to vCloud
Connect-CIServer -Server $vCloudIPorFQDN -User $vCloudUsername -Password $vCloudPassword -Org $vCloudOrganization
#Get Organization Informations
$organization = Get-Org
$htmlheader = @"
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
</head>
"@
$htmlbody1 = @"
<body>
<div data-role="page" id="home">
<div data-role="header">
<h1>$($vCloudOrganization)</h1>
</div>
<div data-role="content">
<div data-role="collapsible">
<h3>$($organization.Name)</h3>
<p>
<ul class="ui-listview ui-listview-inset ui-corner-all ui-shadow" data-inset="true" data-role="listview">
<li class="ui-li-static ui-body-inherit ui-first-child">
Enabled
<p>
$($organization.Enabled)
</p>
</li>
<li class="ui-li-static ui-body-inherit ui-first-child">
Can Publish
<p>
$($organization.CanPublish)
</p>
</li>
<li class="ui-li-static ui-body-inherit ui-first-child">
Deployed VM Quota
<p>
$($organization.DeployedVMQuota)
</p>
</li>
<li class="ui-li-static ui-body-inherit ui-first-child">
Stored VM Quota
<p>
$($organization.StoredVMQuota)
</p>
</li>
<li class="ui-li-static ui-body-inherit ui-first-child">
Catalog Count
<p>
$($organization.CatalogCount)
</p>
</li>
<li class="ui-li-static ui-body-inherit ui-first-child">
vApp Count
<p>
$($organization.VAppCount)
</p>
</li>
</ul>
</p>
</div>
"@
#Get Organization vDC Informations
$organizationvdc = Get-OrgVdc
foreach($vdc in $organizationvdc){
$htmlbody2 += @"
<div data-role="collapsible">
<h3>$($vdc.Name)</h3>
<p>
<ul class="ui-listview ui-listview-inset ui-corner-all ui-shadow" data-inset="true" data-role="listview">
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Allocation Model
<span class="ui-li-count ui-body-inherit">
$($vdc.AllocationModel)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Enabled
<span class="ui-li-count ui-body-inherit">
$($vdc.Enabled)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Cpu Used Ghz
<span class="ui-li-count ui-body-inherit">
$($vdc.CpuUsedGhz)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Cpu Limit Ghz
<span class="ui-li-count ui-body-inherit">
$($vdc.CpuLimitGhz)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Cpu Allocation Ghz
<span class="ui-li-count ui-body-inherit">
$($vdc.CpuAllocationGhz)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Cpu Overhead Ghz
<span class="ui-li-count ui-body-inherit">
$($vdc.CpuOverheadGhz)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Memory Used GB
<span class="ui-li-count ui-body-inherit">
$($vdc.MemoryUsedGB)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Memory Limit GB
<span class="ui-li-count ui-body-inherit">
$($vdc.MemoryLimitGB)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Memory Allocation GB
<span class="ui-li-count ui-body-inherit">
$($vdc.MemoryAllocationGB)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Memory Overhead GB
<span class="ui-li-count ui-body-inherit">
$($vdc.MemoryOverheadGB)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Storage Used GB
<span class="ui-li-count ui-body-inherit">
$($vdc.StorageUsedGB)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Storage Limit GB
<span class="ui-li-count ui-body-inherit">
$($vdc.StorageLimitGB)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
vApp Count
<span class="ui-li-count ui-body-inherit">
$($vdc.VAppCount)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Status
<span class="ui-li-count ui-body-inherit">
$($vdc.Status)
</span>
</li>
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
Network Max Count
<span class="ui-li-count ui-body-inherit">
$($vdc.NetworkMaxCount)
</span>
</li>
</ul>
</p>
</div>
<ul class="ui-listview ui-listview-inset ui-corner-all ui-shadow" data-inset="true" data-filter="true" data-role="listview">
"@
}
#Get Organization vDC Informations
$organizationvapp = Get-CIVApp
foreach($vapp in $organizationvapp){
$htmlbody3 += @"
<li class="ui-li-static ui-body-inherit ui-li-has-count ui-first-child">
<h3>
$($vapp.Name)
</h3>
<p>
<b>Enabled:</b> $($vapp.Enabled)
</p>
<p>
<b>Status:</b> $($vapp.Status)
</p>
<p>
<b>SizeGB:</b> $($vapp.SizeGB)
</p>
<p>
<b>Cpu Count:</b> $($vapp.CpuCount)
</p>
<p>
<b>Memory Allocation MB:</b> $($vapp.MemoryAllocationMB)
</p>
<p>
<b>Maintenance Mode:</b> $($vapp.InMaintenanceMode)
</p>
<p>
<b>Storage Lease:</b> $($vapp.StorageLease)
</p>
<p>
<b>Runtime Lease:</b> $($vapp.RuntimeLease)
</p>
<p>
<b>Owner:</b> $($vapp.Owner)
</p>
</li>
"@
}
$htmlfooter=@"
</ul>
</div>
<div data-role="footer">
</div>
</div>
</body>
</html>
"@
#Generating the output by concatenating strings
$htmlheader + $htmlbody1 + $htmlbody2 + $htmlbody3 + $htmlfooter | Out-File -Encoding "UTF8" $outputFile
#Disconnecting from vCloud
Disconnect-CIServer -Confirm:$false
|
PowerShellCorpus/GithubGist/tekk555_6249941_raw_5b9106c8f4ea44ab8ea6d59ac822179073827033_gistfile1.ps1
|
tekk555_6249941_raw_5b9106c8f4ea44ab8ea6d59ac822179073827033_gistfile1.ps1
|
$ runlevel
N 2
# 0 停止
# 1 シングルユーザモード
# 2 マルチユーザモード
# 6 リブート
# Ubuntu 12.04 LTS. Debian 系 OS では、2-5を区別しない。
|
PowerShellCorpus/GithubGist/qiwihui_307a3cba8097085db347_raw_0590f97a6f0147e19be4489ae96a10e9a193108c_launchIE.ps1
|
qiwihui_307a3cba8097085db347_raw_0590f97a6f0147e19be4489ae96a10e9a193108c_launchIE.ps1
|
$url = "http://domain/default.html"
# Attach to the existing IE window
$app = new-object -com shell.application
# get a list of all IE windows, filter to the one you need by matching its LocationURL
$ie = $app.windows() | where {$_.Type -eq "HTML Document" -and $_.LocationURL -match $url}
# if there no IE windows you need, open a new one
if ($ie -eq $null)
{
$ie = new-object -com "InternetExplorer.Application"
$ie.visible = $true
while($ie.busy)
{
Start-Sleep -m 50
}
# navigate away
$ie.navigate2($url)
}
|
PowerShellCorpus/GithubGist/guitarrapc_c75b35bb51747f2aac44_raw_3fff684a1c575fd74d41fec3d186fd1a615dbd29_PScustomObject.ps1
|
guitarrapc_c75b35bb51747f2aac44_raw_3fff684a1c575fd74d41fec3d186fd1a615dbd29_PScustomObject.ps1
|
([PScustomObject]@{hoge = "hoge"}).Count # Allways null
([PScustomObject]@{hoge = "hoge"}).Length # Allways null
@([PScustomObject]@{hoge = "hoge"}).Count # 1 => Boxing with Array then get Count
@([PScustomObject]@{hoge = "hoge"}).Length # 1 => Boxing with Array then get Legnth
|
PowerShellCorpus/GithubGist/l9l6_3782585_raw_7e68222d64a2db85de645e41a5fe4792f4575d15_Powershell_AllSitesReport.ps1
|
l9l6_3782585_raw_7e68222d64a2db85de645e41a5fe4792f4575d15_Powershell_AllSitesReport.ps1
|
######################## Start Variables ########################
######################## Varun's Script######################
#$siteURL = "http://sp2010citi.caceis.biz/"
#$siteURL = "http://sp-applidoc.caceis.biz/"
#$siteURL = "http://sp-collaborative.lux.caceis.biz/"
#$siteURL = "http://sp-collaboratif.caceis.biz/"
#$siteURL = "http://sp-collaborative.de.caceis.biz"
#$siteURL = "http://sp-collaborative.fed.caceis.biz/"
#$siteURL = "http://sp-collaborative.fra.caceis.biz/"
$filePath = "C:\Tools\Sites Report.csv" #Path for exported CSV file
######################## End Variables ########################
if(Test-Path $filePath)
{
Remove-Item $filePath
}
Clear-Host
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
# Creates an object that represents a SharePoint site.
function CreateNewObject
{
$customObject = New-Object system.Object
$customObject | Add-Member -type NoteProperty -Name WebCreated -Value $web.Created.ToShortDateString()
$customObject | Add-Member -type NoteProperty -Name WebModified -Value $web.LastItemModifiedDate.ToShortDateString()
$customObject | Add-Member -type NoteProperty -Name RequestAccessEmail -Value $web.RequestAccessEmail
$customObject | Add-Member -type NoteProperty -Name WebTitle -Value $web.Title
$customObject | Add-Member -type NoteProperty -Name WebURL -Value $web.URL
$customObject | Add-Member -type NoteProperty -Name WebTemplateName -Value $web.WebTemplate
$customObject | Add-Member -type NoteProperty -Name WebTemplateID -Value $web.WebTemplateId
$customObject | Add-Member -type NoteProperty -Name ItemCount -Value ""
$customObject | Add-Member -type NoteProperty -Name SiteAdmins -Value ""
$customObject | Add-Member -type NoteProperty -Name GreaterThanZeroItems -Value $false
return $customObject
}
$site = new-object microsoft.sharepoint.spsite($siteURL)
$webApp = $site.webapplication
$allSites = $webApp.sites
$customObjectsList =@()
foreach
($site in $allSites)
{
$allWebs = $site.AllWebs
foreach ($web in $allWebs)
{
$itemCount = 0;
$customWebObject = CreateNewObject
$templateID = $web.WebTemplateID.ToString()
foreach ($list in $web.Lists)
{
if(($list.ItemCount -gt 0) -and ($list.Hidden -ne $true))
{
$customWebObject.GreaterThanZeroItems = $true
$itemCount += $list.ItemCount;
}
}
$customWebObject.ItemCount = $itemCount.ToString()
$customObjectsList += $customWebObject
Write-Host $web.title
$web.Dispose()
}
$site.dispose()
}
# Exporting the data to a CSV file
$customObjectsList | Select-Object WebCreated,WebModified,WebTitle,WebURL,WebTemplateName,WebTemplateID,Fab40Site,ItemCount,GreaterThanZeroItems,SiteAdmins,RequestAccessEmail | Export-Csv $filePath
|
PowerShellCorpus/GithubGist/andreaswasita_c21e652fb5c1ab54bfeb_raw_7567aaff146aba8865d107f565901d2b12c751f0_CreateILBInstance.ps1
|
andreaswasita_c21e652fb5c1ab54bfeb_raw_7567aaff146aba8865d107f565901d2b12c751f0_CreateILBInstance.ps1
|
$svc="AZSEDB"
$ilb="SQLILB"
$subnet="Azure-BackEnd"
$IP="10.0.1.100"
Add-AzureInternalLoadBalancer -ServiceName $svc -InternalLoadBalancerName $ilb –SubnetName $subnet –StaticVNetIPAddress $IP
|
PowerShellCorpus/GithubGist/wpsmith_6a96d808f2c72896e05b_raw_7abc84597001f693419a237baf2993ce0813bcfc_host-named-sites.ps1
|
wpsmith_6a96d808f2c72896e05b_raw_7abc84597001f693419a237baf2993ce0813bcfc_host-named-sites.ps1
|
# Replace:
# DATABASE
# NAMED
# APPLICATION NAME
# hostheadername
# DOMAIN\USER
# DOMAIN\SP_FARM_ACCOUNT
# PATHNAME
# SITE COLLECTION NAME
# DIRECTORYPORT
# Create Authentication Provider
$ap = New-SPAuthenticationProvider
# Create Web Application
$w = New-SPWebApplication -DatabaseName "WSS_Content_DATABASE" -ApplicationPool "NAMED App Pool" -Name "APPLICATION NAME" -Port 80 -AuthenticationProvider $ap1 -ApplicationPoolAccount (Get-SPManagedAccount 'DOMAIN\SP_FARM_ACCOUNT') -Path "%wwwroot%\wss\VirtualDirectories\DIRECTORYPORT" -HostHeader "hostheadername"
iisreset /noforce
# Create Root Site Collection
$w = Get-SPWebApplication "APPLICATION NAME"
New-SPSite http://sub.domain.com -OwnerAlias "DOMAIN\USER" -HostHeaderWebApplication $w -Name "APPLICATION NAME" -Template "BLANKINTERNETCONTAINER#0"
# Create Managed Path Site Collection
New-SPManagedPath "PATHNAME" -HostHeader -Explicit
New-SPSite http://sub.domain.com/PATHNAME -OwnerAlias "DOMAIN\USER" -HostHeaderWebApplication $w -Name "SITE COLLECTION NAME" -Template "BLANKINTERNETCONTAINER#0"
|
PowerShellCorpus/GithubGist/senpost_4628251_raw_b159757d558e7fbc2c5a9b398604646dd5ab7084_gistfile1.ps1
|
senpost_4628251_raw_b159757d558e7fbc2c5a9b398604646dd5ab7084_gistfile1.ps1
|
#List all files and hidden files
Get-ChildItem -Attributes !Directory+Hidden
|
PowerShellCorpus/GithubGist/sneal_73a0a088c55fbbe07ec6_raw_c7ae5356fd55a3de4fc937b55f79f839d511cefe_install-7zip.ps1
|
sneal_73a0a088c55fbbe07ec6_raw_c7ae5356fd55a3de4fc937b55f79f839d511cefe_install-7zip.ps1
|
$version = '922'
$msi_file_name = "7z$version-x64.msi"
$download_url = "http://downloads.sourceforge.net/sevenzip/$msi_file_name"
(New-Object System.Net.WebClient).DownloadFile($download_url, "C:\Windows\Temp\$msi_file_name")
&msiexec /i "C:\Windows\Temp\$msi_file_name" INSTALLDIR='C:\7-zip' /qb
|
PowerShellCorpus/GithubGist/guitarrapc_42679ad7bff50da42055_raw_5c89051674b505f118a2e22243d95465ee758c00_Copy-ItemEX.ps1
|
guitarrapc_42679ad7bff50da42055_raw_5c89051674b505f118a2e22243d95465ee758c00_Copy-ItemEX.ps1
|
function Copy-ItemEX
{
[CmdletBinding()]
param
(
[parameter(Mandatory = 1, Position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName =1)]
[alias('PSParentPath')]
[string]$Path,
[parameter(Mandatory = 1, Position = 1, ValueFromPipelineByPropertyName =1)]
[string]$Destination,
[parameter(Mandatory = 0, Position = 2, ValueFromPipelineByPropertyName =1)]
[string[]]$Targets,
[parameter(Mandatory = 0, Position = 3, ValueFromPipelineByPropertyName =1)]
[string[]]$Excludes,
[parameter(Mandatory = 0, Position = 4, ValueFromPipelineByPropertyName =1)]
[Switch]$Recurse,
[parameter(Mandatory = 0, Position = 5)]
[switch]$Force,
[parameter(Mandatory = 0, Position = 6)]
[switch]$WhatIf
)
process
{
# Test Path
if (-not (Test-Path $Path)){throw 'Path not found Exception!!'}
# Get Filter Item Path as List<Tuple<string>,<string>,<string>>
$filterPath = GetTargetsFiles -Path $Path -Targets $Targets -Recurse:$isRecurse -Force:$Force
# Remove Exclude Item from Filter Item
$excludePath = GetExcludeFiles -Path $filterPath -Excludes $Excludes
# Execute Copy, confirmation and WhatIf can be use.
CopyItemEX -Path $excludePath -RootPath $Path -Destination $Destination -Force:$isForce -WhatIf:$isWhatIf
}
begin
{
$isRecurse = $PSBoundParameters.ContainsKey('Recurse')
$isForce = $PSBoundParameters.ContainsKey('Force')
$isWhatIf = $PSBoundParameters.ContainsKey('WhatIf')
function GetTargetsFiles
{
[CmdletBinding()]
param
(
[string]$Path,
[string[]]$Targets,
[bool]$Recurse,
[bool]$Force
)
# fullName, DirectoryName, Name
$list = New-Object 'System.Collections.Generic.List[Tuple[string,string,string]]'
$base = Get-ChildItem $Path -Recurse:$Recurse -Force:$Force
if (($Targets | measure).count -ne 0)
{
foreach($target in $Targets)
{
$base `
| where Name -like $target `
| %{
if ($_ -is [System.IO.FileInfo])
{
$tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.DirectoryName, $_.Name)
}
elseif ($_ -is [System.IO.DirectoryInfo])
{
$tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.PSParentPath, $_.Name)
}
else
{
throw "Type '{0}' not imprement Exception!!" -f $_.GetType().FullName
}
$list.Add($tuple)
}
}
}
else
{
$base `
| %{
if ($_ -is [System.IO.FileInfo])
{
$tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.DirectoryName, $_.Name)
}
elseif ($_ -is [System.IO.DirectoryInfo])
{
$tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.PSParentPath, $_.Name)
}
else
{
throw "Type '{0}' not imprement Exception!!" -f $_.GetType().FullName
}
$list.Add($tuple)
}
}
return $list
}
function GetExcludeFiles
{
param
(
[System.Collections.Generic.List[Tuple[string,string,string]]]
$Path,
[string[]]
$Excludes
)
if (($Excludes | measure).count -ne 0)
{
Foreach ($exclude in $Excludes)
{
# name not like $exclude
$Path | where Item3 -notlike $exclude
}
}
else
{
$Path
}
}
function CopyItemEX
{
[cmdletBinding(
SupportsShouldProcess = $true,
ConfirmImpact = 'High')]
param
(
[System.Collections.Generic.List[Tuple[string,string,string]]]$Path,
[string]$RootPath,
[string]$Destination,
[bool]$Force
)
begin
{
# remove default bound "Force"
$PSBoundParameters.Remove('Force') > $null
}
process
{
# convert to regex format
$root = $RootPath.Replace('Microsoft.PowerShell.Core\FileSystem::','').Replace('\', '\\')
$Path `
| %{
# create destination DirectoryName
$directoryName = Join-Path $Destination ($_.Item2 -split $root | select -Last 1)
[PSCustomObject]@{
Path = $_.Item1
DirectoryName = $directoryName
Destination = Join-Path $directoryName $_.Item3
}} `
| where {$Force -or $PSCmdlet.ShouldProcess($_.Path, ('Copy Item to {0}' -f $_.Destination))} `
| %{
Write-Verbose ("Copying '{0}' to '{1}'." -f $_.Path, $_.Destination)
New-Item -Path $_.DirectoryName -ItemType Directory -Force > $null
Copy-Item -Path $_.Path -Destination $_.Destination -Force
}
}
}
}
}
|
PowerShellCorpus/GithubGist/andrewabest_8776157_raw_9c5c0c13928c7531658f99220e81011491b4a9a4_Deploy.ps1
|
andrewabest_8776157_raw_9c5c0c13928c7531658f99220e81011491b4a9a4_Deploy.ps1
|
Write-Host 'Copy the package payload over to the clickonce web application location'
$source = ".\"
$dest = "C:\Octopus\Applications\${OctopusEnvironmentName}\NextGen.ClickOnce\${OctopusPackageVersion}\Package"
$exclude = @('*.pdb','mage.exe', '*.ps1', '*Build*', '*.pfx')
$appManifestName = "${OctopusPackageName}.exe.manifest"
$appManifestPath = Join-Path $dest $appManifestName
$deployManifestPath = Join-Path $dest "${OctopusPackageName}.application"
Write-Host 'Create package folder and copy everything'
New-Item -ItemType directory -Path $dest
Get-ChildItem $source -Recurse -Exclude $exclude | Copy-Item -Destination $dest
Write-Host 'Create app manifest'
& ".\Build\Mage.exe" -New Application -Name "${OctopusPackageName} ${OctopusEnvironmentName}" -ToFile $appManifestPath -FromDirectory $dest -Version $OctopusPackageVersion | Write-Host
#& ".\Build\Mage.exe" -Sign $appManifestPath -CertFile .\ClickOnce.pfx -Password password
Write-Host 'Create deploy manifest'
& ".\Build\Mage.exe" -New Deployment -AppManifest $appManifestPath -Install true -Publisher "Andrew Best" -ProviderUrl "http://ci/AppName.${OctopusEnvironmentName}/Package/${OctopusPackageName}.application" -Version $OctopusPackageVersion -Name "${OctopusPackageName} ${OctopusEnvironmentName}" -ToFile $deployManifestPath | Write-Host
Write-Host 'Add deploy extension to files'
$ex = @('*.application', '*.manifest')
$packageFiles = Get-ChildItem $dest -Recurse -Exclude $ex
foreach ($file in $packageFiles) {
$newname = $file.name + ".deploy"
Rename-Item -Path $file -NewName $newname
}
Write-Host 'Add mapFileExtensions to deploy manifest so that it works with the *.deploy extension'
$xml = [xml](Get-Content "$deployManifestPath")
$deployment_node = $xml.SelectSingleNode("//*[local-name() = 'deployment']")
$deployment_node.SetAttribute("mapFileExtensions", "true")
$xml.Save("$deployManifestPath")
#Write-Host 'Sign deploy manifest'
#& ".\Build\Mage.exe" -Sign $deployManifestPath -CertFile .\ClickOnceSpike_TemporaryKey.pfx -Password centium
#Run Database with the configured connection string to migrate our testDb
#$connectionString = $OctopusParameters["DbContext"]
#$zeroDb = $OctopusParameters["ZeroDb"]
#& "bin\Database.exe" $connectionString $zeroDb | Write-Host
|
PowerShellCorpus/GithubGist/kouphax_1101809_raw_f480c576ca630f712d45c18abef7a38c0dbc3e0e_Install.ps1
|
kouphax_1101809_raw_f480c576ca630f712d45c18abef7a38c0dbc3e0e_Install.ps1
|
Install-Package Tinyweb
|
PowerShellCorpus/GithubGist/jschell_9166802_raw_20471b66b0bd05aa41c356749ff68516cddaa4d4_azureBuildDC.ps1
|
jschell_9166802_raw_20471b66b0bd05aa41c356749ff68516cddaa4d4_azureBuildDC.ps1
|
## Create New VMs
### Get image names
$serviceName = "jws-dev"
$storage = "jwsdevstor"
$networkName = "jws-network01"
$img2012R2Latest = @(get-azureVMImage | where {$_.ImageName -match "Windows-Server-2012-R2"})[-1].ImageName
$img2012Latest = @(get-azureVMImage | where {$_.ImageName -match "Windows-Server-2012-dataCenter"})[-1].ImageName
$adminUser = "aplank"
$adminPassword = "Ch@ngeMe!"
## Picking Static addr...
$dcRange = @(10..250)
$staticAddress = $null
while( $staticAddress -like $null)
{
$lastOctet = $dcRange | select -first 1
$ipInSubnet1 = "10.0.1." + "$lastOctet"
$availCheck = test-azureStaticVNetIP -ipAddress $ipInSubnet1 -vnetName $networkName
if($availCheck.isAvailable -eq $true)
{ $staticAddress = $ipInSubnet1 }
else
{ $dcRange = $dcRange | select -last ($dcRange.count -1)}
}
# end of static addr assignment...
# first dc provision...
$boxName = 'jws-DC01'
$configDC1 = new-azureVMConfig -name $boxName -imageName $img2012R2Latest -instanceSize "Medium" -diskLabel "OS Volume"|
add-azureProvisioningConfig -Windows -adminUserName $adminUser -Password $adminPassword -timeZone "Pacific Standard Time" |
set-azureSubnet -subnetNames "subnet-1" |
set-azureStaticVNetIP -IPAddress $staticAddress
new-azureVM -serviceName $serviceName -vms $configDC1
# Add the data disk...
Get-AzureVM -name $boxName -serviceName $serviceName |
Add-AzureDataDisk -createNew -diskSizeInGB 20 -diskLabel "$($boxName)-Data" -hostCaching 'None' -LUN 0 |
Update-AzureVM
# credentials for psremote...
$adminPasswordSecure = ConvertTo-SecureString -asPlainText $adminPassword -force
$adminLocal = New-Object -TypeName System.Management.Automation.PsCredential -ArgumentList $adminUser, $adminPasswordSecure
# get URI for WinRM session
$uriWinRM = get-azureWinRMUri -serviceName $serviceName -name $boxName
# enter session
Enter-PSSession -ComputerName $($uriWinRM.host) -Port $($uriWinRM.port) -Authentication Negotiate -Credential $adminLocal -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck)
$newDisk = get-disk | where {$_.PartitionStyle -eq "RAW"}
Initialize-Disk -number $($newDisk.number) -partitionStyle "MBR"
New-Partition -diskNumber $($newDisk.number) -useMaximumSize -driveLetter 'F' |
Format-Volume -newFileSystemLabel 'ADDS-Data' -fileSystem NTFS -confirm:$false
# run for *all* machines...
Set-Volume -driveLetter 'C' -newFileSystemLabel 'OSDisk'
# change the local admin pw
$localAdminPassword = "ItPutsTheSecretInOrItGetsTheHoseAgain"
$localAdmin = [ADSI]"WinNT://./APLANK"
$localAdmin.setPassword($localAdminPassword)
$localAdmin.setInfo()
exit
# close out the pssession and re-up with new pw...
# update the user details with new pw...
$adminPassword = $localAdminPassword
$adminPasswordSecure = ConvertTo-SecureString -asPlainText $adminPassword -force
$adminLocal = New-Object -TypeName System.Management.Automation.PsCredential -ArgumentList $adminUser, $adminPasswordSecure
Enter-PSSession -ComputerName $($uriWinRM.host) -Port $($uriWinRM.port) -Authentication Negotiate -Credential $adminLocal -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck)
### Deploy new DC
### (still inside pssession)
# Install features and roles
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
Install-WindowsFeature -Name RSAT-DNS-Server
# Install-WindowsFeature -Name Windows-Server-Backup
$safeMode = 'MoarHosesMoarProblems'
$safeModeDSPassword = ConvertTo-SecureString -asPlainText $safeMode -force
$domainNetbiosName = "primary"
$domainNetbiosName = $domainNetbiosName.toUpper()
Import-Module ADDSDeployment
# forest/ domain modes available: Win2003, Win2008, Win2008R2, Win2012, Win2012R2
$forestDetails = @{
DomainMode = "Win2012R2"
ForestMode = "Win2012R2"
SafeModeAdministratorPassword = $safeModeDSPassword
DomainName = "$domainNetbiosName.yolo"
DomainNetbiosName = "$domainNetbiosName"
DatabasePath = "F:\NTDS"
LogPath = "F:\NTDS"
SysvolPath = "F:\SYSVOL"
CreateDnsDelegation = $false
InstallDns = $true
NoRebootOnCompletion = $false
Force = $true
}
Install-ADDSForest @forestDetails
#### Machine reboots, connection for session drops
start-sleep -s 180 # sleep for 3 minutes
Enter-PSSession -ComputerName $($uriWinRM.host) -Port $($uriWinRM.port) -Authentication Negotiate -Credential $adminLocal -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck)
# update domain password policy
$domainDetail = get-adDomain
$domainNetbios = $domainDetail.netbiosName
$domainUPNSpace = $domainDetail.dnsRoot
$90day = new-timeSpan -days 90
set-adDefaultDomainPasswordPolicy -identity $domainNetbios -minPasswordAge 0 -maxPasswordAge $90day -minPasswordLength 8
# need to make sure timeSpan is correct, otherwise number input sets to 90 /ticks/
# add domain users...
$passwordStart = "Password55"
$password = ConvertTo-SecureString -AsPlainText $passwordStart -force
$domainUsersCSV = @"
samAccountName,givenName,surName,displayName,
sbad,Strong,Bad,Strong Bad,
hrunner,Homestar,Runner,Homestar Runner,
"@
$adminUsers = ConvertFrom-CSV $domainUsersCSV
$adminUsers | foreach {
new-adUser -name $_.displayName -samAccountName $_.samAccountName -givenName $_.givenName -surName $_.surName -displayName $_.displayName -accountPassword $Password -changePasswordAtLogon:$false -enabled:$true -userPrincipalName "$($_.samAccountName)@$domainUPNSpace"
}
$sbadpw = "Phq9aooneWuNboZZCIPihlMcPFJ6gQ"
$sbadpw = ConvertTo-SecureString -AsPlainText $sbadpw -force
set-adAccountPassword sbad -newPassword $sbadPW
$adminUserSam = @($adminUsers.samAccountName)
$groupsForAdmin = @("Administrators","Domain Admins","Enterprise Admins")
$groupsForAdmin | foreach {
$group = get-adgroup $_
add-adGroupMember -identity $group -members $adminUserSam
}
$groupsToEmpty = @("Schema Admins")
$groupsToEmpty | foreach {
$group = get-adgroup $_
$currentMembers = @(get-adGroupMember -identity $group)
if($currentMembers.count -gt 0)
{
remove-adGroupMember -identity $group -members $currentMembers -confirm:$false
}
}
exit
# switch to using named account...
#
# !!creds
$sbadUser = "primary\sbad"
$sbadPW = "Phq9aooneWuNboZZCIPihlMcPFJ6gQ"
$sbadPW = ConvertTo-SecureString -AsPlainText $sbadPW -force
$sbadPrimary = New-Object -TypeName System.Management.Automation.PsCredential -ArgumentList $sbadUser, $sbadPW
## End of Creds
Enter-PSSession -ComputerName $($uriWinRM.host) -Port $($uriWinRM.port) -Authentication Negotiate -Credential $sbadPrimary -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck)
exit
# exit the pssession
##
# re-run static finder...
$dcRange = @(10..250)
$staticAddress = $null
while( $staticAddress -like $null)
{
$lastOctet = $dcRange | select -first 1
$ipInSubnet1 = "10.0.1." + "$lastOctet"
$availCheck = test-azureStaticVNetIP -ipAddress $ipInSubnet1 -vnetName "jws-network01"
if($availCheck.isAvailable -eq $true)
{ $staticAddress = $ipInSubnet1 }
else
{ $dcRange = $dcRange | select -last ($dcRange.count -1)}
}
# for instance sizes, /must/ capitalize the first letter (dumb)
$boxName = 'jws-DC02'
$configDC2 = new-azureVMConfig -name $boxName -imageName $img2012R2Latest -instanceSize "Small" -diskLabel "OS Volume"|
add-azureProvisioningConfig -WindowsDomain -Domain 'Primary' -adminUserName $adminUser -Password $adminPassword -domainUserName $adminUser -domainPassword $adminPassword -JoinDomain 'Primary.yolo' -timeZone "Pacific Standard Time" |
set-azureSubnet -subnetNames "subnet-1" |
set-azureStaticVNetIP -IPAddress $staticAddress
new-azureVM -serviceName "jws-dev" -vms $configDC2
$uriWinRM = get-azureWinRMUri -serviceName $serviceName -name $boxName
Enter-PSSession -ComputerName $($uriWinRM.host) -Port $($uriWinRM.port) -Authentication Negotiate -Credential $sbadPrimary -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck)
# Install features and roles
Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
Install-WindowsFeature -Name RSAT-DNS-Server
# Install-WindowsFeature -Name Windows-Server-Backup
$safeMode = 'd178V4NQpK9zYSp33QC5DbmyzVIil5'
$safeModeDSPassword = ConvertTo-SecureString -asPlainText $safeMode -force
Import-Module ADDSDeployment
# re-run static finder...
$boxName = 'jws-DC03'
$configDC2 = new-azureVMConfig -name $boxName -imageName $img2012R2Latest -instanceSize "small" -diskLabel "OS Volume"|
add-azureProvisioningConfig -WindowsDomain -Domain 'Primary' -domainUserName $adminUser -domainPassword $adminPassword -JoinDomain 'Primary.yolo' -timeZone "Pacific Standard Time" |
set-azureSubnet -subnetNames "subnet-1" |
set-azureStaticVNetIP -IPAddress $staticAddress
new-azureVM -serviceName "jws-dev" -vms
$configGeneric = new-azureVMConfig -name $boxName -imageName $img2012Latest -instanceSize "Medium" -diskLabel "OS Volume"|
add-azureProvisioningConfig -Windows -adminUserName $adminUser -Password $adminPassword -timeZone "Pacific Standard Time" |
set-azureSubnet "subnet-1"
new-azureVM -serviceName "jws-dev" -vms $configGeneric
# to use the 'set-azureStaticVNetIP', must have 'set-azureSubnet' set as well...
# 'remove-azuredisk' -diskName -deleteVHD (switch)
# remove-azurevm -serviceName -name -deleteVHD (switch)
$configTestStatic = new-azureVMConfig -name 'jws-testStatic' -imageName $img2012Latest -instanceSize "Medium" -diskLabel "OS Volume"|
add-azureProvisioningConfig -Windows -adminUserName $adminUser -Password $adminPassword -timeZone "Pacific Standard Time" |
set-azureSubnet -subnetNames "subnet-1" |
set-azureStaticVNetIP -IPAddress 10.0.4.20
|
PowerShellCorpus/GithubGist/originalmind_7636510_raw_cc8e9b0dc7443ee02db07cde8105c71919f60f76_set-path-portablegit.ps1
|
originalmind_7636510_raw_cc8e9b0dc7443ee02db07cde8105c71919f60f76_set-path-portablegit.ps1
|
# Usage: Call this script from your PowerShell profile:
# & c:\path\to\scripts\set-path-portablegit.ps1
# todo: set GITHUB_ROOT from registry
Set-Variable -Option Constant -Name GITHUB_ROOT -Value ${Env:USERPROFILE}\AppData\Local\GitHub\
# Get the most recently created version of PortableGit
if (!(Test-Path $GITHUB_ROOT)) {
Write-Host Sorry can''t find GitHub path.
exit 1
}
$PortableGitDir = gci $GITHUB_ROOT | where-object { $_.Name -like 'PortableGit*' } | sort CreationTime | select -last 1
if (!(Test-Path $PortableGitDir.FullName)) {
Write-Host Sorry can''t find Portable Git path.
exit 2
}
$PortableGitDirName = $PortableGitDir.FullName
Write-Host Adding Portable Git location to path: $PortableGitDirName
$env:Path += ";$PortableGitDirName\bin;$PortableGitDirName\cmd"
|
PowerShellCorpus/GithubGist/sukottosan_9671646_raw_3b1b64b1b9fa69ac0990d351f23712e9bf58f696_adcreation.ps1
|
sukottosan_9671646_raw_3b1b64b1b9fa69ac0990d351f23712e9bf58f696_adcreation.ps1
|
Install-WindowsFeature -Name AD-Domain-Services,RSAT-ADDS-Tools
Install-ADDSForest -DomainMode Win2012R2 -DomainName "lab.lab.com" -DomainNetbiosName "LAB" -ForestMode Win2012R2 -DatabasePath "C:\Windows\NTDS" -InstallDns:$true -LogPath "C:\Windows\NTDS" -NoRebootOnCompletion:$false -SysvolPath "C:\Windows\SYSVOL" -Force:$true
Add-DnsServerResourceRecordA -Name "brix" -ZoneName "lab.lab.com" -IPv4Address "192.168.0.9"
Get-DnsServerResourceRecord -ZoneName "lab.lab.com"
|
PowerShellCorpus/GithubGist/rheid_a5ffa6a648f07453039d_raw_986aa8559355924e757d3cac5b3abfda30d09467_updateListNoEvents.ps1
|
rheid_a5ffa6a648f07453039d_raw_986aa8559355924e757d3cac5b3abfda30d09467_updateListNoEvents.ps1
|
# open web
$web = Get-SPWeb http://yoursite
# get list
$list = $web.Lists["Your List"]
# get item
$item = $list.GetItemById(1)
# disable event firing
$myAss = [Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");
$type = $myAss.GetType("Microsoft.SharePoint.SPEventManager");
$prop = $type.GetProperty([string]"EventFiringDisabled",[System.Reflection.BindingFlags] ([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static));
$prop.SetValue($null, $true, $null);
# change properties
$item["Title"] = "New Title"
# update item (without changing the Modified or Modified By fields)
$item.SystemUpdate($false)
# enable event firing
$prop.SetValue($null, $true, $null);
|
PowerShellCorpus/GithubGist/rysstad_10616903_raw_c7e78a6de43b38c9345dffecfe96f89406a19232_Add-Printer.ps1
|
rysstad_10616903_raw_c7e78a6de43b38c9345dffecfe96f89406a19232_Add-Printer.ps1
|
$PrinterPath = "\\printerServer\printerShare"
$PrinterName = "PrinterName"
$wmiNet = new-Object -com WScript.Network
$wmiNet.AddWindowsPrinterConnection($PrinterPath)
# Set as default
(New-Object -ComObject WScript.Network).SetDefaultPrinter($PrinterName)
# List all printers
# (New-Object -ComObject WScript.Network).EnumPrinterConnections()
|
PowerShellCorpus/GithubGist/PaulStovell_5159690_raw_6f756fd0300de02a4506e5ae6f3919c32537c85d_DeployToAzure.ps1
|
PaulStovell_5159690_raw_6f756fd0300de02a4506e5ae6f3919c32537c85d_DeployToAzure.ps1
|
## Octopus Azure deployment script, version 1.0
## --------------------------------------------------------------------------------------
##
## This script is used to control how we deploy packages to Windows Azure.
##
## When the script is run, the correct Azure subscription will ALREADY be selected,
## and we'll have loaded the neccessary management certificates. The Azure PowerShell module
## will also be loaded.
##
## If you want to customize the Azure deployment process, simply copy this script into
## your NuGet package as DeployToAzure.ps1. Octopus will invoke it instead of the default
## script.
##
## The script will be passed the following parameters in addition to the normal Octopus
## variables passed to any PowerShell script.
##
## $OctopusAzureSubscriptionId // The subscription ID GUID
## $OctopusAzureSubscriptionName // The random name of the temporary Azure subscription record
## $OctopusAzureServiceName // The name of your cloud service
## $OctopusAzureStorageAccountName // The name of your storage account
## $OctopusAzureSlot // The name of the slot to deploy to (Staging or Production)
## $OctopusAzurePackageUri // URI to the .cspkg file in Azure Blob Storage to deploy
## $OctopusAzureConfigurationFile // The name of the Azure cloud service configuration file to use
## $OctopusAzureDeploymentLabel // The label to use for deployment
## $OctopusAzureSwapIfPossible // "True" if we should attempt to "swap" deployments rather than a new deployment
function CreateOrUpdate()
{
$deployment = Get-AzureDeployment -ServiceName $OctopusAzureServiceName -Slot $OctopusAzureSlot -ErrorVariable a -ErrorAction silentlycontinue
if (($a[0] -ne $null) -or ($deployment.Name -eq $null))
{
CreateNewDeployment
return
}
if (($OctopusAzureSwapIfPossible -eq $true) -and ($OctopusAzureSlot -eq "Production"))
{
Write-Host "Checking whether a swap is possible"
$staging = Get-AzureDeployment -ServiceName $OctopusAzureServiceName -Slot "Staging" -ErrorVariable a -ErrorAction silentlycontinue
if (($a[0] -ne $null) -or ($staging.Name -eq $null))
{
Write-Host "Nothing is deployed in staging"
}
else
{
Write-Host ("Current staging deployment: " + $staging.Label)
if ($staging.Label -eq $OctopusAzureDeploymentLabel) {
SwapDeployment
return
}
}
}
UpdateDeployment
}
function SwapDeployment()
{
Write-Host "Swapping the staging environment to production"
Move-AzureDeployment -ServiceName $OctopusAzureServiceName
}
function UpdateDeployment()
{
Write-Host "A deployment already exists in $OctopusAzureServiceName for slot $OctopusAzureSlot. Upgrading deployment..."
Set-AzureDeployment -Upgrade -ServiceName $OctopusAzureServiceName -Package $OctopusAzurePackageUri -Configuration $OctopusAzureConfigurationFile -Slot $OctopusAzureSlot -Mode Auto -label $OctopusAzureDeploymentLabel -Force
}
function CreateNewDeployment()
{
Write-Host "Creating a new deployment..."
New-AzureDeployment -Slot $OctopusAzureSlot -Package $OctopusAzurePackageUri -Configuration $OctopusAzureConfigurationFile -label $OctopusAzureDeploymentLabel -ServiceName $OctopusAzureServiceName
}
function WaitForComplete()
{
$completeDeployment = Get-AzureDeployment -ServiceName $OctopusAzureServiceName -Slot $OctopusAzureSlot
$completeDeploymentID = $completeDeployment.DeploymentId
Write-Host "Deployment complete; Deployment ID: $completeDeploymentID"
}
CreateOrUpdate
WaitForComplete
|
PowerShellCorpus/GithubGist/tophatsteve_2888674_raw_52e839f054ea533486407c718c291c2c144e4ef0_classfactory.ps1
|
tophatsteve_2888674_raw_52e839f054ea533486407c718c291c2c144e4ef0_classfactory.ps1
|
function ClassFactory(){
$object = New-Module {
$myField = 5
function xTimesMyField($x) {
$x * $myField
}
Export-ModuleMember -Variable * -Function *
} -asCustomObject
return $object
}
# create object
$obj = ClassFactory
# add method to object
Add-Member -InputObject $obj -MemberType ScriptMethod -Name "sayHello" -Value { echo "Hello" }
|
PowerShellCorpus/GithubGist/mwrock_5422968_raw_2a29648403ffbf07bcc7ce13fdcee078d43547ec_gistfile1.ps1
|
mwrock_5422968_raw_2a29648403ffbf07bcc7ce13fdcee078d43547ec_gistfile1.ps1
|
Import-Module "${env:ProgramFiles(x86)}\Microsoft Team Foundation Server 2012 Power Tools\Microsoft.TeamFoundation.PowerTools.PowerShell.dll"
|
PowerShellCorpus/GithubGist/bgallagh3r_3535837_raw_0ccf27cc76cb785d2682330a152824b70eac92c3_ssh-agent-utils.ps1
|
bgallagh3r_3535837_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/theagreeablecow_6171487_raw_4361906bc445705430ded742c04b0fc262f9b629_set-ADPhotos.ps1
|
theagreeablecow_6171487_raw_4361906bc445705430ded742c04b0fc262f9b629_set-ADPhotos.ps1
|
<#
.SYNOPSIS
Import photos into Active Directory
.DESCRIPTION
- Source files are collected in bulk from network location and filtered on Last Modified Date
- Source files must be in the format username.jpg and will be checked against valid AD users
- The files are copied and processed in a temporary working directory
- The files are resized (retaining proportions) and imported into AD
- Both the original and new files are date stamped and backed up (see Exported and Imported folders)
- Optional:
- Lync Address book is updated
- A report is emailed summarising the events
.PARAMETER SourcePath
Specifies the location of the original photos
.PARAMETER Days
Specifies the number days to match against the Modified Date (age of file), for inclusion in the import
Optional - The default is '1' day if not specified
.SYNTAX
Set-ADPhotos <SourcePath> <Days>
.EXAMPLE
.\Set-ADPhotos '\\Server1\sharename' 1
.AUTHOR
TheAgreeableCow July 2013
.NOTES
If setting a sheduled task, ensure to match the schedule with the <Days> parameter.
eg In the default example, run the schedule daily.
Microsoft recommend photo sizes:
- AD thumbnail size max of 96 x 96 pixels and no larger that 10kb
#>
Function Set-ADPhotos{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName = $true)]
[String] $SourcePath="",
[String] $Days=""
)
Begin{
#Working Variables
$WorkingPath = "C:\ADPhotos"
$Logfile = "$WorkingPath\ADPhotos.log"
$TypeFilter = "*.jpg"
$ModifiedAge = (get-date).Adddays(-$Days)
$WidthPx = 96
$HeightPx = 96
#Email Log
$SendEmailLog = $TRUE
$SmtpServer = "exchange.mydomain.com"
$EmailTo = "marketing.user@mydomain.com"
$EmailCc = "it.user@mydomain.com"
#Lync Address Book
$UpdateAddressBook = $TRUE
$LyncServer = "lync1.mydomain.com"
#Set files count to 0
$LocalFilesCount = 0
$NetworkFilesCount = 0
$AllFilesCount = 0
$SucessCount = 0
$FailCount = 0
#Load required powershell Sessions and arrays
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
if ((Get-PSSnapin -Name Lync -ErrorAction SilentlyContinue) -eq $null ){
import-module Lync
}
if ((Get-PSSnapin -Name ActiveDirectory -ErrorAction SilentlyContinue) -eq $null ){
import-module ActiveDirectory
}
#Create working directories
if (!(Test-Path -PathType Container $WorkingPath)){
New-Item $WorkingPath -type Directory
New-Item "$WorkingPath\Exported" -type Directory
New-Item "$WorkingPath\Imported" -type Directory
New-Item "$WorkingPath\Failed" -type Directory
}
#Gather Local files
$LocalFiles = get-childitem -Path $WorkingPath -filter $TypeFilter | where {!$_.PSIsContainer} | where-object {$_.LastWriteTime -gt $ModifiedAge}
$LocalCount = $LocalFiles | measure-object
$LocalFilesCount = $LocalCount.count
if ($LocalFilesCount -gt 0){
foreach ($LocalFile in $LocalFiles){
$LocalName = [io.path]::GetFileNameWithoutExtension($LocalFile)
$LocalFilesNames += "$LocalName, "
}
}
#Gather Network Files
$NetworkFiles = get-childitem -Path $SourcePath -filter $TypeFilter | where {!$_.PSIsContainer} | where-object {$_.LastWriteTime -gt $ModifiedAge}
$NetworkCount = $NetworkFiles | measure-object
$NetworkFilesCount = $NetworkCount.count
if ($NetworkFilesCount -gt 0){
foreach ($NetworkFile in $NetworkFiles){
$NetworkName = [io.path]::GetFileNameWithoutExtension($NetworkFile)
$NetworkFilesNames += "$NetworkName, "
}
$NetworkFiles | copy-item -destination $WorkingPath
}
}
Process{
$AllFilesCount = $LocalFilesCount + $NetworkFilesCount
if ($AllFilesCount -gt 0){
$AllFiles = get-childitem -Path $WorkingPath -filter $TypeFilter | where {!$_.PSIsContainer}
foreach ($File in $AllFiles){
#Confirm Photos match Active Directory Username
$Name = [io.path]::GetFileNameWithoutExtension($File)
$User = Get-ADUser -Filter {SamAccountName -eq $Name}
if ($user -ne $null){
#Export existing photo as a backup
$Export = Get-ADUser $Name -properties SamAccountName, ThumbnailPhoto
if ($Export.ThumbnailPhoto -ne $null){
$FileStamp = "$Name $(get-date -f yyyy-MM-dd-HH-mm-ss).jpg"
$Export.thumbnailphoto | Set-Content ("$WorkingPath\Exported\$FileStamp") -Encoding byte
}
#Determine new dimensions (ensuring to keep proportions)
$OldImage = new-object System.Drawing.Bitmap "$WorkingPath\$File"
$OldWidth = $OldImage.Width
$OldHeight = $OldImage.Height
if($OldWidth -lt $OldHeight){
$NewWidth = $WidthPx
[int]$NewHeight = [Math]::Round(($NewWidth*$OldHeight)/$OldWidth)
if($NewHeight -gt $HeightPx){
$NewHeight = $HeightPx
[int]$NewWidth = [Math]::Round(($NewHeight*$OldWidth)/$OldHeight)
}
}
else{
$NewHeight = $HeightPx
[int]$NewWidth = [Math]::Round(($NewHeight*$OldWidth)/$OldHeight)
if($NewWidth -gt $WidthPx){
$NewWidth = $WidthPx
[int]$NewHeight = [Math]::Round(($NewWidth*$OldHeight)/$OldWidth)
}
}
#Resize Working Image
$NewImage = new-object System.Drawing.Bitmap $NewWidth,$NewHeight
$Graphics = [System.Drawing.Graphics]::FromImage($NewImage)
$Graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
$Graphics.DrawImage($OldImage, 0, 0, $NewWidth, $NewHeight)
#Save Working Image
$ImageFormat = $OldImage.RawFormat
$OldImage.Dispose()
$NewImage.Save("$WorkingPath\$File",$ImageFormat)
$NewImage.Dispose()
#Import into AD
$Photo = [byte[]](Get-Content "$WorkingPath\$File" -Encoding byte)
Set-ADUser $Name -Replace @{thumbnailPhoto=$Photo}
#Save a copy as Imported
$FileStamp = "$Name $(get-date -f yyyy-MM-dd-HH-mm-ss).jpg"
move-item "$WorkingPath\$File" "$WorkingPath\imported\$FileStamp" -force
#Logging
$SucessCount = $SucessCount +1
$SucessFilesNames += "$Name, "
}
Else{
#Logging
$FailCount = $FailCount +1
$FailedFilesNames += "$Name, "
#Delete Working Image
$FileStamp = "$Name $(get-date -f yyyy-MM-dd-HH-mm-ss).jpg"
move-item "$WorkingPath\$File" "$WorkingPath\failed\$FileStamp" -force
}
}
}
}
End{
#Update Lync Address Book
if ($UpdateAddressBook -eq $TRUE){
write-host "Updating Lync address book..."
Update-CsAddressBook -fqdn $LyncServer
}
else{
write-host "Lync address book NOT set to update"
}
#Logging
Add-Content $Logfile "-------------------------------------------"
Add-Content $Logfile "New job started $(get-date)"
Add-Content $Logfile "Local Path: $WorkingPath"
Add-Content $Logfile "Network Path: $SourcePath"
Add-Content $Logfile "Modified Age: $ModifiedAge"
Add-Content $Logfile "Filter: $TypeFilter"
Add-Content $Logfile "Fixed Dimensions: $WidthPx(w) x $HeightPx(h)"
Add-Content $Logfile "Local Files Found ($LocalFilesCount): $LocalFilesNames"
Add-Content $Logfile "Network Files Found ($NetworkFilesCount): $NetworkFilesNames"
Add-Content $Logfile "Import SUCCESS ($SucessCount): $SucessFilesNames"
Add-Content $Logfile "Import FAILED ($FailCount): $FailedFilesNames"
if ($UpdateAddressBook -eq $TRUE){
Add-Content $Logfile "Lync Address book was updated"
}
else{
Add-Content $Logfile "Lync Address book was NOT updated"
}
if ($SendEmailLog -eq $TRUE){
Add-Content $Logfile "Email log was sent"
}
else{
Add-Content $Logfile "Email log was NOT sent"
}
#Load Email Variables
$EmailFrom = "admin.scripts@nortonrosefulbright.com"
$EmailSubject = "[AUTO] AD Photos Processed $(get-date -f yyyy-MM-dd)"
If ($AllFilesCount -gt 0){
$EmailBody = "An Active Directory photo sync was completed on $(get-date). `
`
$AllFilesCount new photo(s) found for processing (modified since $ModifiedAge). `
`
$SucessCount photo(s) imported sucessfully: $SucessFilesNames `
$FailCount photo(s) NOT imported (file name did not match a user in AD): $FailedFilesNames `
`
Please see the attached log for full details `
`
Regards, `
`
Admin Scripts"
}
else{
$EmailBody = "An Active Directory photo sync was completed on $(get-date). `
`
There were no new photos found in $WorkingPath or $SourcePath (modified since $ModifiedAge). `
`
Regards, `
`
Admin Scripts"
}
#Send Email Log
if ($SendEmailLog -eq $TRUE){
write-host "Sending email log..."
Send-MailMessage -To $EmailTo -Cc $EmailCc -From $EmailFrom -Subject $EmailSubject -SmtpServer $SmtpServer -body $EmailBody -attachment $Logfile
}
else{
write-host $EmailBody
}
}
}
#Load Arguments and call Function
$HelpText = @"
Missing or invalid arguments. Correct syntax is Set-ADPhotos <SourcePath> <Days>
For example .\Set-ADPhotos.ps1 '\\Server1\sharename' 1
"@
if ($args[0] -ne $NULL){
$SourcePath = $args[0]
}
else{
write-host $HelpText
exit
}
if ($args[1] -ne $NULL){
$Days = $args[1]
}
else{
$Days = 1
}
Set-ADPhotos $SourcePath $Days
|
PowerShellCorpus/GithubGist/belotn_6509348_raw_1d2e153ec18e9601311cb3462301600341d0ccbc_get-xaserverrole.ps1
|
belotn_6509348_raw_1d2e153ec18e9601311cb3462301600341d0ccbc_get-xaserverrole.ps1
|
$Branch='LocalMachine'
$SubBranch="SOFTWARE\Wow6432Node\Citrix\IMA\RUNTIME"
get-xaserver | select ServerNAme,@{N="Session-Only";E={
$registry=[microsoft.win32.registrykey]::OpenRemoteBaseKey($branch,$_.servername)
$registrykey=$registry.OpenSubKey($Subbranch)
@{$true="Controller";$false="Worker"}[$registrykey.GetValue("WorkerRole") -eq 0]
}}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.