full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
---|---|---|
PowerShellCorpus/GithubGist/mwjcomputing_5067386_raw_33df560b26bde7fd19fb4b678b7e92fa908da2d3_Get-OracleJavaVersion.ps1
|
mwjcomputing_5067386_raw_33df560b26bde7fd19fb4b678b7e92fa908da2d3_Get-OracleJavaVersion.ps1
|
function Get-OracleJavaVersion {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true)]
[alias("Computer")]
[string]$ComputerName = "$env:COMPUTERNAME"
)
begin{
## Create WMI filter.
$filter = "Name Like 'Java %' AND Vendor='Oracle'"
## Make new object
$obj = New-Object PSObject
}
process{
## Collect information about Java from WMI.
$javaInfo = Get-WmiObject -Class 'Win32_Product' -Filter $filter -ComputerName $ComputerName
## Add information to object
Add-Member -InputObject $obj -MemberType NoteProperty -Name Computer -Value $computerName
Add-Member -InputObject $obj -MemberType NoteProperty -Name Name -Value $javaInfo.Name
Add-Member -InputObject $obj -MemberType NoteProperty -Name Vendor -Value $javaInfo.Vendor
Add-Member -InputObject $obj -MemberType NoteProperty -Name Version -Value $javaInfo.Version
}
end{
## Output object
Write-Output -InputObject $obj
}
<#
.SYNOPSIS
Gets version information about the version of Oracle Java that is installed.
.DESCRIPTION
Uses WMI to get the version information about the version of Oracle Java that is installed.
.PARAMETER ComputerName
The name of the computer to check
.EXAMPLE
PS> Get-OracleJavaVersion -ComputerName DC1
.INPUTS
System.String
.OUTPUTS
PSObject
.NOTES
Written by: Matt Johnson
Email: mwjcomputing [at] gmail [dot] com
.LINK
www.mwjcomputing.com
.LINK
github.com/mwjcomputing
#>
}
|
PowerShellCorpus/GithubGist/HarmJ0y_38c1fabcc5c59118c824_raw_2d45d14e9eb23917d267e7c2199ec68bc05105b5_random.ps1
|
HarmJ0y_38c1fabcc5c59118c824_raw_2d45d14e9eb23917d267e7c2199ec68bc05105b5_random.ps1
|
$megs=1000;$w=New-Object IO.streamWriter $env:temp\data.dat;[char[]]$c='azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789-_';1..$megs|ForEach-Object{1..4|ForEach-Object{$r=$c|Get-Random -Count $c.Count;$s=-join $r;$w.Write($s*4kb);}};
|
PowerShellCorpus/GithubGist/altrive_5124149_raw_37f9e72b8404b43c5628694cdd4eda34c03bd187_Copy-WindowsImageSxS.ps1
|
altrive_5124149_raw_37f9e72b8404b43c5628694cdd4eda34c03bd187_Copy-WindowsImageSxS.ps1
|
<#
.Synopsis
Extract WinSxS data from Windows Image and copy to destination folder
.Description
WinSxS is used to enable Windows features which removed from disk.
In offline environment. Enable feature in ServerCore installation need
WinSxS data that included in full installer image.
WIM extract takes long times operation
so, extract WinSxs and copy to network share and reuse it.
.Parameter MediaPath
ISO Media Image Path or Install Media Drive Root Path E:\
.Parameter WimIndex
Specify Windows Image Index in WIM file.
if you need to enable features in ServerCore OS
you need to select correspod *Full* OS image Index.
* 1: Windows Server 2012 Standard Core
* 2: Windows Server 2012 Standard Full
* 3: Windows Server 2012 Datacenter Core
* 4: Windows Server 2012 Datacenter Full
.Parameter Destination
Target directory to copy WinSxs directory
.Example
$params=@{
MediaPath = [ISO Media Path]
WimIndex = 4 #Windows Server 2012 Datacenter Image Index
Destination = [Copy Destination Path]
}
#Short Path
Copy-WindowsImageSxS @params
#>
function Copy-WindowsImageSxS
{
param(
[Parameter(Mandatory=$true)]
[string]$MediaPath,
[Parameter(Mandatory=$true)]
[int]$WimIndex,
[Parameter(Mandatory=$true)]
[string]$Destination
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
#Create SxS distinaion Directory
if(!(Test-Path $Destination))
{
New-Item -Type Directory -Path $Destination | Out-Null
}
try{
#Mount ISO Image or Resolve Media Drive
if([IO.Path]::GetExtension($MediaPath) -eq ".iso")
{
Mount-DiskImage $MediaPath
$driveLetter = (Get-DiskImage $MediaPath | Get-Volume).DriveLetter
$wimPath= "{0}:\sources\install.wim" -f $driveLetter
}
else
{
$wimPath= Join-Path $MediaPath "sources\install.wim" -Resolve
}
#Create Temp Directory to mount Windows Image
#if use GUID to directorynName, PathTooLongException occuer when call GetChildItem
$tempDir = [IO.Path]::GetTempFileName()
Remove-Item -Path $tempdir
New-Item -Type Directory -Path $tempdir | Out-Null #Create Directory(May Conflict Occured?)
#Mount Windows Image
Write-Verbose "Mounting Windows Image..."
Mount-WindowsImage -Path $tempDir -ImagePath $wimPath -Index $wimIndex -ReadOnly -Verbose:$False | Out-Null
#Copy WinSxS Directory
$fromDir = "$($tempDir)\Windows\WinSxS"
$totalSize = (Get-ChildItem $fromDir -Recurse | Measure-Object -Property Length -Sum).Sum
Write-Verbose ("WinSxs Folder Total Size: {0:N2} GB" -f ($totalSize / 1GB))
Write-Verbose "Executing comand robocopy.exe $fromDir $Destination /S "
Write-Progress -Activity "Copying WinSxS Folder..." -Status "Start Copy" -PercentComplete 0
$job = Start-Job {robocopy.exe $args[0] $args[1] /S | Out-Null} -ArgumentList $fromDir,$Destination
while ($job.State -ne "Completed" )
{
$items = (Get-ChildItem $Destination -Recurse | Measure-Object -Property Length -Sum)
if($items -ne $null)
{
Write-Progress -Activity "Copying WinSxS Folder..." -Status "Copying Files" -PercentComplete (($items.Sum/$totalSize)*100)
}
sleep 5
}
Write-Verbose "Copy Operation Finished"
Write-Progress -Activity "Copying WinSxS Folder..." -Completed
}
finally{
#Cleanup
if([IO.Path]::GetExtension($MediaPath) -eq ".iso"){
Dismount-DiskImage $MediaPath -ErrorAction SilentlyContinue
}
try{
Dismount-WindowsImage -Path $tempDir -Discard -Verbose:$False| Out-Null
Remove-Item -Path $tempDir -ErrorAction SilentlyContinue
}
catch{
$Host.UI.WriteErrorLine("Error occured in cleanup" + $_.Exception)
}
}
}
|
PowerShellCorpus/GithubGist/Stephanvs_a540003a2fdd194b1ac0_raw_73038d08dbda4a78f36447ac701390950f1c160f_Microsoft.PowerShell_profile.ps1
|
Stephanvs_a540003a2fdd194b1ac0_raw_73038d08dbda4a78f36447ac701390950f1c160f_Microsoft.PowerShell_profile.ps1
|
Set-Location $env:userprofile\Source
# Load posh-git example profile
. 'C:\tools\poshgit\dahlbyk-posh-git-c481e5b\profile.example.ps1'
function Set-VsCmd
{
param(
[parameter(Mandatory, HelpMessage="Enter VS version as 2010, 2012, or 2013")]
[ValidateSet(2010,2012,2013)]
[int]$version
)
$VS_VERSION = @{ 2010 = "10.0"; 2012 = "11.0"; 2013 = "12.0" }
$targetDir = "c:\Program Files (x86)\Microsoft Visual Studio $($VS_VERSION[$version])\VC"
if (!(Test-Path (Join-Path $targetDir "vcvarsall.bat"))) {
"Error: Visual Studio $version not installed"
return
}
pushd $targetDir
cmd /c "vcvarsall.bat&set" |
foreach {
if ($_ -match "(.*?)=(.*)") {
Set-Item -force -path "ENV:\$($matches[1])" -value "$($matches[2])"
}
}
popd
write-host "`nVisual Studio $version Command Prompt variables set." -ForegroundColor Yellow
}
Set-VsCmd 2013
|
PowerShellCorpus/GithubGist/vgrem_34d0e65b0732a1b368ce_raw_c339f80bcbd6fdad3619674b0b0bd555d144fccd_Invoke-LoadMethodV2.ps1
|
vgrem_34d0e65b0732a1b368ce_raw_c339f80bcbd6fdad3619674b0b0bd555d144fccd_Invoke-LoadMethodV2.ps1
|
Function Invoke-LoadMethodV2() {
param(
$Context = $(throw "Please provide an Client Context"),
$Object = $(throw "Please provide an Client Object instance on which to invoke the generic method")
)
$load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load")
$type = $Object.GetType()
$clientObjectLoad = $load.MakeGenericMethod($type)
$clientObjectLoad.Invoke($Context,@($Object,$null))
}
|
PowerShellCorpus/GithubGist/onyxhat_650121af37bcb4fefe71_raw_f352888235506896e24f6ba37a2515eb0e310ff3_Update-Windows.ps1
|
onyxhat_650121af37bcb4fefe71_raw_f352888235506896e24f6ba37a2515eb0e310ff3_Update-Windows.ps1
|
$Host.UI.RawUI.WindowTitle = "-=Windows Update=-"
$Script = $MyInvocation.MyCommand.Definition
Write-Host -NoNewline "Checking for Updates..."
$UpdateSession = New-Object -Com Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$SearchResult = $UpdateSearcher.Search("IsInstalled=0 and Type='Software'")
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++) {
$Update = $SearchResult.Updates.Item($X)
}
If ($SearchResult.Updates.Count -eq 0) {
Write-Host "NONE!"
Exit
}
Write-Host "DONE!"
$UpdatesToDownload = New-Object -Com Microsoft.Update.UpdateColl
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++) {
$Update = $SearchResult.Updates.Item($X)
$Null = $UpdatesToDownload.Add($Update)
}
Write-Host -NoNewline "Downloading Updates..."
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Null = $Downloader.Download()
$UpdatesToInstall = New-Object -Com Microsoft.Update.UpdateColl
For ($X = 0; $X -lt $SearchResult.Updates.Count; $X++) {
$Update = $SearchResult.Updates.Item($X)
If ($Update.IsDownloaded) {
$Null = $UpdatesToInstall.Add($Update)
}
}
Write-Host "DONE!"
Write-Host -NoNewline "Installing Updates..."
$Installer = $UpdateSession.CreateUpdateInstaller()
$Installer.Updates = $UpdatesToInstall
$InstallationResult = $Installer.Install()
Write-Host "DONE!"
If ($InstallationResult.RebootRequired -eq $True) {
Copy-Item -Path $Script -Destination ($env:SystemDrive + "\") -Force | Out-Null
New-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce -Name "WSUS" -Value "$PSHOME\powershell.exe -Command `"& $($env:SystemDrive + "\" + (Split-Path -Leaf $Script))`"" | Out-Null
}
Add-Content (Join-Path (Split-Path $Script -Parent) "updates.log") $("Date: " + $(Get-Date) + " --- Updates: " + $UpdatesToInstall.Count)
|
PowerShellCorpus/GithubGist/SyntaxC4_8776866_raw_e0434c6089176715ea9b3b9a3f8bd595ecb46078_Microsoft.PowerShell_profile.ps1
|
SyntaxC4_8776866_raw_e0434c6089176715ea9b3b9a3f8bd595ecb46078_Microsoft.PowerShell_profile.ps1
|
# It's your choice if you want to enter the code and press the button.
# >: 4 8 15 16 23 42
function prompt {
write-host '>:' -nonewline
return ' '
}
|
PowerShellCorpus/GithubGist/ao-zkn_de13466be8f1c1e849ea_raw_673c2af1bd6c0606121a97f8287099abe1e83642_Replace-FileName.ps1
|
ao-zkn_de13466be8f1c1e849ea_raw_673c2af1bd6c0606121a97f8287099abe1e83642_Replace-FileName.ps1
|
# ------------------------------------------------------------------
# ファイル名を置換する
# 関数名:Replace-FileName
# 引数 :FilePath ファイル名を置換するファイルパス
# :Befor 置換前
# :After 置換後
# 戻り値:なし
# ------------------------------------------------------------------
function Replace-FileName([String]$FilePath, [String]$Befor, [String]$After){
if(Test-Path -LiteralPath $FilePath -PathType Leaf){
$fileInfo = Get-ChildItem -LiteralPath $FilePath
# 置換対象が存在する場合
if($fileInfo.BaseName -match $Befor){
# 置換
$newFileName = ($fileInfo.BaseName -replace $Befor,$After) + $fileInfo.Extension
$newFilePath = Join-Path -Path (Split-Path $FilePath -Parent) -ChildPath $NewFileName
Move-Item -LiteralPath $FilePath -Destination $newFilePath
}
}else{
Write-Host "ファイルが存在しません。ファイル名[ $FilePath ]"
}
}
|
PowerShellCorpus/GithubGist/konkked_914998828afea8746dff_raw_5d74b79b278147c79b5255079da110359fafea44_touch.ps1
|
konkked_914998828afea8746dff_raw_5d74b79b278147c79b5255079da110359fafea44_touch.ps1
|
Function Scaffold ( $path , $type )
{
If( !(Test-Path $path) ) {
New-Item $path -Type $type -Force
}
}
Function Scaffold-Silent( $path , $type)
{
Scaffold $path $type > $null
}
Function Scaffold-File($path)
{
Scaffold $path File
}
Function Scaffold-Directory($path)
{
Scaffold $path Directory
}
Function Scaffold-Silent-File($path)
{
Scaffold $path File > $null
}
Function Scaffold-Silent-Directory($path)
{
Scaffold $path Directory > $null
}
Function Scaffold-All()
{
Foreach( $val in $args )
{
Scaffold-File $val
}
}
Function Scaffold-All-File()
{
Foreach( $val in $args )
{
Scaffold-File $val
}
}
Function Scaffold-All-Directory()
{
Foreach( $val in $args )
{
Scaffold-Directory $val
}
}
Function Scaffold-Silent-All-File()
{
Foreach( $val in $args )
{
Scaffold-Silent-File $val > $null
}
}
Function Scaffold-Silent-All-Directory()
{
Foreach( $val in $args )
{
Scaffold-Silent-File $val > $null
}
}
Function Scaffold-Silent-All()
{
Foreach($val in $args)
{
Scaffold-Silent-Directory $val 2> $null
}
}
Set-Alias touch Scaffold-Silent-All-File
Set-Alias touchd Scaffold-Silent-All-Directory
|
PowerShellCorpus/GithubGist/johnmeilleur_e5f49aa3aa8033ae5b11_raw_537f0bb92b3cc8c367ca1ca3e718166c231a4195_CheckInAndPublishAllContent.ps1
|
johnmeilleur_e5f49aa3aa8033ae5b11_raw_537f0bb92b3cc8c367ca1ca3e718166c231a4195_CheckInAndPublishAllContent.ps1
|
Param($siteUrl)
# This script ensures all of the publishing pages are checked in.
$site = Get-SPSite $siteUrl
foreach ($web in $site.AllWebs) {
$publishingWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$publishingPages = $publishingWeb.GetPublishingPages()
foreach ($publishingPage in $publishingPages) {
if ($publishingPage.ListItem.File.CheckOutStatus -ne "None") {
Write-Output "[PAGE] $($web.Title) > $($publishingPage.ListItem.Title) was checked out."
$publishingPage.CheckIn("")
} else {
#Write-Output "[PAGE] $($web.Title) > $($publishingPage.ListItem.Title) was already checked in."
}
if ($publishingPage.ListItem.File.MinorVersion -ne 0) {
$publishingPage.ListItem.File.Publish("")
Write-Output "[PAGE] $($web.Title) > $($publishingPage.ListItem.Title) is now published."
}
}
if ($web.Lists["Master Page Gallery"] -ne $null) {
$list = $web.Lists["Master Page Gallery"]
foreach ($item in $list.Items) {
if ($item.File.CheckOutStatus -ne "None") {
Write-Output "[MASTER PAGE GALLERY] $($web.Title) > $($item.Name) was checked out."
$item.File.CheckIn("")
} else {
#Write-Output "[MASTER PAGE GALLERY] $($web.Title) > $($item.Name) was already checked in."
}
if ($item.File.MinorVersion -ne 0 -and $item.File.Name -notlike "*.js") {
$item.File.Publish("")
Write-Output "[MASTER PAGE GALLERY] $($web.Title) > $($item.Name) is now published."
}
}
}
if ($web.Lists["Style Library"] -ne $null) {
$list = $web.Lists["Style Library"]
foreach ($item in $list.Items) {
if ($item.File.CheckOutStatus -ne "None") {
Write-Output "[STYLE LIBRARY] $($web.Title) > $($item.Name) was checked out."
$item.File.CheckIn("")
} else {
#Write-Output "[STYLE LIBRARY] $($web.Title) > $($item.Name) was already checked in."
}
if ($item.File.MinorVersion -ne 0) {
$item.File.Publish("")
Write-Output "[PAGE] $($web.Title) > $($item.Name) is now published."
}
}
}
if ($web.Lists["Images"] -ne $null) {
$list = $web.Lists["Images"]
foreach ($item in $list.Items) {
if ($item.File.CheckOutStatus -ne "None") {
Write-Output "[IMAGES] $($web.Title) > $($item.Name) was checked out."
$item.File.CheckIn("")
} else {
#Write-Output "[IMAGES] $($web.Title) > $($item.Name) was already checked in."
}
if ($item.File.MinorVersion -ne 0) {
$item.File.Publish("")
Write-Output "[IMAGES] $($web.Title) > $($item.Name) is now published."
}
}
}
if ($web.Lists["Documents"] -ne $null) {
$list = $web.Lists["Documents"]
foreach ($item in $list.Items) {
if ($item.File.CheckOutStatus -ne "None") {
Write-Output "[DOCUMENTS] $($web.Title) > $($item.Name) was checked out."
$item.File.CheckIn("")
} else {
#Write-Output "[DOCUMENTS] $($web.Title) > $($item.Name) was already checked in."
}
if ($item.File.MinorVersion -ne 0) {
$item.File.Publish("")
Write-Output "[DOCUMENTS] $($web.Title) > $($item.Name) is now published."
}
}
}
}
|
PowerShellCorpus/GithubGist/zachbonham_4774553_raw_67f3db1d1004fe498f16608bff5493760f43d438_retry.ps1
|
zachbonham_4774553_raw_67f3db1d1004fe498f16608bff5493760f43d438_retry.ps1
|
# complete rip off of http://blog.mirthlab.com/2012/05/25/cleanly-retrying-blocks-of-code-after-an-exception-in-ruby/
#
# usage
# retriable -tries 5 -action { do-work-that-could-throw-exception }
#
function retriable($tries=3, $interval=1, [scriptblock]$action)
{
$retry_count = 1
$the_exception = $null
do
{
$is_error = $false
try
{
& $action
# reset in case it worked this last try
#
$is_error = $false
}
catch
{
#cache off exception to throw if we've exhausted our retries
#
$the_exception = $_
$is_error = $true
write-debug "[retriable] caught exception"
write-debug "[retriable] attempt $retry_count of $tries failed, trying again"
if ( $retry_count -ge $tries )
{
write-debug "[retriable] exhausted $retry_count retry attempts"
}
else
{
write-debug "[retriable] waiting $interval seconds"
sleep -seconds $interval
}
}
$retry_count = $retry_count + 1
} while($is_error -eq $true -and $retry_count -le $tries)
if ( $is_error )
{
throw $the_exception
}
}
|
PowerShellCorpus/GithubGist/jnsn_7dab1fbe99f1cf719097_raw_fafb72b4e038b2aa80602f66bf25e356d9661c9b_gistfile1.ps1
|
jnsn_7dab1fbe99f1cf719097_raw_fafb72b4e038b2aa80602f66bf25e356d9661c9b_gistfile1.ps1
|
$subscription = "[Your Subscription Name]"
$service = "[Your Azure Service Name]"
$slot = "staging" #staging or production
$package = "[ProjectName]\bin\[BuildConfigName]\app.publish\[ProjectName].cspkg"
$configuration = "[ProjectName]\bin\[BuildConfigName]\app.publish\ServiceConfiguration.Cloud.cscfg"
$timeStampFormat = "g"
$deploymentLabel = "ContinuousDeploy to $service v%build.number%"
Write-Output "Running Azure Imports"
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\*.psd1"
Import-AzurePublishSettingsFile "C:\TeamCity\[PSFileName].publishsettings"
Set-AzureSubscription -CurrentStorageAccount $service -SubscriptionName $subscription
function Publish(){
$deployment = Get-AzureDeployment -ServiceName $service -Slot $slot -ErrorVariable a -ErrorAction silentlycontinue
if ($a[0] -ne $null) {
Write-Output "$(Get-Date -f $timeStampFormat) - No deployment is detected. Creating a new deployment. "
}
if ($deployment.Name -ne $null) {
#Update deployment inplace (usually faster, cheaper, won't destroy VIP)
Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment."
UpgradeDeployment
} else {
CreateNewDeployment
}
}
function CreateNewDeployment()
{
write-progress -id 3 -activity "Creating New Deployment" -Status "In progress"
Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: In progress"
$opstat = New-AzureDeployment -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service
$completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot
$completeDeploymentID = $completeDeployment.deploymentid
write-progress -id 3 -activity "Creating New Deployment" -completed -Status "Complete"
Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: Complete, Deployment ID: $completeDeploymentID"
}
function UpgradeDeployment()
{
write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress"
Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: In progress"
# perform Update-Deployment
$setdeployment = Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -ServiceName $service -Force
$completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot
$completeDeploymentID = $completeDeployment.deploymentid
write-progress -id 3 -activity "Upgrading Deployment" -completed -Status "Complete"
Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: Complete, Deployment ID: $completeDeploymentID"
}
Write-Output "Create Azure Deployment"
Publish
|
PowerShellCorpus/GithubGist/belotn_6867616_raw_f1826a5fb29fa88112bab6b0c2afe0164c405449_get-RequiredGpoStatus.ps1
|
belotn_6867616_raw_f1826a5fb29fa88112bab6b0c2afe0164c405449_get-RequiredGpoStatus.ps1
|
Get-ADOrganizationalUnit -Filter 'OU -like "*Citrix*"' -SearchBase 'dc=fabricam,dc=com' -Properties * |% {
$_.gpLink -split ']' } |? {
$_ -match '[0,2]$'} |% {
(($_ -replace '\[','').split(';')[0]) -replace 'LDAP://',''} |% {
get-adobject $_ -properties * } |
sort -Unique DisplayName |
select DisplayName,flags,@{N='flagsRecommended';E={
if([bool]( gci "$($_.gPCFileSysPath)\User") -eq $false){
if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){
3
}else{
1
}
}else {
if([bool](gci "$($_.gPCFileSysPath)\Machine") -eq $false){
2
}ELSE{
0
}
}
} }
|
PowerShellCorpus/GithubGist/glallen01_5624949_raw_442deda43d5dd25185bfb58bbedf61acb0052a49_reserve_dhcp.ps1
|
glallen01_5624949_raw_442deda43d5dd25185bfb58bbedf61acb0052a49_reserve_dhcp.ps1
|
$DHCPserver="172.16.32.2"
$DHCPscope="10.0.0.0"
$output="C:\netsh-out.cmd"
$csv=Import-CSV "MAC_LIST.csv"
# csv file MUST have the following header columns
# MAC,IP,NAME
# 12345678abcd,10.0.0.20,SITEWKCDR01
$csv | %{
add-content -Encoding ASCII -Path $output
-Value "netsh dhcp server $DHCPserver scope $DHCPscope `
add reservedip $($_.IP) $($_.MAC) $($_.NAME) $($_.NAME) BOTH"
}
# this script takes "MAC_LIST.csv" as input, and creates
# "netsh-out.cmd" as output. Run the "netsh-out.cmd" script
# to create reservations.
|
PowerShellCorpus/GithubGist/jrotello_3812564_raw_88b4ea3525df45176f1895feb531a300dbab3a63_DownloadTRWallpapers.ps1
|
jrotello_3812564_raw_88b4ea3525df45176f1895feb531a300dbab3a63_DownloadTRWallpapers.ps1
|
param(
[string[]]$targetDirectories = $(throw "targetDirectories parameter is required"),
[string]$size = "1920x1280"
)
function getUrl ($imageNumber) {
$monthNumber =[System.DateTime]::Today.Month
$monthName = [System.Globalization.DateTimeFormatInfo]::InvariantInfo.GetAbbreviatedMonthName($monthNumber).ToLower()
$imageId = 4 * ($monthNumber - 1) + $imageNumber
$urlFormat = "http://ecalendar.thomsonreuters.com/download.asp?size={0}&mo={1}&id={2}"
return [String]::Format($urlFormat, $size, $monthName, $imageId)
}
function downloadWallpaper($url, $path) {
"Downloading $url to $path"
$webclient = New-Object System.Net.WebClient
$webclient.DownloadFile($url, "$path")
}
1..4 | % {
$url = getUrl $_
$filename = [string]::Format("tr_{0}.jpg", $_-1)
$targetDirectories | % {
downloadWallpaper $url "$_\$filename"
}
}
|
PowerShellCorpus/GithubGist/gravejester_f44543e603e776f2304a_raw_3b3d548affae65d6f5901784b33678960151262d_Out-CapitalizedString.ps1
|
gravejester_f44543e603e776f2304a_raw_3b3d548affae65d6f5901784b33678960151262d_Out-CapitalizedString.ps1
|
function Out-CapitalizedString {
param([string]$String)
if(-not([System.String]::IsNullOrEmpty($String))) {
foreach ($sentence in ($String.Split('.'))) {
if(-not([System.String]::IsNullOrEmpty($sentence))) {
$sentence = $sentence.Trim()
[array]$outputString += [char]::ToUpper($sentence[0]) + $sentence.Substring(1)
}
else {
[array]$outputString += $sentence
}
}
Write-Output ($outputString -join '. ').Trim()
}
}
|
PowerShellCorpus/GithubGist/guitarrapc_de79bffe9f19104efc8c_raw_7f417647972ceb00377d7a072fe4e4d6ec87ba69_New-ZipCompress.ps1
|
guitarrapc_de79bffe9f19104efc8c_raw_7f417647972ceb00377d7a072fe4e4d6ec87ba69_New-ZipCompress.ps1
|
function New-ZipCompress
{
[CmdletBinding(DefaultParameterSetName="safe")]
param(
[parameter(
mandatory,
position = 0,
valuefrompipeline,
valuefrompipelinebypropertyname)]
[string]
$source,
[parameter(
mandatory = 0,
position = 1,
valuefrompipeline,
valuefrompipelinebypropertyname)]
[string]
$destination,
[parameter(
mandatory = 0,
position = 2)]
[switch]
$quiet,
[parameter(
mandatory = 0,
position = 3,
ParameterSetName="safe")]
[switch]
$safe,
[parameter(
mandatory = 0,
position = 3,
ParameterSetName="force")]
[switch]
$force
)
begin
{
# only run with Verbose mode
if ($PSBoundParameters.Verbose.IsPresent)
{
# start Stopwatch
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$starttime = Get-Date
}
Write-Debug "import .NET Class for ZipFile"
try
{
Add-Type -AssemblyName "System.IO.Compression.FileSystem"
}
catch
{
}
}
process
{
Write-Verbose "check source is file or Directory."
$file = Get-Item -Path $source
Write-Debug 'Another check source is "file/directory" or "contains PSISContainer'
if ($file.PSISContainer -and ($file.count -gt 1) -and ($source[-1] -eq "*"))
{
Write-Verbose "Detected as source using * without extension."
$oldsource = $source
$f = Get-Item -Path $source | select -First 1
$source = Split-Path -Path $f -Parent
$file = Get-Item -Path $source
Write-Verbose ("changed source {0} to parent folder {1}." -f $oldsource, $source)
}
# set zip extension
$zipExtension = ".zip"
Write-Debug ("set desktop as destination path destination {0} is null" -f $destination)
if ([string]::IsNullOrWhiteSpace($destination))
{
$desktop = [System.Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop)
if ($file.PSISContainer -and ($file.count -eq 1))
{
Write-Verbose "Detected as Directory"
if ($file.FullName -eq $file.Root)
{
$filename = $file.PSDrive.Name
}
else
{
# remove \ or / on last letter of source
$fullpath = Join-Path (Split-Path -Path $file -Parent) (Split-Path -Path $file -Leaf)
$filename = [System.IO.Path]::GetFileName($fullpath)
}
Write-Verbose ("Desktop : {0}" -f $desktop)
Write-Verbose ("GetFileName : {0}" -f $filename)
Write-Verbose ("zipExtension : {0}" -f $zipExtension)
$destination = Join-Path $desktop ($filename + $zipExtension)
}
elseif ($file.PSISContainer -and ($file.count -gt 1) -and ($source[-1] -eq "*"))
{
Write-Verbose "Detected as source which use * without extension"
Write-Verbose "create zip from parent directory when last letter of source was wildcard *"
$filename = ([System.IO.Path]::GetFileNameWithoutExtension($file.FullName))
Write-Verbose ("Desktop : {0}" -f $desktop)
Write-Verbose ("GetFileName : {0}" -f $filename)
Write-Verbose ("zipExtension : {0}" -f $zipExtension)
$destination = Join-Path $desktop ($filename + $zipExtension)
}
else
{
Write-Verbose "Detected as File"
# use first file name as zip name
$filename = ([System.IO.Path]::GetFileNameWithoutExtension(($file | select -First 1 -ExpandProperty fullname)))
Write-Verbose ("Desktop : {0}" -f $desktop)
Write-Verbose ("GetFileName : {0}" -f ([System.IO.Path]::GetFileNameWithoutExtension(($file | select -First 1 -ExpandProperty fullname))))
Write-Verbose ("zipExtension : {0}" -f $zipExtension)
$destination = Join-Path $desktop ($filename + $zipExtension)
}
}
Write-Debug "check destination is input as .zip"
if (-not($destination.EndsWith($zipExtension)))
{
throw ("destination parameter value [{0}] not end with extension {1}" -f $destination, $zipExtension)
}
Write-Debug "check destination is already exist, CreateFromDirectory Method will fail with same name of destination file."
if (Test-Path $destination)
{
if ($safe)
{
Write-Debug "safe output zip file to new destination path, avoiding destination zip name conflict."
# show warning for same destination exist.
Write-Verbose ("Detected destination name {0} is already exist." -f $destination)
$olddestination = $destination
# get current destination information
$destinationRoot = [System.IO.Path]::GetDirectoryName($destination)
$destinationfile = [System.IO.Path]::GetFileNameWithoutExtension($destination)
$destinationExtension = [System.IO.Path]::GetExtension($destination)
# renew destination name with (2)...(x) until no more same name catch.
$count = 2
$destination = Join-Path $destinationRoot ($destinationfile + "(" + $count + ")" + $destinationExtension)
while (Test-Path $destination)
{
++$count
$destination = Join-Path $destinationRoot ($destinationfile + "(" + $count + ")" + $destinationExtension)
}
# show warning as destination name had been changed due to escape error.
Write-Warning ("Safe old deistination {0} change to new name {1}" -f $olddestination, $destination)
}
else
{
if($force)
{
Write-Warning ("force replacing old zip file {0}" -f $destination)
Remove-Item -Path $destination -Force
}
else
{
Remove-Item -Path $destination -Confirm
}
if (Test-Path $destination)
{
Write-Warning "Cancelled removing item. Quit cmdlet execution."
return
}
}
}
else
{
Write-Debug ("Destination not found. Check parent folder for destination {0} is exist." -f $destination)
$parentpath = Split-Path $destination -Parent
if (-not(Test-Path $parentpath))
{
Write-Warning ("Parent folder {0} not found. Creating path." -f $parentpath)
New-Item -Path $parentpath -ItemType Directory -Force
}
}
# compressionLevel
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
# show file property
Write-Verbose ("file.PSISContainer : {0}" -f $file.PSISContainer)
Write-Verbose ("file.count : {0}" -f $file.count)
Write-Debug "execute compression"
if ($file.PSISContainer -and ($file.count -eq 1))
{
try # create zip from directory
{
# include BaseDirectory
$includeBaseDirectory = $true
Write-Verbose "Detected as Directory"
Write-Verbose ("destination : {0}" -f $destination)
Write-Verbose ("file.fullname : {0}" -f $file.FullName)
Write-Verbose ("compressionLevel : {0}" -f $compressionLevel)
Write-Verbose ("includeBaseDirectory : {0}" -f $includeBaseDirectory)
if ($quiet)
{
Write-Verbose ("zipping up folder {0} to {1}" -f $file.FullName, $destination)
[System.IO.Compression.ZipFile]::CreateFromDirectory($file.fullname,$destination,$compressionLevel,$includeBaseDirectory) > $null
$?
}
else
{
Write-Verbose ("zipping up folder {0} to {1}" -f $file.FullName, $destination)
[System.IO.Compression.ZipFile]::CreateFromDirectory($file.fullname,$destination,$compressionLevel,$includeBaseDirectory)
Get-Item $destination
}
}
catch
{
Write-Error $_
$?
}
}
elseif ($file.PSISContainer -and ($file.count -gt 1) -and ($source[-1] -eq "*"))
{
try # create zip from directory when last letter of source was wildcard *
{
# include BaseDirectory
$includeBaseDirectory = $true
Write-Verbose "Detected as source which use * without extension"
Write-Verbose ("destination : {0}" -f $destination)
Write-Verbose ("file.fullname : {0}" -f $file.FullName)
Write-Verbose ("compressionLevel : {0}" -f $compressionLevel)
Write-Verbose ("includeBaseDirectory : {0}" -f $includeBaseDirectory)
if ($quiet)
{
Write-Verbose ("zipping up folder {0} to {1}" -f $file.FullName, $destination)
[System.IO.Compression.ZipFile]::CreateFromDirectory($file.FullName,$destination,$compressionLevel,$includeBaseDirectory) > $null
$?
}
else
{
Write-Verbose ("zipping up folder {0} to {1}" -f $file.FullName, $destination)
[System.IO.Compression.ZipFile]::CreateFromDirectory($file.FullName,$destination,$compressionLevel,$includeBaseDirectory)
Get-Item $destination
}
}
catch
{
Write-Error $_
$?
}
}
else
{
try # create zip from files
{
# create zip to add
$destzip = [System.IO.Compression.Zipfile]::Open($destination,"Update")
# get items
$files = Get-ChildItem -Path $source
foreach ($file in $files)
{
Write-Verbose "Detected as File"
Write-Verbose ("destzip : {0}" -f $destzip)
Write-Verbose ("file.fullname : {0}" -f $file.FullName)
Write-Verbose ("file.name : {0}" -f $file2)
Write-Verbose ("compressionLevel : {0}" -f $compressionLevel)
Write-Verbose ("zipping up files {0} to {1}" -f $file.FullName, $destzip)
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($destzip, $file.FullName, $file.Name, $compressionLevel) > $null
}
# show result
if ($quiet)
{
$?
}
else
{
Get-Item $destination
}
}
catch
{
Write-Error $_
$?
}
finally
{
Write-Debug ("Dispose Object {0} to remove file handler." -f $sourcezip)
$destzip.Dispose()
}
}
}
end
{
# only run with Verbose mode
if ($PSBoundParameters.Verbose.IsPresent)
{
# end Stopwatch
$endsw = $sw.Elapsed.TotalMilliseconds
$endtime = Get-Date
Write-Verbose ("Start time`t: {0:o}" -f $starttime)
Write-Verbose ("End time`t: {0:o}" -f $endtime)
Write-Verbose ("Duration`t: {0} ms" -f $endsw)
}
}
}
|
PowerShellCorpus/GithubGist/harrybiscuit_1877081_raw_dc408d1ad455804023e3c38d5284be725b318ea0_CreateJunction.ps1
|
harrybiscuit_1877081_raw_dc408d1ad455804023e3c38d5284be725b318ea0_CreateJunction.ps1
|
$junctionPath = ".\junction.exe"
$toBeCreated = "c:\MyNewJunction";
if(!(Test-Path $junctionPath)){
Write-Host "Expected Junction.exe to be in the same folder as this script file. This file is required to create the new junction."
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
exit
}
Write-Host "Found junction.exe"
Write-Host "Enter the full path to the existing folder to which we will point the junction"
Write-Host "For example D:\My\Existing\Folder"
$existingPath = Read-Host "Path --> "
& $junctionPath $toBeCreated, $existingPath
Write-Host "Press any key to finish ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
PowerShellCorpus/GithubGist/guitarrapc_c2136dc0cb6a15f721bc_raw_b0ad519a442801269acaa803be538d7764316add_TypeSuccessfullyPassed.ps1
|
guitarrapc_c2136dc0cb6a15f721bc_raw_b0ad519a442801269acaa803be538d7764316add_TypeSuccessfullyPassed.ps1
|
fuga | %{$_} # Now you'll see Intellisence work when you type $_.
|
PowerShellCorpus/GithubGist/zippy1981_1576084_raw_e290558724287f936b6ee726781b0f6a1613688f_mstsc-Ac.ps1
|
zippy1981_1576084_raw_e290558724287f936b6ee726781b0f6a1613688f_mstsc-Ac.ps1
|
<#
.SYNOPSIS
mstsc-Ac.ps1 (Version 1.0, 7 Jan 2012)
The author may be contacted via [email protected]
The latest authoritative version of this script is always available at
http://bit.ly/mstsc-Ac
.DESCRIPTION
This script will see if a host is up and listening on a given port, and start a
remote desktop connection to it. The idea is you run this script after rebooting a windows server
.EXAMPLE
.\mstsc-Ac.ps1 192.168.0.2
Starts an RDP connection on 192.168.0.2
.EXAMPLE
.\mstsc-Ac.ps1 192.168.0.2 3390
Starts an RDP connection on 192.168.0.2 port 3390 .
.EXAMPLE
mstsc-Ac.ps1 192.168.0.2 -AdditionalParameters "/w:1000 /h:500"
Starts an RDP connection on 192.168.0.2 with a width of 1000 pixels and a height of 500 pixels.
.Notes
Copyright (c) 2012 Justin Dearing
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*****************************************************************************
NOTE: YOU MAY *ALSO* DISTRIBUTE THIS FILE UNDER ANY OF THE FOLLOWING...
PERMISSIVE LICENSES:
BSD: http://www.opensource.org/licenses/bsd-license.php
MIT: http://www.opensource.org/licenses/mit-license.html
RECIPROCAL LICENSES:
GPL 2: http://www.gnu.org/copyleft/gpl.html
*****************************************************************************
LASTLY: THIS IS NOT LICENSED UNDER GPL v3 (although the above are compatible)
#>
param(
[string] $HostOrIpAddress = "",
[int] $Port = 3389,
[string] $AdditionalParameters = "/f"
)
# TODO: It seems you can't specify the user name and password on the command line
<#
[string] $userName = $(Read-Host -Prompt "Username"),
[string] $password = $(
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR(
(Read-Host -Prompt "Password" -AsSecureString)
)
)
#>
if ([String]::IsNullOrEmpty($HostOrIpAddress)) {
# This is the first value in the drop down list of the remote desktop client
$lastHost = (Get-ItemProperty 'HKCU:\Software\Microsoft\Terminal Server Client\Default' 'MRU0').MRU0
$hostInput = (Read-Host -Prompt "Host (Default $($lastHost))").Split(':')
if ([String]::IsNullOrEmpty($hostInput)) { $hostInput = $lastHost }
$HostOrIpAddress = $hostInput[0];
if ($host.Length -gt 1) { $Port = $hostInput[1] }
}
$pingTimeout = 1000 # ping timeout in milllliseconds
$successfulConsecutivePingCount = 5
$sleepTime = 5 # Time to sleep in seconds
$ping = New-Object System.Net.NetworkInformation.Ping
$rdpPortListening = $false;
# Were looking for 5 consecutive pings that don't time out.
# Then were going to try to connect to the remote desktop port
while (-not $rdpPortListening) {
for ($i = 0; $i -lt $successfulConsecutivePingCount; $i++) {
$result = $ping.Send($HostOrIpAddress, $pingTimeout);
if ($result.Status -eq 'Success') {
Write-Host "Reply from $($result.Address) Round Trip Time $($result.RoundTripTime)"
} else {
Write-Host "Request Timed out. Sleeping for $($sleepTime) seconds."
$i = 0;
Start-Sleep $sleepTime
}
#$ping.Send('74.125.115.107', 500);
}
try {
$socket = New-Object Net.Sockets.TcpClient($HostOrIpAddress, $Port)
if ($socket.Connected) {
$rdpPortListening = $true
Write-Host "RDP Service appears to be up"
}
$socket.Close()
}
catch [System.Management.Automation.MethodInvocationException] {
if ($_.Exception.InnerException.GetType() -eq [System.Net.Sockets.SocketException]) {
Write-Host $_.Exception.InnerException.Message
Start-Sleep $sleepTime
}
else {
throw $_.Exception.InnerException
}
}
}
Invoke-Expression "mstsc /v $($HostOrIpAddress):$($Port) $($AdditionalParameters)"
|
PowerShellCorpus/GithubGist/jen20_11290410_raw_c3e177f0f8d48bfa3168785f068279ee9a6162b1_pin-vs.ps1
|
jen20_11290410_raw_c3e177f0f8d48bfa3168785f068279ee9a6162b1_pin-vs.ps1
|
$shell = new-object -com "Shell.Application"
$dir = $shell.Namespace("C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE")
$item = $dir.ParseName("devenv.exe")
$item.InvokeVerb('taskbarpin')
|
PowerShellCorpus/GithubGist/binamov_6499320_raw_9692799b4ac53aac29d819ca77036bc5f25ea237_user_data.ps1
|
binamov_6499320_raw_9692799b4ac53aac29d819ca77036bc5f25ea237_user_data.ps1
|
<powershell>
#####
#DON'T FORGET TO SET/CHANGE THE USERNAME/PASSWORD BELOW!
#####
$user="chef"
$password="chef"
# Disable password complexity requirements
$seccfg = [IO.Path]::GetTempFileName()
secedit /export /cfg $seccfg
(Get-Content $seccfg) | Foreach-Object {$_ -replace "PasswordComplexity\s*=\s*1", "PasswordComplexity=0"} | Set-Content $seccfg
secedit /configure /db $env:windir\security\new.sdb /cfg $seccfg /areas SECURITYPOLICY
del $seccfg
# Create a user with her password, add to Admin group
net user /add $user $password;
net localgroup Administrators /add $user;
# These commands are necessary only if the target machine is being
# used as a Chef node and you want to bootstrap it. They do not need
# to appear on a "workstation" machine.
#
# Get the instance ready for Chef bootstrapper
winrm quickconfig -q
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="512"}'
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" profile=public protocol=tcp localport=5985 remoteip=localsubnet new remoteip=any
</powershell>
|
PowerShellCorpus/GithubGist/wpsmith_4190b9a03bc1544a7df5_raw_da4700a0b3fb2cf5decfabba42e7e439f860e26e_self-elevating-script.ps1
|
wpsmith_4190b9a03bc1544a7df5_raw_da4700a0b3fb2cf5decfabba42e7e439f860e26e_self-elevating-script.ps1
|
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
clear-host
}
else
{
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
# Run your code that needs to be elevated here
Write-Host -NoNewLine "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
|
PowerShellCorpus/GithubGist/meganehouser_8619643_raw_bf0584e71ef4ac1e1ca3d9f693a828d794492b14_CopyZip.ps1
|
meganehouser_8619643_raw_bf0584e71ef4ac1e1ca3d9f693a828d794492b14_CopyZip.ps1
|
### 使い方
### 1. PowerShellを起動する
### 2. PowerShell 実行権限の変更(最初の一回のみ実行)
### Set-ExecutionPolicy RemoteSigned
### 3. 7z をインストール(インストールしたフォルダ内に7z.exeがある)
### http://sevenzip.sourceforge.jp/download.html
### 4. このスクリプトをCopyZip.ps1というファイル名で実行
### 5. コピー元のフォルダパス、コピー先・ZIPファイル作成先のフォルダパス、7z.exeのパスを書き換える
### 6. PowerShellでカレントディレクトリをCopyZip.ps1を置いたディレクトリに移動
### 7. 以下のコマンドを実行
### .\CopyZip.ps1
# コピー元のフォルダパス
$sourceFolder = 'C:\source'
# コピー先・ZIPファイル作成先のフォルダパス
$destFolder = 'C:\dest'
# 7z.exeのパス
$zipExe = 'C:\Program Files (x86)\7-Zip\7z.exe'
# コピー先一時フォルダ
$tempFolder = Join-Path $destFolder $(Get-Date).ToString("yyyyMMdd")
New-Item -Path $tempFolder -ItemType Directory -Force
# コピー元からコピー先にコピーを行う
Copy-Item $sourceFolder $tempFolder -recurse -Force
# コピー先から空のフォルダを削除する
Get-ChildItem -Path $tempFolder -Recurse | Where-Object {$_.PSIsContainer -and !$_.GetFiles().Count -and !$_.GetDirectories().Count} | Remove-Item -Force
# ZIP圧縮
$destZipFolder = Join-Path $destFolder ($(Get-Date).ToString("yyyyMMdd") + "_" + (Split-Path $sourceFolder -Leaf))
cmd /c $zipExe a -tzip $destZipFolder $tempFolder
# 一時フォルダ削除
Remove-Item -Path $tempFolder -Recurse
|
PowerShellCorpus/GithubGist/n-fukuju_8487265_raw_ee0206d054b67e93c8271d51e4a8ff7e420c4ffa_assignletter.ps1
|
n-fukuju_8487265_raw_ee0206d054b67e93c8271d51e4a8ff7e420c4ffa_assignletter.ps1
|
$beforeLetter = "D"
$afterLetter = "E"
# ドライブのボリューム番号を取得。
Write-Output "list volume" | DiskPart | ?{$_ -match ("Volume[ ]{1}(?<volume>\d)[ ]*"+ $beforeLetter)} | Out-Null
$volume = $Matches["volume"]
# ボリュームにドライブ文字を割り当てる。
Write-Output ("select volume {0}`nassign letter={1}" -f $volume, $afterLetter) | DiskPart | Out-Null
|
PowerShellCorpus/GithubGist/joshyu_fa8551e343bc860f9a87_raw_d86a0d64139ac6d3be475af7359480880242b9e5_importsp.ps1
|
joshyu_fa8551e343bc860f9a87_raw_d86a0d64139ac6d3be475af7359480880242b9e5_importsp.ps1
|
$url = "http://apcndae-dzn493x/testsub"
$pathb = "D:/spCmdlets"
$listtoback = "$pathb/list.txt"
$path = "$pathb/backup"
$specifytitle = $args[0]
if(![string]::IsNullOrEmpty($specifytitle)){
Write-Output "import $specifytitle"
$ff = $path+"/"+ $specifytitle + ".cmp"
Import-SPWeb $url -Path $ff
}else{
$content= Get-Content $listtoback
foreach($title in $content){
$tt= $title -split "/"
if($tt.Length -gt 1){
$tt = $tt[1];
}else{
$tt = $tt[0]
}
$file = "$path/$tt.cmp"
Write-Output "import $tt"
Import-SPWeb $url -Path $file
}
}
|
PowerShellCorpus/GithubGist/andreaswasita_ae980580fd42fa70c957_raw_08069d8e3dac1807d36d56b9aae41c2158417ccf_ClusterNetworkCloudServiceVIP.ps1
|
andreaswasita_ae980580fd42fa70c957_raw_08069d8e3dac1807d36d56b9aae41c2158417ccf_ClusterNetworkCloudServiceVIP.ps1
|
# Define variables
$ClusterNetworkName = "Cluster Network 1" # the cluster network name
$IPResourceName = "IP Address 10.0.1.0" # the IP Address resource name
$CloudServiceIP = "23.100.xxx.xxx" # IP address of your cloud service
Import-Module FailoverClusters
Get-ClusterResource $IPResourceName | Set-ClusterParameter -Multiple @{"Address"="$CloudServiceIP";"ProbePort"="59999";SubnetMask="255.255.255.128";"Network"="$ClusterNetworkName";"OverrideAddressMatch"=1;"EnableDhcp"=0}
# Define variables
$ClusterNetworkName = "Cluster Network 2" # the cluster network name
$IPResourceName = "IP Address 192.168.1.0" # the IP Address resource name
$CloudServiceIP = "23.100.xxx.xxx" # IP address of your cloud service
Import-Module FailoverClusters
Get-ClusterResource $IPResourceName | Set-ClusterParameter -Multiple @{"Address"="$CloudServiceIP";"ProbePort"="59999";SubnetMask="255.255.255.128";"Network"="$ClusterNetworkName";"OverrideAddressMatch"=1;"EnableDhcp"=0}
|
PowerShellCorpus/GithubGist/sandrinodimattia_4114961_raw_9d0a52bf4ee7e36fa9cefad144a03b6041db26f9_gistfile1.ps1
|
sandrinodimattia_4114961_raw_9d0a52bf4ee7e36fa9cefad144a03b6041db26f9_gistfile1.ps1
|
# Arguments.
param
(
[Microsoft.WindowsAzure.Management.ServiceManagement.Model.PersistentVMRoleContext]$vm = $(throw "'vm' is required."),
[int]$publicPort = $(throw "'publicPort' is required."),
[int]$dynamicPortFirst = $(throw "'dynamicPortFirst' is required."),
[int]$dynamicPortLast = $(throw "'dynamicPortLast' is required.")
)
Get-ChildItem "${Env:ProgramFiles(x86)}\Microsoft SDKs\Windows Azure\PowerShell\Azure\*.dll" | ForEach-Object {[Reflection.Assembly]::LoadFile($_) | out-null }
$totalPorts = $dynamicPortLast - $dynamicPortFirst + 1
if ($totalPorts -gt 150)
{
$(throw "You cannot add more than 150 endpoints (this includes the Public FTP Port)")
}
# Add endpoints.
Write-Host -Fore Green "Adding: FTP-Public-$publicPort"
Add-AzureEndpoint -VM $vm -Name "FTP-Public-$publicPort" -Protocol "tcp" -PublicPort $publicPort -LocalPort $publicPort
for ($i = $dynamicPortFirst; $i -le $dynamicPortLast; $i++)
{
$name = "FTP-Dynamic-" + $i
Write-Host -Fore Green "Adding: $name"
Add-AzureEndpoint -VM $vm -Name $name -Protocol "tcp" -PublicPort $i -LocalPort $i
}
# Update VM.
Write-Host -Fore Green "Updating VM..."
$vm | Update-AzureVM
Write-Host -Fore Green "Done."
|
PowerShellCorpus/GithubGist/DanSmith_3668859_raw_d3979c2b4c598dc23f4ffb31fa04bafa55d57bab_RegisterEventLog.ps1
|
DanSmith_3668859_raw_d3979c2b4c598dc23f4ffb31fa04bafa55d57bab_RegisterEventLog.ps1
|
# https://github.com/dansmith
#
$source = "My Application Name"
$wid=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp=new-object System.Security.Principal.WindowsPrincipal($wid)
$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
$IsAdmin=$prp.IsInRole($adm)
if($IsAdmin -eq $false)
{
[System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
[Windows.Forms.MessageBox]::Show(“Please run this as an Administrator”,
“Not Administrator”,
[Windows.Forms.MessageBoxButtons]::OK,
[Windows.Forms.MessageBoxIcon]::Information)
exit
}
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false)
{
[System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
[System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
[Windows.Forms.MessageBox]::Show(“Event log created successfully”,
“Complete”,
[Windows.Forms.MessageBoxButtons]::OK,
[Windows.Forms.MessageBoxIcon]::Information)
}
else
{
[System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
[Windows.Forms.MessageBox]::Show(“Event log already exists”,
“Complete”,
[Windows.Forms.MessageBoxButtons]::OK,
[Windows.Forms.MessageBoxIcon]::Information)
}
|
PowerShellCorpus/GithubGist/schakko_4713248_raw_eb2072fe7699413fbe058bdbef5f1a585896c7d1_check_microsoft_windows_software_raid.ps1
|
schakko_4713248_raw_eb2072fe7699413fbe058bdbef5f1a585896c7d1_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.
$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"
}
}
}
|
PowerShellCorpus/GithubGist/djcsdy_931645_raw_41ff54f8d05306604c3a003e56fd568809c524f4_svn-clean-all.ps1
|
djcsdy_931645_raw_41ff54f8d05306604c3a003e56fd568809c524f4_svn-clean-all.ps1
|
svn status --no-ignore |
Select-String '^[?I]' |
ForEach-Object {
[Regex]::Match($_.Line, '^[^\s]*\s+(.*)$').Groups[1].Value
} |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
PowerShellCorpus/GithubGist/kmoormann_3361439_raw_a36bc173ced73a39271e414d583d984f242e85f1_ClearDir.ps1
|
kmoormann_3361439_raw_a36bc173ced73a39271e414d583d984f242e85f1_ClearDir.ps1
|
function Global:ClearDir([string] $PATH)
{
$AllItemsInPath = $Path + "*"
Remove-Item $AllItemsInPath -recurse -force
}
|
PowerShellCorpus/GithubGist/robdmoore_dcd325e0ee73493ff1b7_raw_ef8b67f67de19afd60c0b3e0b970b7b2319eefb0_gistfile1.ps1
|
robdmoore_dcd325e0ee73493ff1b7_raw_ef8b67f67de19afd60c0b3e0b970b7b2319eefb0_gistfile1.ps1
|
$scriptpath = $(Split-Path $MyInvocation.MyCommand.Path)
cd $scriptpath
if (-not (ls *.publishsettings | Test-Any)) {
Write-Warning "Please save a .publishsettings file to this folder"
start .
Get-AzurePublishSettingsFile
exit 1
}
Import-AzurePublishSettingsFile
|
PowerShellCorpus/GithubGist/jayotterbein_438ae58b5ab9f64399ea_raw_c35a8ff076d34979dbd312750f62298ccb61e7c8_sln.ps1
|
jayotterbein_438ae58b5ab9f64399ea_raw_c35a8ff076d34979dbd312750f62298ccb61e7c8_sln.ps1
|
Function sln
{
[string[]]$installed = @(gci HKLM:\Software\Microsoft\VisualStudio\) |% { $_.Name } |% { Split-Path $_ -Leaf }
$versions = @()
foreach ($i in $installed)
{
[Version]$v = "0.0"
if ([Version]::TryParse($i, [ref]$v))
{
$versions += $v
}
}
$versions = $versions | sort -Descending
$maxVersion = $versions[0]
$maxVersionRegPath = (Join-Path "HKLM:\Software\Microsoft\VisualStudio\" ($maxVersion.ToString()))
$maxVersionInstallPath = (Get-ItemProperty $maxVersionRegPath).InstallDir
$devenv = (Join-Path $maxVersionInstallPath "devenv.exe")
if (!(Test-Path $devenv))
{
Write-Error "Unable to locate devenv: $devenv"
}
else
{
$searchPath = Resolve-Path '.'
if (Get-Command 'Get-GitDirectory' -ErrorAction SilentlyContinue)
{
$gitDirectory = Get-GitDirectory
if ((-not [string]::IsNullOrEmpty($gitDirectory)) -and (Test-Path $gitDirectory))
{
$searchPath = Resolve-Path (Split-Path ($gitDirectory))
}
}
$solutions = @(gci $searchPath *.sln -Recurse)
if ($solutions.Count -eq 0)
{
Write-Error "Unable to find any solution files in $searchPath"
}
else
{
$sln = Resolve-Path $solutions[0].FullName
Write-Host "Opening first solution file: $sln"
pushd (Split-Path $sln)
& $devenv $sln
popd
}
}
}
|
PowerShellCorpus/GithubGist/Astn_6e1f27aae1fff631f441_raw_a121f23b429dc55c76c820325c6507caa256fcef_all-git-remove-config-for-nustache.ps1
|
Astn_6e1f27aae1fff631f441_raw_a121f23b429dc55c76c820325c6507caa256fcef_all-git-remove-config-for-nustache.ps1
|
## remove all *.Config where there is a *.nustache.config in the same directory
## for any given n
## f(n) = if exists n.nustache.config and exists n.config
## then remove n.config
# for each Git Repo below the current directory
ls -Directory | Where-Object { (ls $_ -Directory -Hidden -Filter ".git")} | ForEach-Object {
# go to that repo
Pushd $_
# list all *.nustache.config
ls -Recurse -Filter "*.nustache.config" | ForEach-Object {
$checkpath = $_.FullName.Replace(".Nustache.config",".config")
# if a file exists with the same name minus ".Nustache"
if (test-path $checkpath){
Write-Warning "Removing $checkpath because we have $($_.FullName)"
# delete it and remove from git
git rm $checkpath
}else{
Write-Host "Skipping $_.FullName does not have a cooresponding .config"
}
}
# go back to the root directory
Popd
}
|
PowerShellCorpus/GithubGist/zhujo01_fa324e86946dfca3b119_raw_0c59b17029bf72456795d500eb6ac64ba2fb44e1_vmware-openstack.ps1
|
zhujo01_fa324e86946dfca3b119_raw_0c59b17029bf72456795d500eb6ac64ba2fb44e1_vmware-openstack.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
# - Openstack
#
# Coppyright (c) 2014, CliQr Technologies, Inc. All rights reserved.
########################################################################
|
PowerShellCorpus/GithubGist/ranniery_1063498091a21b82e68c_raw_9d817a3d8486a7415a9768f08730dc8b7b2590f6_RepairWMI.ps1
|
ranniery_1063498091a21b82e68c_raw_9d817a3d8486a7415a9768f08730dc8b7b2590f6_RepairWMI.ps1
|
###########################
# Ranniery Holanda #
# [email protected] #
# @_ranniery #
# 23/07/2014 #
###########################
# RepairWMI.ps1 #
###########################
# Parando e desativando o serviço do WMI #
(Get-service Winmgmt).stop()
Set-Service -Name Winmgmt -StartupType Disabled -Status Stopped
# Acessando o diretório do WMI #
Set-Location $env:windir\system32\wbem
# Resetando o repositorio #
winmgmt /resetrepository
# Iniciando o Registro das Dlls, Mofs e Mfls #
regsvr32.exe /s %systemroot%\system32\scecli.dll
regsvr32.exe /s %systemroot%\system32\userenv.dll
mofcomp.exe cimwin32.mof
mofcomp.exe cimwin32.mfl
mofcomp.exe rsop.mof
mofcomp.exe rsop.mfl
$dlls = get-childitem | where {$_.extension -eq ".dll"}
foreach($dll in $dlls)
{
Write-Host "registrando $dll..."
regsvr32.exe /s $dll
}
$mofs = get-childitem | where {$_.extension -eq ".mof"}
foreach($mof in $mofs)
{
Write-Host "registrando $mof..."
mofcomp.exe $mof
}
$mfls = get-childitem | where {$_.extension -eq ".mfl"}
foreach($mfl in $mfls)
{
Write-Host "registrando $mfl..."
mofcomp.exe $mfl
}
# Startando o serviço do WMI e mudando para automatico #
Set-Service -Name Winmgmt -StartupType Automatic -Status Running
|
PowerShellCorpus/GithubGist/seanbamforth_9436765_raw_9d3936fa46624df23c20c8695ee8d80a904867a9_copylocaltos3.ps1
|
seanbamforth_9436765_raw_9d3936fa46624df23c20c8695ee8d80a904867a9_copylocaltos3.ps1
|
param (
[string]$from = $(get-location).ToString(),
[string]$to = "selectcs-backup",
[switch]$mirror
)
#$DebugPreference = "Continue"
#todo:if no parameters, then show instructions
#todo:mirror option into own function
#todo:aws details need to be in the environment.
#todo:Copy from & copy to to use the same script. Maybe put it into a module.
import-module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1"
add-type -assemblyName "System.Web"
$blocksize = (1024*1024*5)
$startblocks = (1024*1024*16)
$AccessKeyId = (get-item env:aws-access-key-id -erroraction ignore).value
$AccessKeySecret = (get-item env:aws-access-key-secret -erroraction ignore).value
if ( !($AccessKeyId) -or !($AccessKeySecret)) {
$ok = ($AccessKeyId) -or ($AccessKeySecret)
Write-Host "AWS Access keys have not been created."
Write-Host "==================================================================="
Write-Host "To run this script you must create two environment variables called"
Write-Host "aws-access-key-id and aws-access-key-secret"
Write-Host "--"
break
}
# Regions: us-east-1, us-west-2, us-west-1, eu-west-1, ap-southeast-1
$region = "eu-west-1"
$backupFrom = $from
$backupTo = $to
$backupFrom = $backupFrom.ToLower()
$BackupTo = $BackupTo.ToLower()
if ($backupFrom[-1] -ne "\") { $backupFrom += "\" }
$bucket = $BackupTo.Split(":")[0]
$s3folder = $BackupTo.Split(":")[1]
if (!($s3folder)) {
$s3folder = $env:COMPUTERNAME + "/"
$s3folder += $(get-location).ToString() + "/"
$s3folder = $s3folder.replace("\\","/").replace(":\","/").replace("\","/")
$s3folder = $s3folder.ToLower()
}
$s3folder = $s3folder.ToLower().replace("\" , "/")
if ($s3folder[-1] -ne "/") { $s3folder += "/" }
$msg="Copying files from $backupFrom to $BackupTo"
Write-Host $msg
Write-Host "-"
Write-Host "Bucket: $bucket"
write-Host "Mirror: $mirror"
Write-Host "S3 Folder: $s3folder"
Write-Host ("=" * $msg.Length)
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
function AmazonEtagHashForFile($filename) {
$lines = 0
[byte[]] $binHash = @()
$reader = [System.IO.File]::Open($filename,"OPEN","READ")
if ((Get-Item $filename).length -gt $startblocks) {
$buf = new-object byte[] $blocksize
while (($read_len = $reader.Read($buf,0,$buf.length)) -ne 0){
$lines += 1
$binHash += $md5.ComputeHash($buf,0,$read_len)
}
$binHash=$md5.ComputeHash( $binHash )
}
else {
$lines = 1
$binHash += $md5.ComputeHash($reader)
}
$reader.Close()
$hash = [System.BitConverter]::ToString( $binHash )
$hash = $hash.Replace("-","").ToLower()
if ($lines -gt 1) {
$hash = $hash + "-$lines"
}
return $hash
}
function s3NameToLocalName($file) {
$file = $file.replace($s3Folder,"")
$file = $file.replace("/" , "\")
$file = [System.Web.HttpUtility]::UrlDecode($file)
$file = $backupFrom + $file
return $file
}
function s3BackupFile($file) {
if (!$file.PSIsContainer) {
$fromFile = $file.fullname.ToLower()
$tofile = $file.fullname.ToLower()
$tofile = $tofile.replace($backupfrom,"")
$tofile = $tofile.replace("\" , "/")
$tofile = [System.Web.HttpUtility]::UrlEncode($tofile)
$tofile = $tofile.replace("%2f" , "/")
$tofile = $s3folder + $tofile
$s3file = (Get-S3Object -BucketName $bucket -Key $tofile)
if ($s3file -eq $null) {
Write-Host "$fromFile -> $tofile (New File)"
Write-S3Object -BucketName $bucket -File $fromfile -Key $tofile
return
}
$hash = AmazonEtagHashForFile($fromFile)
$etag =$s3file[0].etag.Replace('"',"")
if ($etag -ne $hash) {
Write-Host("$fromFile -> $tofile (Different)" )
Write-S3Object -BucketName $bucket -File $fromfile -Key $tofile
}
}
}
Set-AWSCredentials -AccessKey $AccessKeyId -SecretKey $AccessKeySecret
Set-DefaultAWSRegion $region
#Mirroring....
if ($mirror) {
do {
$s3files = (Get-S3Object -Marker $marker -MaxKeys $maxkeys -BucketName $bucket -KeyPrefix $s3Folder )
$s3files | Foreach-Object{
$marker = $_.key
$LocalFile = (s3NameToLocalName $_.key)
if (!(Test-Path $LocalFile)) {
$DeleteAmazonFile = $_.key
Write-Host ("Deleting... $DeleteAmazonFile")
$response = Remove-S3Object -BucketName $bucket -Key $DeleteAmazonFile -Force
}
}
} while ($s3files.length -eq $maxkeys)
}
#now we restore
$files = Get-ChildItem $BackupFrom -Recurse
$files | Foreach-Object{
s3BackupFile $_
}
Write-Host("..")
|
PowerShellCorpus/GithubGist/jonschoning_5447758_raw_d86adc409913eb04e0bef5fbcd14ebc2b73d510e_set-iis-physicalpaths.ps1
|
jonschoning_5447758_raw_d86adc409913eb04e0bef5fbcd14ebc2b73d510e_set-iis-physicalpaths.ps1
|
import-module WebAdministration
$root = "IIS:\Sites\DefaultWebSite"
Function Set-IIS-PhysicalPaths {
Param(
[parameter(mandatory=$true)][string]$branch
)
Set-ItemProperty "$($root)\SubApplication" -Name physicalPath -Value "C:\inetpub\wwwroot\$($branch)\" -Verbose
}
if($args.length -eq 1) {
Set-IIS-Tickets-PhysicalPaths $args[0]
} else {
Set-IIS-Tickets-PhysicalPaths
}
|
PowerShellCorpus/GithubGist/ziembor_9433720_raw_f042d430051a4767c5a347934616b3c54fabf923_Out-SpeechFx.ps1
|
ziembor_9433720_raw_f042d430051a4767c5a347934616b3c54fabf923_Out-SpeechFx.ps1
|
function Out-SpeechFx {[CmdletBinding()]
param([Parameter(Position=0, Mandatory=$false,ValueFromPipeline=$true)][alias("text")][string] $Message = 'Brak tekstu do czytania',
[Parameter(Position=1)][string][validateset('Male','Female')] $Gender = 'Female',
[Parameter(Position=2)][string] $lang = (Get-UICulture).Name,
[Parameter(Position=3)][int] $Rate = 0,
[Parameter(Position=4)][string] $Voice,
[Parameter(Position=5)][int][ValidateRange(1,100)] $Volume = 100
)
begin {
try { Add-Type -Assembly System.Speech -ErrorAction Stop }
catch { Write-Error -Message "Error loading the required assemblies"}
}
process {
$voices = @()
$allVoices = $object.GetInstalledVoices()| select -ExpandProperty VoiceInfo
write-verbose "Lang: $lang Gender: $Gender Message: $Message"
$object = New-Object System.Speech.Synthesis.SpeechSynthesizer
if($Voice -eq $null -or $Voice -eq "") {
$voices = $allVoices | where {$_.Culture -match $lang -and $_.Gender -eq $Gender}
if(-not $voices.count -ge 1) {$voices = $allVoices | where {$_.Culture -match $lang} } }
else {$voices = $allVoices | where {$_.Name -match $Voice -or $_.Description -match $Voice -or $_.Id -match $Voice }}
if(-not $voices.count -ge 1) {$voices = $allVoices | where {$_.Name -eq "Microsoft David Desktop"}}
try { [string]$selectedvoice = ($voices | get-random).Name ;
Write-Verbose -Message "Selecting a voice name: $selectedvoice"
$object.SelectVoice($selectedvoice)
} catch {"No such voice"}
$object.Rate = $Rate
$object.Volume = $Volume
$object.Speak($Message)
}
end {
$sumState = ($object).State
$sumRate = ($object).Rate
$sumVolume = ($object).Volume
$sumVoiceName = ($object.Voice).Name
Write-Verbose -Message "Speech summary: $sumState $sumRate $sumVolume $sumVoiceName"
$object = $null}
}
|
PowerShellCorpus/GithubGist/altrive_9151365_raw_eecfc423e15a9487805b55fa5d5e7b3873294b1b_SetAccountPrevilage.ps1
|
altrive_9151365_raw_eecfc423e15a9487805b55fa5d5e7b3873294b1b_SetAccountPrevilage.ps1
|
#Requires -RunAsAdministrator
function Main
{
$ErrorActionPreference = "Stop"
$VerbosePreference = "Continue"
#Target account to assign previlage
$svcAccount = "TestSvc"
#サービスとしてログオン
Write-Verbose ("Set account previlage({0}) to '{1}'" -f "SeServiceLogonRight", $svcAccount)
[LsaWrapper]::SetRight($svcAccount, "SeServiceLogonRight")
#バッチジョブとしてログオン
Write-Verbose ("Set account previlage({0}) to '{1}'" -f "SeBatchLogonRight", $svcAccount)
[LsaWrapper]::SetRight($svcAccount, "SeBatchLogonRight")
#ボリュームの保守タスクを実行
Write-Verbose ("Set account previlage({0}) to '{1}'" -f "SeManageVolumePrivilege", $svcAccount)
[LsaWrapper]::SetRight($svcAccount, "SeManageVolumePrivilege")
#メモリ内のページのロック
Write-Verbose ("Set account previlage({0}) to '{1}'" -f "SeLockMemoryPrivilege", $svcAccount)
[LsaWrapper]::SetRight($svcAccount, "SeLockMemoryPrivilege")
#ローカルログオンを拒否
Write-Verbose ("Set account previlage({0}) to '{1}'" -f "SeDenyInteractiveLogonRight", $svcAccount)
[LsaWrapper]::SetRight($svcAccount, "SeDenyInteractiveLogonRight")
}
Add-Type -TypeDefinition @'
using System;
using System.Text;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.ComponentModel;
public static class LSAWrapper
{
[DllImport("advapi32.dll", PreserveSig = true)]
private static extern UInt32 LsaOpenPolicy(
ref LSA_UNICODE_STRING SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
Int32 DesiredAccess,
out IntPtr PolicyHandle
);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern long LsaAddAccountRights(
IntPtr PolicyHandle,
IntPtr AccountSid,
LSA_UNICODE_STRING[] UserRights,
long CountOfRights);
[DllImport("advapi32.dll")]
private static extern long LsaClose(IntPtr objectHandle);
[DllImport("kernel32.dll")]
private static extern int GetLastError();
[DllImport("advapi32.dll")]
private static extern long LsaNtStatusToWinError(long status);
[StructLayout(LayoutKind.Sequential)]
private struct LSA_OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public readonly LSA_UNICODE_STRING ObjectName;
public UInt32 Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr Buffer;
}
[Flags]
private enum LSA_AccessPolicy : long
{
POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
POLICY_TRUST_ADMIN = 0x00000008L,
POLICY_CREATE_ACCOUNT = 0x00000010L,
POLICY_CREATE_SECRET = 0x00000020L,
POLICY_CREATE_PRIVILEGE = 0x00000040L,
POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
POLICY_SERVER_ADMIN = 0x00000400L,
POLICY_LOOKUP_NAMES = 0x00000800L,
POLICY_NOTIFICATION = 0x00001000L
}
//POLICY_ALL_ACCESS mask <http://msdn.microsoft.com/en-us/library/windows/desktop/ms721916%28v=vs.85%29.aspx>
private const int POLICY_ALL_ACCESS = (int)(
LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
LSA_AccessPolicy.POLICY_CREATE_SECRET |
LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
LSA_AccessPolicy.POLICY_NOTIFICATION |
LSA_AccessPolicy.POLICY_SERVER_ADMIN |
LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
LSA_AccessPolicy.POLICY_TRUST_ADMIN |
LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
);
public static void SetRight(string accountName, string privilegeName)
{
//Convert assigned privilege to LSA_UNICODE_STRING[] object
var userRights = GetUserRightsObject(privilegeName);
//Get account SID and pin object for P/Invoke
var sid = GetBinarySID(accountName);
var handle = GCHandle.Alloc(sid, GCHandleType.Pinned);
//Open LSA policy
IntPtr policyHandle = OpenPolicyHandle();
try
{
//add the right to the account
long status = LsaAddAccountRights(policyHandle, handle.AddrOfPinnedObject(), userRights, userRights.Length);
var winErrorCode = LsaNtStatusToWinError(status);
if (winErrorCode != 0)
{
throw new Win32Exception((int)winErrorCode, "LsaAddAccountRights failed");
}
}
finally
{
handle.Free();
Marshal.FreeHGlobal(userRights[0].Buffer); //Can use LsaFreeMemory instead?
LsaClose(policyHandle);
}
}
private static LSA_UNICODE_STRING[] GetUserRightsObject(string privilegeName)
{
//initialize userRights objects
return new[]
{
new LSA_UNICODE_STRING
{
Buffer = Marshal.StringToHGlobalUni(privilegeName),
Length = (UInt16)(privilegeName.Length * UnicodeEncoding.CharSize),
MaximumLength = (UInt16)((privilegeName.Length + 1) * UnicodeEncoding.CharSize)
}
};
}
private static byte[] GetBinarySID(string accountName)
{
//Get account SID
NTAccount account;
try
{
account = new NTAccount(accountName);
}
catch(IdentityNotMappedException)
{
throw; //TODO:ErrorHandling
}
//Convert SID to byte[]
var identity = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
var buffer = new byte[identity.BinaryLength];
identity.GetBinaryForm(buffer, 0);
return buffer;
}
private static IntPtr OpenPolicyHandle()
{
//dummy variables
var systemName = new LSA_UNICODE_STRING();
var objectAttributes = new LSA_OBJECT_ATTRIBUTES
{
Length = 0,
RootDirectory = IntPtr.Zero,
Attributes = 0,
SecurityDescriptor = IntPtr.Zero,
SecurityQualityOfService = IntPtr.Zero
};
IntPtr policyHandle;
uint status = LsaOpenPolicy(ref systemName, ref objectAttributes, POLICY_ALL_ACCESS, out policyHandle);
var winErrorCode = LsaNtStatusToWinError(status);
if (winErrorCode != 0)
{
throw new Win32Exception((int)winErrorCode, "LsaOpenPolicy failed");
}
return policyHandle;
}
}
'@
Main
|
PowerShellCorpus/GithubGist/marcind_9512656_raw_4aaaf190a53262526b3574ba53587bfbf990e4da_gistfile1.ps1
|
marcind_9512656_raw_4aaaf190a53262526b3574ba53587bfbf990e4da_gistfile1.ps1
|
# Execute this in Nuget powershell console
get-project -all | %{ $_.Properties | ?{ $_.Name -eq "WebApplication.StartWebServerOnDebug"} | %{ $_.Value = $False } }
#
|
PowerShellCorpus/GithubGist/ianbattersby_4546636_raw_8bef5088c2c412da77200411bcb73fa41a7f875c_gistfile1.ps1
|
ianbattersby_4546636_raw_8bef5088c2c412da77200411bcb73fa41a7f875c_gistfile1.ps1
|
$vmm = Get-SCVMMServer -ComputerName "my-vmm-host"
$ls = Get-SCLibraryServer -ComputerName "my-vmm-host"
Import-SCVirtualMachine -ImportVMPath "c:\temp\myovf.ovf" -LibraryServerObject $ls -VMMServerObject $vmm -LibrarySharePath "\\my-vmm-host\MSSCVMMLibrary\Import\" -VHDSourcePath "C:\Virtual Machines\BlankVHD.vhd" -VMName "MY-VM"
Import-SCVirtualMachine : Method not found: 'Int32 Microsoft.VirtualManager.Utils.MonitorResolutionLimits.GetMonitorResolutionIndex(Int32, System.String)'.
At line:1 char:1
+ Import-SCVirtualMachine -ImportVMPath
"C:\Temp\GitHubEnterprise\ReExport\github- ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : NotSpecified: (:) [Import-SCVirtualMachine], Mis
singMethodException
+ FullyQualifiedErrorId : System.MissingMethodException,Microsoft.SystemCe
nter.VirtualMachineManager.OVFTool.ImportVirtualMachine
|
PowerShellCorpus/GithubGist/altrive_8023060_raw_d5e01e9473599f3c678162dca89ad0dcb10fdc88_Add-TypeDefinition.ps1
|
altrive_8023060_raw_d5e01e9473599f3c678162dca89ad0dcb10fdc88_Add-TypeDefinition.ps1
|
function Add-TypeDefinition
{
[CmdletBinding()]
param (
[string] $Path,
[string[]] $ReferencedAssemblies = @("Microsoft.CSharp"),
[string] $OutputAssembly,
[switch] $IgnoreWarnings,
[switch] $UseTypeAlias
)
$ErrorActionPreference = "Stop"
if (!(Test-Path $Path)){
Write-Error ("Specified path '{0}' is not exists" -f $Path)
}
if ($Path.EndsWith(".cs"))
{
$files = New-Object IO.FileInfo($Path)
}
else
{
$files = Get-ChildItem -Path $Path -Filter "*.cs" -Recurse -File
}
if (($files -eq $null) -or $files.Count -eq 0){
return
}
#Merge C# code files to import definitions
$sb = New-Object Text.StringBuilder
foreach ($file in $files)
{
#Write-Verbose ("Add C# type definition from file '{0}'" -f $file.Name)
$content = Get-Content $file.FullName -Raw
$sb.AppendLine($content) > $null
}
$params = @{
ReferencedAssemblies = $ReferencedAssemblies
IgnoreWarnings = $IgnoreWarnings
}
if (![String]::IsNullOrEmpty($OutputAssembly)){
$params.Add("OutputAssembly", $OutputAssembly)
}
if ($UseTypeAlias)
{
#Guid suffix to create unique class name
$uniqueSuffix = "_{0}" -f [Guid]::NewGuid().ToString().Replace("-", "_")
#Regex to find class declarations
$regex = [regex] "(?<=public\s+(static\s+)?(partial\s+)?class\s+)\w+"
#Replace class name to unique name
$code = $regex.Replace($sb.ToString(), [String]::Format("{0}{1}", "$&", $uniqueSuffix))
#Add replaced code definition
Add-Type @params -TypeDefinition $code
#Add Alias to original class name
foreach ($match in $regex.Matches($code))
{
$className = $match.Value.Replace($uniqueSuffix, "")
#Write-Verbose ("Set class name alias '{0}' to '{1}'" -f $className, $match.Value) -Verbose
[PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Add($className, $match.Value)
}
}
else
{
#Add replaced code definition
Write-Verbose "Call Add-Type with no type aliases"
Add-Type @params -TypeDefinition $sb.ToString()
}
}
|
PowerShellCorpus/GithubGist/guillaume8375_5991511_raw_95b3bfa2a866617bbdd014f33b6637d4a1bb014f_top_powershell.ps1
|
guillaume8375_5991511_raw_95b3bfa2a866617bbdd014f33b6637d4a1bb014f_top_powershell.ps1
|
while (1) {ps | sort -desc cpu | select -first 30; sleep -seconds 2; cls;
write-host "Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName";
write-host "------- ------ ----- ----- ----- ------ -- -----------"}
|
PowerShellCorpus/GithubGist/ctrlbold_c22e2a213f5b05e47c0c_raw_3ae37441d728c172f1f4b8d70779d67932e40f2d_Get-Duplicates.ps1
|
ctrlbold_c22e2a213f5b05e47c0c_raw_3ae37441d728c172f1f4b8d70779d67932e40f2d_Get-Duplicates.ps1
|
# Create Datatable
$dt = New-Object System.Data.Datatable "Music"
[void]$dt.Columns.Add("Artist")
[void]$dt.Columns.Add("Genre")
[void]$dt.Columns.Add("Album")
[void]$dt.Columns.Add("ReleaseYear")
# Add data
[void]$dt.Rows.Add("Poison","Glam Metal","Open Up and Say... Ahh!",1988)
[void]$dt.Rows.Add("Cinderella","Night Songs","Flesh & Blood",1986)
[void]$dt.Rows.Add("Eazy-E","Gangsta Rap","Eazy-Duz-It",1988)
[void]$dt.Rows.Add("Tim Smooth","Southern Rap","I Gotsta' Have It",1991)
# Add dupes
[void]$dt.Rows.Add("Poison","Glam Metal","Open Up and Say... Ahh!",1988)
[void]$dt.Rows.Add("Eazy-E","Gangsta Rap","Eazy-Duz-It",1988)
[void]$dt.Rows.Add("Eazy-E","Gangsta Rap","Eazy-Duz-It",1988)
# Perform the dupe check
[void][Reflection.Assembly]::LoadWithPartialName("System.Data.DataSetExtensions")
[void][Reflection.Assembly]::LoadWithPartialName("System.Data.Linq")
# Add a count column prior to making the dataset a LINQ list.
[void]$dt.Columns.Add("DupeCount")
$source = [System.Data.DataTableExtensions]::AsEnumerable($dt)
$list = [System.Linq.Enumerable]::ToList($source)
# Group By
$groupbyquery = [System.Func[System.Data.DataRow, string]] { param($row) $row.Artist, $row.Album }
$groupby = [System.Linq.Enumerable]::GroupBy($list,$groupbyquery)
# Where, can probably use Any, too.
$wherequery = [System.Func[System.Object, bool]] { param($row) $row.Artist.count -gt 1 -and $row.Album -gt 1 }
$where = [System.Linq.Enumerable]::Where($groupby,$wherequery)
# Select distinct, and add a count
$selectquery = [system.func[System.Object,System.Object]] { param($row)
$null = $row.Item(0)["DupeCount"] = $row.count
$row.Item(0)
}
$select = [System.Linq.Enumerable]::Select($where,$selectquery)
# You could streamline it, too.
# [System.Linq.Enumerable]::Select([System.Linq.Enumerable]::GroupBy($list,$groupbyquery).Where({$wherequery}),$selectquery)
# Build & populate new dupetable
$dupetable = $dt.Clone()
foreach ($row in $select) { $dupetable.ImportRow($row) }
# Remove count column from original datatable
[void]$dt.Columns.Remove("DupeCount")
# Show your results. Orderby can probably be performed above, but whatever.
$dupetable | Select Artist, Album, Dupecount | Sort-Object Dupecount
|
PowerShellCorpus/GithubGist/vbratkev_03bd128c2f494711a4e4_raw_393b32662bdb832aec63e60fd974c8e79aeda613_ZipUtils.ps1
|
vbratkev_03bd128c2f494711a4e4_raw_393b32662bdb832aec63e60fd974c8e79aeda613_ZipUtils.ps1
|
function zip ($zipFilePath, $targetDir) {
# load Ionic.Zip.dll
[System.Reflection.Assembly]::LoadFrom(path\to\Ionic.Zip.dll)
$encoding = [System.Text.Encoding]::GetEncoding("shift_jis") # 日本語のファイルを扱うために必要
$zipfile = new-object Ionic.Zip.ZipFile($encoding)
$zipfile.AddDirectory($targetDir)
if (!(test-path (split-path $zipFilePath -parent))) {
mkdir (split-path $zipFilePath -parent)
}
write-host "Saving... zip file from $targetDir"
$zipfile.Save($zipFilePath)
$zipfile.Dispose()
write-host "Saved."
}
function Extract-Zip() {
param(
[string] $ZipFilePath,
[string] $ExtractDirectory,
[boolean] $FileBaseNameDir = $false
)
# load Ionic.Zip.dll
[System.Reflection.Assembly]::LoadFrom("path\to\Ionic.Zip.dll") | Out-Null
if((Test-Path -Path $ZipFilePath -PathType Leaf)){
if($FileBaseNameDir){
$FileInfo = Get-ChildItem $ZipFilePath
$ExtractDirectory = [System.IO.Path]::Combine($ExtractDirectory, $FileInfo.BaseName)
}
Write-Host "Extracting... zip file [$ZipFilePath] to $ExtractDirectory" -BackgroundColor Green
$Zip = [Ionic.Zip.ZIPFile]::Read($ZipFilePath)
try {
$Zip | ForEach-Object{
$_.Extract($ExtractDirectory, [Ionic.Zip.ExtractExistingFileAction]::OverWriteSilently)
}
}finally{
$Zip.Dispose()
}
Write-Host "Extracted." -ForegroundColor Green
}else{
Write-Host "Is a directory" -ForegroundColor Red
}
}
|
PowerShellCorpus/GithubGist/staxmanade_4206883_raw_5e8f27a83fc308165a28425cfce1ac8b11d3c147_Powershell_Create_Change_Package.ps1
|
staxmanade_4206883_raw_5e8f27a83fc308165a28425cfce1ac8b11d3c147_Powershell_Create_Change_Package.ps1
|
param(
$beginSha = $(throw '-beginSha is required'),
$endSha = $(throw '-endSha is required'),
$projectName = $( (get-item .).name )
)
# Get a list of all the files that have been added/modified/deleted
$filesWithMods = git diff --name-status $beginSha $endSha | Select @{Name="ChangeType";Expression={$_.Substring(0,1)}}, @{Name="File"; Expression={$_.Substring(2)}}
# There has to be a cleaner way? (to get the sha1 of the 'end commit')
$endShaShortName = (git log --format=%H $endSha | select -First 1).Substring(0, 10)
$beginShaShortName = (git log --format=%H $beginSha | select -First 1).Substring(0, 10)
$deployFileBasename = "..\$($projectName)_$endShaShortName"
#var to hold the 'readme' file we're dumping information to
$rm = "$deployFileBaseName.txt"
"Changes from $beginShaShortName to $endShaShortName" > $rm
"" >> $rm
"Files Removed:" >> $rm
$filesWithMods | where{$_.ChangeType -eq 'D' } | %{ "`t" + $_.File } >> $rm
"" >> $rm
$filesAddedOrModified = $filesWithMods | where{$_.ChangeType -ne 'D' }
"Files Added or Modified:" >> $rm
$filesWithMods | where{$_.ChangeType -ne 'D' } | %{ "`t" + $_.File } >> $rm
"" >> $rm
"" >> $rm
"" >> $rm
"Complete git diff between the changes:" >> $rm
git diff $beginSha $endSha >> $rm
# Dump the modified/added files to the zip (excluding the deleted files)
$filesAddedOrModified | %{ $_.File} | AddTo-7Zip "$deployFileBasename.zip" | out-null
|
PowerShellCorpus/GithubGist/mwjcomputing_4691239_raw_6be19594c1c3446a46bd543ebbd293e9147057ec_IgnoreCertErrors.ps1
|
mwjcomputing_4691239_raw_6be19594c1c3446a46bd543ebbd293e9147057ec_IgnoreCertErrors.ps1
|
[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
|
PowerShellCorpus/GithubGist/ploegert_fa02e9c1a943f97219b9_raw_17f05c1f028493c48c2767f1337a27852aeea0ea_Deploy-WebSite.ps1
|
ploegert_fa02e9c1a943f97219b9_raw_17f05c1f028493c48c2767f1337a27852aeea0ea_Deploy-WebSite.ps1
|
#Modified and simplified version of https://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/
#From: #https://gist.github.com/3694398
$subscription = "[SubscriptionName]" #this the name from your .publishsettings file
$service = "[ServiceName]" #this is the name of the cloud service
$storageAccount = "[StorageAccountName]" #this is the name of the storage service
$slot = "production" #staging or production
$package = "[Fully Qualified Path to .cspkg]"
$configuration = "[Fully Qualified path to .cscfg]"
$publishSettingsFile = "[Path to .publishsettings file, relative is OK]"
$timeStampFormat = "g"
$deploymentLabel = "PowerShell Deploy to $service"
Write-Output "Slot: $slot"
Write-Output "Subscription: $subscription"
Write-Output "Service: $service"
Write-Output "Storage Account: $storageAccount"
Write-Output "Slot: $slot"
Write-Output "Package: $package"
Write-Output "Configuration: $configuration"
Write-Output "Running Azure Imports"
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell\Azure\*.psd1"
Import-AzurePublishSettingsFile $publishSettingsFile
Set-AzureSubscription -CurrentStorageAccount $storageAccount -SubscriptionName $subscription
Set-AzureService -ServiceName $service -Label $deploymentLabel
function Publish(){
$deployment = Get-AzureDeployment -ServiceName $service -Slot $slot -ErrorVariable a -ErrorAction silentlycontinue
if ($a[0] -ne $null) {
Write-Output "$(Get-Date -f $timeStampFormat) - No deployment is detected. Creating a new deployment. "
}
if ($deployment.Name -ne $null) {
#Update deployment inplace (usually faster, cheaper, won't destroy VIP)
Write-Output "$(Get-Date -f $timeStampFormat) - Deployment exists in $servicename. Upgrading deployment."
UpgradeDeployment
} else {
CreateNewDeployment
}
}
function CreateNewDeployment()
{
write-progress -id 3 -activity "Creating New Deployment" -Status "In progress"
Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: In progress"
$opstat = New-AzureDeployment -Slot $slot -Package $package -Configuration $configuration -label $deploymentLabel -
ServiceName $service
$completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot
$completeDeploymentID = $completeDeployment.deploymentid
write-progress -id 3 -activity "Creating New Deployment" -completed -Status "Complete"
Write-Output "$(Get-Date -f $timeStampFormat) - Creating New Deployment: Complete, Deployment ID:
$completeDeploymentID"
}
function UpgradeDeployment()
{
write-progress -id 3 -activity "Upgrading Deployment" -Status "In progress"
Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: In progress"
# perform Update-Deployment
$setdeployment = Set-AzureDeployment -Upgrade -Slot $slot -Package $package -Configuration $configuration -label
$deploymentLabel -ServiceName $service -Force
$completeDeployment = Get-AzureDeployment -ServiceName $service -Slot $slot
$completeDeploymentID = $completeDeployment.deploymentid
write-progress -id 3 -activity "Upgrading Deployment" -completed -Status "Complete"
Write-Output "$(Get-Date -f $timeStampFormat) - Upgrading Deployment: Complete, Deployment ID: $completeDeploymentID"
}
Write-Output "Create Azure Deployment"
Publish
|
PowerShellCorpus/GithubGist/JingwenTian_8858531_raw_af3fd13e154e35a8740210369151ff80663a5377_gistfile1.ps1
|
JingwenTian_8858531_raw_af3fd13e154e35a8740210369151ff80663a5377_gistfile1.ps1
|
vi /etc/ssh/sshd_config
#把 PermitRootLogin yes 改为 PermitRootLogin no
#重启sshd服务
service sshd restart
|
PowerShellCorpus/GithubGist/jonretting_34ed19ed2b06d99c484b_raw_1eb36bcb32e532c805609080a5a006778baebf4d_gistfile1.ps1
|
jonretting_34ed19ed2b06d99c484b_raw_1eb36bcb32e532c805609080a5a006778baebf4d_gistfile1.ps1
|
# Your NAS Synology device suddenly lost connection to your Windows Domain Controller, and or intermittent AD connectivity issues.
# Symptoms include but not limited to:
# - Failing to rejoin after removing the account on the Domain.
# - Failing to rejoin without any changes
# - Join attempt results in = "Failed to join the Windows domain. Please check your domain and firewall settings and try again"
# - Synology is joined, but attempting to connect from domain clients results in "There are no logon servers available to service the logon request"
# - This problem happens intermittently, sometimes rebooting the Synology device allows you to rejoin (Not a solution).
# - Sometimes rebooting both Synology device and Domain Controller allows you to rejoin (Not a solution).
# 1st.) *OPTIONAL* Remove the AD Synology device from Avtice Directory Users/Computers.
# Step could be required if your Synology system is currently in a disconnected state.
# ie: Inaccessible from Domain systems, and or "no login servers available".
# Always try Step 2 first, you have nothing to lose. Permissions for Domain Users/Groups, entered
# on your Synology system, for shared folders do not get removed when the Synology Computer object
# is deleted from the Domain's Active Directory Users/Computers.
# 2nd.) *THE FIX*) Enable SMB1 Protocol - Try the following commands on your Domain Controller:
# Use the appropriate commands for the terminal/console/shell you are using.
# Goal: Enable SMB1 and restart LanmanWorkstation and LanmanServer SMB Windows services
# powershell v4 (ws2012+)
Set-SmbServerConfiguration –EnableSMB1Protocol $true
# powershell v2 (ws2k8)
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters" SMB1 -Type DWORD -Value 1 -Force
# cmd (cmd/run)
reg.exe ADD 'HKLM\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters' /v SMB1 /t REG_DWORD /d 0x1 /f
# restart SMB services (Powershell)
Restart-Service LanmanWorkstation -Force; Restart-Service LanmanServer -Force
# restart SMB services (cmd)
net stop LanmanWorkstation & net start LanmanWorkstation
net stop LanmanServer & net start LanmanServer
# sc cmd method
sc stop LanmanWorkstation & sc start LanmanWorkstation
sc stop LanmanServer & sc start LanmanServer
# 3rd.) Enjoy the problem never happening again. You might also want to setup a WINS server, since Synology boxes seem to function
# much better with one available to them.
# Info: Why would SMB1 all of a sudden be relevant to a previously joined device with it disabled? No Clue.
# Since I don’t use SMB for anything on the related Domain Controller, I now schedule a task to restart SMB services
# once a day. If the problem persists you may want to evaluate your Domain's Network Permissions (Securty Settings)
# for NTLM authentication. I can see this being an issue for certain environments. Might want to look into adding an
# server exception for your NAS. Granted i have not tested a Synology with zero NTLM (no NTLMv2 only Krb). I am also not sure
# what data is passed from NAS to DC in regards to SMB1. Somepoint i will setup a lab and capture data with SMB1 enabled/disabled,
# and the activity of the synology system in a dissconnected domain state.
|
PowerShellCorpus/GithubGist/malexw_7848290_raw_711abc8b2bcc53bd718d546f694345b0bd60ef12_gowork.ps1
|
malexw_7848290_raw_711abc8b2bcc53bd718d546f694345b0bd60ef12_gowork.ps1
|
$Env:gopath = $args[0]
cd $args[0]
|
PowerShellCorpus/GithubGist/wojtha_1039912_raw_5d458ef59689419aaca85924932760dca2a5e74c_drush_module_cleanup.ps1
|
wojtha_1039912_raw_5d458ef59689419aaca85924932760dca2a5e74c_drush_module_cleanup.ps1
|
###############################################################################
#
# Cleanup of Drupal modules using Drush & Windows PowerShell
#
# Author: Vojtech Kusy <[email protected]>
#
###############################################################################
# Create directory .trash if doesn't exist
if(!(Test-Path .\.trash -pathtype container)) {
New-Item .trash -type directory
}
# List all disabled & unistalled modules and move them to .trash
drush pml --status="disabled,not installed" --pipe | foreach {
if(($_ -and (Test-Path ".\$_" -pathtype container))){
Move-Item ".\$_" .\.trash
}
}
# One liner - Dry run
# if(!(Test-Path .\.trash -pathtype container)) { echo "Creating .trash directory" }; drush pml --status="disabled,not installed" --pipe | foreach {if(($_ -and (Test-Path ".\$_" -pathtype container))){ "Moving .\$_ to .\trash\$_" }}
# One liner - Pipe output
# drush pml --status="disabled,not installed" --pipe | foreach {if(($_ -and (Test-Path ".\$_" -pathtype container))){ echo $_ }}
# One liner - Move
# if(!(Test-Path .\.trash -pathtype container)) {New-Item .trash -type directory}; drush pml --status="disabled,not installed" --pipe | foreach {if(($_ -and (Test-Path ".\$_" -pathtype container))){Move-Item ".\$_" .\.trash}}
# One liner - Git Move
# if(!(Test-Path .\.trash -pathtype container)) {New-Item .trash -type directory}; drush pml --status="disabled,not installed" --pipe | foreach {if(($_ -and (Test-Path ".\$_" -pathtype container))){Move-Item ".\$_" .\.trash}}
# One liner - Git Remove
# if(!(Test-Path .\.trash -pathtype container)) {New-Item .trash -type directory}; drush pml --status="disabled,not installed" --pipe | foreach {if(($_ -and (Test-Path ".\$_" -pathtype container))){git rm -r --cached ".\$_"; Move-Item ".\$_" .\.trash}}
|
PowerShellCorpus/GithubGist/rm-jamotion_9066943_raw_8eda181e879de240fbf36e65a0be8417c4155f6b_JoomlaExtensionLinkerForWindows.ps1
|
rm-jamotion_9066943_raw_8eda181e879de240fbf36e65a0be8417c4155f6b_JoomlaExtensionLinkerForWindows.ps1
|
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$princ = New-Object System.Security.Principal.WindowsPrincipal($identity)
if(!$princ.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
{
$powershell = [System.Diagnostics.Process]::GetCurrentProcess()
$psi = New-Object System.Diagnostics.ProcessStartInfo $powerShell.Path
$script = $MyInvocation.MyCommand.Path
$prm = $script
foreach($a in $args) {
$prm += ' ' + $a
}
$psi.Arguments = $prm
$psi.Verb = "runas"
[System.Diagnostics.Process]::Start($psi) | Out-Null
return;
}
#-------------------------------------------------------------------------------------
Function New-SymLink ($link, $target)
{
if (test-path -pathtype container $target)
{
$command = "cmd /c mklink /d"
}
else
{
$command = "cmd /c mklink"
}
invoke-expression "$command ""$link"" ""$target"""
}
#-------------------------------------------------------------------------------------
$extName = Read-Host 'Gib den Namen der Komponente ein (z.B. com_joecc)'
Add-Type -AssemblyName System.Windows.Forms
$extPath = Read-Host 'Gib den Pfad zum Projekt der Joomla-Komponente ein ([ENTER] für Ordnerauswahl-Dialog)'
if ([string]::IsNullOrWhiteSpace($extPath)){
write-host 'Der Dialog zur Ordner-Auswahl wurde geöffnet'
$FolderBrowserExt = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
SelectedPath = 'MyDocuments'
}
[void]$FolderBrowserExt.ShowDialog()
$extPath = $FolderBrowserExt.SelectedPath
}
if (!(Test-Path -Path $extPath)){
Write-Host -ForegroundColor Red -Object 'Der Pfad ist ungültig - Abbruch!'
exit 1
}
$jPath = Read-Host 'Gib den Pfad zur Joomla Installation ein ([ENTER] für Ordnerauswahl-Dialog)'
if ([string]::IsNullOrWhiteSpace($jPath)){
write-host 'Der Dialog zur Ordner-Auswahl wurde geöffnet'
$FolderBrowserJ = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
SelectedPath = 'c:\wamp\www'
}
[void]$FolderBrowserJ.ShowDialog()
$jPath = $FolderBrowserJ.SelectedPath
}
if (!(Test-Path -Path $extPath)){
Write-Host -ForegroundColor Red -Object 'Der Pfad ist ungültig - Abbruch!'
exit 1
}
$answer = Read-Host -Prompt ([string]::Format('Ich werde die Komponente im Ordner {0} mit der Joomla-Installation {1} verknüpfen. Korrekt? (J/N) [ENTER = J]',$extPath,$jPath))
$answer = $answer.ToLower()
if (($answer -ne 'j') -and !([string]::IsNullOrWhiteSpace($answer))){
Write-Host -ForegroundColor Red -Object 'Ok, du wolltest nicht! Also hab ich aufgehört...'
exit 0
}
Write-Host -ForegroundColor Green -Object 'Ok, los geht''s!'
Write-Host 'Erstelle Admin-Verknüpfung'
$extPathAdmin = Join-Path -ChildPath 'admin' -Path $extPath
$jPathAdmin = Join-Path -ChildPath 'administrator\components' -Path $jPath
$jPathAdmin = Join-Path -childPath $extName -Path $jPathAdmin
Remove-Item $jPathAdmin -Force -Recurse
New-SymLink $jPathAdmin $extPathAdmin
Write-Host 'Erstelle Site-Verknüpfung'
$extPathSite = Join-Path -ChildPath 'site' -Path $extPath
$jPathSite = Join-Path -ChildPath 'components' -Path $jPath
$jPathSite = Join-Path -childPath $extName -Path $jPathSite
Remove-Item $jPathSite -Force -Recurse
New-SymLink $jPathSite $extPathSite
Write-Host 'Erstelle Media-Verknüpfung'
$extPathMedia = Join-Path -ChildPath 'media' -Path $extPath
$jPathMedia = Join-Path -ChildPath 'media' -Path $jPath
$jPathMedia = Join-Path -childPath $extName -Path $jPathMedia
Remove-Item $jPathMedia -Force -Recurse
New-SymLink $jPathMedia $extPathMedia
Write-Host -ForegroundColor Green -Object 'Alles gemacht! Viel Spass beim coden...'
|
PowerShellCorpus/GithubGist/guitarrapc_e78bbd4ddc07389e17d6_raw_2e058ed77e51327a14195d8aaa91268ddafa145b_Copy-StrictedFilterFileWithDirectoryStructure.ps1
|
guitarrapc_e78bbd4ddc07389e17d6_raw_2e058ed77e51327a14195d8aaa91268ddafa145b_Copy-StrictedFilterFileWithDirectoryStructure.ps1
|
<#
# Copy "All Directory Structure" and "File" which Extension type is .bat
Copy d:\GitHub\valentia -Destination d:\fuga -Force -Recurse -Filter "*.bat"
# Copy "All Directory Structure" and "File" which Extension type is .md
Copy d:\GitHub\valentia -Destination d:\fuga -Force -Recurse -Filter "*.md"
# If you want to exclude specific file to copy
Get-ChildItem -Path $Destination -Recurse -File | where Name -in Readme_J.md | Remove-Item -Recurse
# search Folder which include file
$hoge = ls d:\fuga -Recurse -Directory | where {$_.GetFiles()}
# Remove All Empty (none file exist) folders
ls d:\fuga -Recurse -Exclude $hoge -Directory | Remove-Item -Recurse
#>
function Copy-StrictedFilterFileWithDirectoryStructure
{
[CmdletBinding()]
param
(
[parameter(
mandatory = 1,
position = 0,
ValueFromPipeline = 1,
ValueFromPipelineByPropertyName = 1)]
[string]
$Path,
[parameter(
mandatory = 1,
position = 1,
ValueFromPipelineByPropertyName = 1)]
[string]
$Destination,
[parameter(
mandatory = 1,
position = 2,
ValueFromPipelineByPropertyName = 1)]
[string[]]
$Targets,
[parameter(
mandatory = 0,
position = 3,
ValueFromPipelineByPropertyName = 1)]
[string[]]
$Excludes
)
begin
{
$list = New-Object 'System.Collections.Generic.List[String]'
}
process
{
Foreach ($target in $Targets)
{
# Copy "All Directory Structure" and "File" which Extension type is $ex
Copy-Item -Path $Path -Destination $Destination -Force -Recurse -Filter $target
}
}
end
{
# Remove -Exclude Item
Foreach ($exclude in $Excludes)
{
Get-ChildItem -Path $Destination -Recurse -File | where Name -like $exclude | Remove-Item
}
# search Folder which include file
$allFolder = Get-ChildItem $Destination -Recurse -Directory
$containsFile = $allFolder | where {$_.GetFiles()}
$containsFile.FullName `
| %{
$fileContains = $_
$result = $allFolder.FullName `
| where {$_ -notin $list} `
| where {
$shortPath = $_
$fileContains -like "$shortPath*"
}
$result | %{$list.Add($_)}
}
$folderToKeep = $list | sort -Unique
# Remove All Empty (none file exist) folders
Get-ChildItem -Path $Destination -Recurse -Directory | where fullName -notin $folderToKeep | Remove-Item -Recurse
}
}
Copy-StrictedFilterFileWithDirectoryStructure -Path d:\GitHub\valentia -Destination D:\fuga -Target *.bat, *.md -Exclude Readme_J.md
# Sample
# Copy-StrictedFilterFileWithDirectoryStructure -Path D:\GitHub\valentia -Destination D:\fuga -Targets *.bat, *.md
# Sample : -Exlude item will not exit in copied folder
# Copy-StrictedFilterFileWithDirectoryStructure -Path d:\GitHub\valentia -Destination D:\fuga -Targets *.bat, *.md -Excludes Readme*.md
|
PowerShellCorpus/GithubGist/JingwenTian_8875701_raw_73ede657e39566fd054fac099aa47f60dfb758f3_gistfile1.ps1
|
JingwenTian_8875701_raw_73ede657e39566fd054fac099aa47f60dfb758f3_gistfile1.ps1
|
#删除sth目录下文件
git rm sth/* -r
#然后commit
git commit -a -m 'remove sth'
#再次push就可以了
git push -u origin master
#可以增加忽略文件:
vim .gitignore
#在文件中添加
sth/**/*
|
PowerShellCorpus/GithubGist/miriyagi_8475177_raw_38624af708fc2c7b462e69717f26c1675abe2b87_Microsoft.PowerShell_profile.ps1
|
miriyagi_8475177_raw_38624af708fc2c7b462e69717f26c1675abe2b87_Microsoft.PowerShell_profile.ps1
|
Import-Module PSReadLine
Set-PSReadlineOption -EditMode Emacs
Set-PSReadlineKeyHandler -Key UpArrow -Function PreviousHistory
Set-PSReadlineKeyHandler -Key DownArrow -Function NextHistory
Set-PSReadlineKeyHandler -Key Ctrl+I -Function Complete
Set-PSReadlineKeyHandler -Key Ctrl+K -Function KillLine
Set-PSReadlineKeyHandler -Key Ctrl+L -ScriptBlock { Clear-Host; [PSConsoleUtilities.PSConsoleReadline]::KillLine($null, $null) }
Set-PSReadlineKeyHandler -Key Ctrl+N -Function NextHistory
Set-PSReadlineKeyHandler -Key Ctrl+P -Function PreviousHistory
Set-PSReadlineKeyHandler -Key Ctrl+U -Function BackwardKillLine
Set-PSReadlineKeyHandler -Key Ctrl+S -Function HistorySearchForward
Set-PSReadlineKeyHandler -Key Ctrl+V -Function Paste
Set-PSReadlineKeyHandler -Key Ctrl+W -Function BackwardKillWord
Set-PSReadlineKeyHandler -Key Ctrl+LeftArrow -Function BackwardWord
Set-PSReadlineKeyHandler -Key Ctrl+RightArrow -Function ForwardWord
Set-PSReadlineKeyHandler -Key Ctrl+Backspace -Function BackwardKillWord
|
PowerShellCorpus/GithubGist/sebnilsson_6522182_raw_ba4adb7032ddd56bf45c53d44fbfeea199df8bed_chocolatey-unzip-movetoparent.ps1
|
sebnilsson_6522182_raw_ba4adb7032ddd56bf45c53d44fbfeea199df8bed_chocolatey-unzip-movetoparent.ps1
|
$packageName = '{PACKAGE_NAME}'
$url = 'http://SITE.COM/FILE.ZIP'
$subFolderFilter = '*SUBFOLDER*'
try {
$rootDir = Join-Path "$env:systemdrive\" $packageName
if (Test-Path "$rootDir") {
Write-Host "Removing existing files, keeping config-files"
Remove-Item "$rootDir\*" -Recurse -force -exclude *.config
}
Install-ChocolateyZipPackage "$packageName" "$url" "$rootDir"
$subFolder = Join-Path $rootDir (Get-ChildItem $rootDir $subFolderFilter | ?{ $_.PSIsContainer })
Write-Host "Moving items from subfolder"
Get-ChildItem $subFolder -Recurse | ?{$_.PSIsContainer } | Move-Item -Destination $rootDir
Get-ChildItem $subFolder | ?{$_.PSIsContainer -eq $false } | Move-Item -Destination $rootDir
Remove-Item "$subFolder"
Write-ChocolateySuccess "$packageName"
} catch {
Write-ChocolateyFailure "$packageName" "$($_.Exception.Message)"
throw
}
|
PowerShellCorpus/GithubGist/canoas_8976244_raw_445127140653fd6a2284b6bd48cf4239155d7ee3_Clear-TMGCachedUrl.ps1
|
canoas_8976244_raw_445127140653fd6a2284b6bd48cf4239155d7ee3_Clear-TMGCachedUrl.ps1
|
param(
$url = (Read-Host "Url? e.g http://www.maxfinance.pt/img/frame5.jpg")
)
begin {
$tmgroot = new-object -comobject FPC.Root
$tmgarray = $tmgroot.GetContainingArray()
$myCache = $tmgArray.Cache.CacheContents
$regex = ‘([a-zA-Z]{3,})://([\w-\.]+)(/[\w- ./?%&=]*)*?’
}
process {
if($url -match $regex) {
$hostname = $Matches[2]
$ip =[System.Net.Dns]::GetHostAddresses($hostname) | select -ExpandProperty IPAddressToString
$cachedUrl = $url.Replace($Matches[0], "zttp://$ip/$hostname")
try {
$myCache.FetchUrl("", $cachedUrl ,0,0) # "","zttp://83.240.174.194/www.maxfinance.pt/img/frame7.jpg",customTTL,fpcTtlIfNon
Write-host -ForegroundColor green "Done clearing $cachedUrl"
}
catch {
if($_.Exception.Message.Contains("The system cannot find the file specified")) {
Write-Warning "Cache Hit not found!"
}
else
{
throw
}
}
}
else
{
write-warning "Error parsing url"
$Matches
}
}
|
PowerShellCorpus/GithubGist/joshtransient_5984713_raw_0692c891ab3d7da9e313c77a4cba9e66bd45544a_Recover-SecureStoreCredentials.ps1
|
joshtransient_5984713_raw_0692c891ab3d7da9e313c77a4cba9e66bd45544a_Recover-SecureStoreCredentials.ps1
|
<#
.SYNOPSIS
Secure Store Credential Extraction
.NOTES
Author: Josh Leach, Critigen
Date: 27 Mar 2013
Adapted from http://msdn.microsoft.com/en-us/library/ff394459(v=office.14).aspx
.DESCRIPTION
Pulls information about Secure Store target applications. The account running this script must be a member of each Secure Store app, otherwise you'll receive access denied.
.PARAMETER AppName
[All (default)|<Target Application ID>]: Name of the secure store target application, or all of them.
.PARAMETER Retrieve
[Credentials (default)|Admins|Members]: Retrieve stored credentials, target application administrators, or target application members.
.EXAMPLE
.\storextract.ps1 -AppName 'MySecStoreApplication' -Retrieve Credentials
Gets stored credentials from MySecStoreApplication.
.EXAMPLE
.\storextract.ps1 -Retrieve Members
Retrieves all claims for members of every secure store target application.
#>
# Some parameters!
Param (
[string]$AppName = 'All',
[string][ValidateSet('Credentials','Admins','Members')]$Retrieve = 'Credentials'
)
#REGION Globals and Functions
# Instantiate local Admin web app
$admin = [microsoft.sharepoint.administration.spadministrationwebapplication]::Local
# Check for use of AppName param, instantiate store
if($AppName -eq 'All') {
$store = Get-SPSecureStoreApplication -ServiceContext $admin.url -All
} else {
$store = Get-SPSecureStoreApplication -ServiceContext $admin.url -Name "$AppName" -ErrorAction Stop
}
Function Retrieve-Credentials {
# Grab the SPSite for the SecStore Provider's context
$aSite = Get-SPSite $admin.url
# Set up SecStore provider
$issp = [microsoft.office.securestoreservice.server.securestoreproviderfactory]::Create()
$issp.Context = [microsoft.sharepoint.spservicecontext]::GetContext($aSite)
# Set up an array for output mechanism
$data = @()
# Enum through each SecStore app, then through the stored credentials
foreach($app in $store) { foreach($cred in $issp.GetCredentials($app.TargetApplication.ApplicationId)) {
$row = '' | Select-Object AppID,CredType,Value
$row.AppID = $app.TargetApplication.ApplicationId
$row.CredType = $cred.CredentialType.ToString()
# Good one-liner for decrypting a SecureString. Stolen from:
# http://blogs.msdn.com/b/timid/archive/2009/09/09/powershell-one-liner-decrypt-securestring.aspx
$row.Value = [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($cred.Credential))
$data += $row
}}
$data
}
Function Retrieve-Users {
# Not worried about validating set here since we do it in the main script params
Param([string]$UserType)
$data = @()
# Enum through each SecStore app...
foreach($app in $store) {
# ...then determine which set of claims to get
if($users -eq 'Admins') { $claims = $app.TargetApplicationClaims.AdministratorClaims }
else { $claims = $app.TargetApplicationClaims.GroupClaims }
$claims |% {
$row = '' | Select-Object AppId,ClaimType,Value
$row.AppId = $app.TargetApplication.ApplicationId
$row.ClaimType = $_.ClaimIssuer
$row.Value = $_.ClaimValue
$data += $row
}
}
$data
}
#ENDREGION
#REGION Main Program
if($Retrieve -eq "Credentials") { Retrieve-Credentials }
else { Retrieve-Users -UserType $Retrieve }
#ENDREGION
|
PowerShellCorpus/GithubGist/ferventcoder_9788258_raw_0991fc0ea1d535fc5b9ce99e432fd9a848103682_UserAdd.ps1
|
ferventcoder_9788258_raw_0991fc0ea1d535fc5b9ce99e432fd9a848103682_UserAdd.ps1
|
param (
[parameter(Position=0)]
[alias("user")][string]$userName,
[alias("group")][string]$groupName=$null,
[alias("home")][string]$homeDirectory=$null
)
# there are some much simpler ways to do this with the Active-Directory Module
# like Get-ADUser, Set-ADUser, etc but it is not installed on Win2008 (non-R2)
# and below so we want to prefer what works natively for all Windows machines
if ($userName -eq $null) { return "Error: Please pass in a User Name" }
$groups = @()
$currentHomeDirectory = $null
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
# these do not return null
#$adsiUser = [ADSI]("WinNT://$env:COMPUTERNAME/$userName")
#$adsiGroup = [ADSI]("WinNT://$env:COMPUTERNAME/$groupName")
$adsiUser = $adsi.Children | ?{$_.SchemaClassName -eq 'user'} | ?{$_.Name.ToString().ToLower() -eq "$userName".ToLower()}
if ($adsiUser -eq $null) {
# we are creating the user
$newUser = $adsi.Children.Add("$userName","user")
#$newUser.Invoke("Put", { "Description", "Test Group from .NET" });
$newUser.CommitChanges()
$adsiUser = $newUser
} else {
$groups = $adsiUser.Groups() | %{$_.GetType().InvokeMember("Name", "GetProperty", $null, $_, $null)}
$currentHomeDirectory = $adsiUser.HomeDirectory.Value
}
if ($groupName -ne $null) {
# does the group exist?
$adsiGroup = $adsi.Children | ?{$_.SchemaClassName -eq 'group'} | ?{$_.Name.ToString().ToLower() -eq "$groupName".ToLower()}
if ($adsiGroup -eq $null) {
# create the group
$newGroup = $adsi.Children.Add("$groupName","group")
$newGroup.CommitChanges()
$adsiGroup = $newGroup
}
# is the user in the group?
if (! ($groups -contains "$groupName")) {
#put the user in the group
$adsiGroup.PSBase.Invoke("Add",$adsiUser.PSBase.Path)
}
}
# this may or may not be the correct thing to do because of HOMEDRIVE
if ($homeDirectory -ne $null) {
# does the user have the home directory set properly?
if ($currentHomeDirectory -ne $homeDirectory) {
$adsiUser.HomeDirectory = "$homeDirectory"
$adsiUser.CommitChanges()
}
}
|
PowerShellCorpus/GithubGist/jasonf_8d0343f0fe8f0456b05c_raw_43028a1948f71780e3193118937ef3f753a614a2_get-advanced-setting-cluster.ps1
|
jasonf_8d0343f0fe8f0456b05c_raw_43028a1948f71780e3193118937ef3f753a614a2_get-advanced-setting-cluster.ps1
|
# Change the following variables
$vcenter = "myvcenter.domain.local"
# Advanced setting value to find
$advanced_setting = "Misc.SIOControlFlag2"
#cluster to check
$cluster_name = "cluster_name"
# No changes past this point
Connect-VIServer $vcenter -Credential (Get-Credential)
Get-AdvancedSetting -Entity (Get-Cluster $cluster_name | Get-VMHost) -Name $advanced_setting |
select entity,name,value
Disconnect-VIserver
|
PowerShellCorpus/GithubGist/jeffpatton1971_d8460a45117192817ef3_raw_29f4c2eb8af2942ada87278a3596ed2febc75d81_Set-ZenossPermissions.ps1
|
jeffpatton1971_d8460a45117192817ef3_raw_29f4c2eb8af2942ada87278a3596ed2febc75d81_Set-ZenossPermissions.ps1
|
<#
.SYNOPSIS
Setup permissions for Zenoss monitoring on Windows
.DESCRIPTION
This script works under the assumption that you have a GPO or manually added your zenoss user to several groups.
In testing these are the groups that appear to work
Backup Operators
Distributed COM Users
Event Log Readers
Performance Log Users
Performance Monitor Users
Users
This script will setup the zenoss user to access the WMI namespace root, and all nodes below. If this isn't
what you want comment out the two lines with $Inheritance in them.
.PARAMETER Class
This is the ROOT class by default, but could be any class you wish
.PARAMETER Principal
This is the DOMAIN\Username of your monitoring account
.EXAMPLE
.\Set-ZenossPermissions.ps1 -Principal "Domain\Username"
Description
-----------
This is the only syntax for this script.
.NOTES
ScriptName : Set-ZenossPermissions.ps1
Created By : jspatton
Date Coded : 12/23/2014 16:58:30
ScriptName is used to register events for this script
ErrorCodes
100 = Success
101 = Error
102 = Warning
104 = Information
This should be run elevated
.LINK
https://gist.github.com/jeffpatton1971/d8460a45117192817ef3
.LINK
http://community.zenoss.org/docs/DOC-4517
.LINK
http://tech.lanesnotes.com/2010/07/how-to-delegate-services-control-in.html
#>
[CmdletBinding()]
Param
(
[string]$Class = "root",
[string]$Principal = "DOMAIN\UserName"
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName 'Windows Powershell' -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
# Dotsource in the functions you need.
}
Process
{
$security = Get-WmiObject -Namespace $Class -Class __SystemSecurity
$binarySD = @($null)
$result = $security.PsBase.InvokeMethod("GetSD",$binarySD)
$ID = new-object System.Security.Principal.NTAccount($Principal)
$sid = $ID.Translate( [System.Security.Principal.SecurityIdentifier] ).toString()
#
# Convert the current permissions to SDDL
#
$converter = new-object system.management.ManagementClass Win32_SecurityDescriptorHelper
$CurrentWMISDDL = $converter.BinarySDToSDDL($binarySD[0])
#
# Set SDDL
#
$InheritanceSDDL = "(A;CI;CCDCLCSWRPWPRCWD;;;BA)"
$RemoteEnableSDDL = "(A;CI;CCDCWP;;;$($sid))"
#
# Assign SDDL
#
$NewWMISDDL = $CurrentWMISDDL.SDDL += $InheritanceSDDL
$NewWMISDDL = $CurrentWMISDDL.SDDL += $RemoteEnableSDDL
#
# Convert SDDL back to Binary
#
$WMIbinarySD = $converter.SDDLToBinarySD($NewWMISDDL)
$WMIconvertedPermissions = ,$WMIbinarySD.BinarySD
$result = $security.PsBase.InvokeMethod("SetSD",$WMIconvertedPermissions)
if($result='0'){write-host "`t`tApplied WMI Security complete."}
#
# Configure non-admin access to services
#
$scSDDL = (Invoke-Expression -Command "cmd /c sc sdshow SCMANAGER")|ForEach-Object {if ($_){$_}}
$dSDDL = $scSDDL.Substring(0, $scSDDL.IndexOf("S:"))
$mySDDL = "(A;;CCLCRPRC;;;$($sid))"
$sSDDL = $scSDDL.Substring($scSDDL.IndexOf("S:"),($scSDDL.Length) - ($scSDDL.IndexOf("S:")))
$newSDDL = "$($dSDDL)$($mySDDL)$($sSDDL)"
Start-Process -FilePath cmd.exe -ArgumentList "/c sc sdset SCMANAGER $($newSDDL)"
#
# Open Remote Administration firewall ports
#
Start-Process -FilePath netsh -ArgumentList "firewall set service remoteadmin enable"
#
# Restart WMI Service
#
Restart-Service -Name Winmgmt -Force
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
}
|
PowerShellCorpus/GithubGist/andreaswasita_974272eba92eb505c220_raw_09a674861560642fd2ad25751aec4c50418f9148_Get-AzureVMExtensionAntiMalware.ps1
|
andreaswasita_974272eba92eb505c220_raw_09a674861560642fd2ad25751aec4c50418f9148_Get-AzureVMExtensionAntiMalware.ps1
|
$servicename = "AzureVMAntiMalware"
$name = "MyAzureVM01"
# Get Azure VM
$vm = Get-AzureVM –ServiceName $servicename –Name $name
# Get Microsoft Antimalware Agent Azure Virtual Machine Status
Get-AzureVMExtension -Publisher Microsoft.Azure.Security -ExtensionName IaaSAntimalware -Version 1.* -VM $vm.VM
|
PowerShellCorpus/GithubGist/mhinze_1571601_raw_dd45f9370ea204cf56add69a0ca8ec6fadddbd7a_ac.ps1
|
mhinze_1571601_raw_dd45f9370ea204cf56add69a0ca8ec6fadddbd7a_ac.ps1
|
function global:aspcomp()
{
$dir = Join-Path $solutionScriptsContainer "..\Your.Web.Project" -Resolve
$bin = Join-Path $dir "bin"
$compiler = Join-Path $([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) "aspnet_compiler.exe"
& $compiler -p $dir -v $bin
}
|
PowerShellCorpus/GithubGist/WilbertOnGithub_2137097_raw_4a275fa81e678dfaee37c3550b31db61cfa72e71_postgitsvn.ps1
|
WilbertOnGithub_2137097_raw_4a275fa81e678dfaee37c3550b31db61cfa72e71_postgitsvn.ps1
|
# Script that cleans up an entire directory with Git repositories
# that have been imported from Subversion using the 'git svn clone'
# command.
# It does the following:
# - Recurses through all subdirectory in the directory you specify.
# For each git repository in a subdirectory:
# - Parses all tags from the remote branches and creates explicit
# git tags.
# - Parses all other remote branches and creates local branches
# from them.
# Basically, it follows the workflow as described here on StackOverflow
# http://stackoverflow.com/a/3972103/33671
# This script assumes that git is in your path.
Param
(
[Parameter(Mandatory = $True)]
[string]$DirectoryWithGitRepositories
)
# Strip all leading whitespace from the 'git branch -r' command.
function StripWhiteSpace([array]$RemoteBranches)
{
$Stripped=@()
foreach ($RemoteBranch in $RemoteBranches)
{
$RemoteBranch = $RemoteBranch -replace "^\s*", ""
$Stripped = $Stripped + $RemoteBranch
}
return $Stripped
}
# Retrieve all branches that should become tags.
function GetAllTags ([array]$RemoteBranches)
{
$Tags = @{}
foreach ($RemoteBranch in $RemoteBranches)
{
if ($RemoteBranch -match "tags/(.*)")
{
# Remove %20 characters and make everything lowercase
$FilteredValue = $matches[1] -replace "%20", "-"
$Tags[$RemoteBranch] = $FilteredValue.ToLower()
}
}
return $Tags
}
# Retrieve all branches that are *not* tags.
# Discard default 'trunk' branch
function GetAllNonTags ([array]$RemoteBranches)
{
$Branches = @{}
foreach ($RemoteBranch in $RemoteBranches)
{
if ($RemoteBranch -match "^tags/" -or $RemoteBranch -eq "trunk")
{
# Nothing
}
else
{
$Key = "remotes/" + $RemoteBranch
$Branches[$Key] = $RemoteBranch
}
}
return $Branches
}
# Actually create the local branches
function CreateLocalBranches($Branches)
{
Write-Host "Found" $Branches.Count "branches in remote."
if ($Branches.Count -gt 0)
{
Write-Host "Creating local branches..."
$Branches.GetEnumerator() | Foreach-Object {
Write-Host "git branch" $_.Value $_.Key
git branch $_.Value $_.Key
Write-Host
}
}
Write-Host
}
# Actually create the local tags
function CreateTags ($Tags)
{
Write-Host "Found" $Tags.Count "tagbranches in remote"
if ($Tags.Count -gt 0)
{
Write-Host "Creating local tags..."
$Tags.GetEnumerator() | Foreach-Object {
Write-Host "git branch" $_.Value $_.Key
git branch $_.Value $_.Key
Write-Host "git tag" $_.Value $_.Value
git tag $_.Value $_.Value
Write-Host "git branch -D" $_.Value
git branch -D $_.Value
Write-Host
}
}
}
# The fun starts here...
$items = Get-ChildItem -Path $DirectoryWithGitRepositories
foreach ($item in $items)
{
if ($item.Attributes -eq "Directory")
{
Write-Host "Switching to" $item.FullName
pushd $item.FullName
[array]$RemoteBranches = git branch -r
$RemoteBranches = StripWhiteSpace ($RemoteBranches)
CreateTags (GetAllTags ($RemoteBranches))
CreateLocalBranches (GetAllNonTags ($RemoteBranches))
popd
}
}
Write-Host "Done."
|
PowerShellCorpus/GithubGist/matthewhatch_a5d31fed0b03ed8bef61_raw_ae8ab44e17af5e404ecbf7ee3b4c795b146c900c_gistfile1.ps1
|
matthewhatch_a5d31fed0b03ed8bef61_raw_ae8ab44e17af5e404ecbf7ee3b4c795b146c900c_gistfile1.ps1
|
<#
These are the functions I use to update my configuration database. This is a custom database that I use to organize DSC configuration
GUIDs and there associated servers. I track configuration versions and some other information.
For other appliacations the queries would change, but the concepts are the same. I have these functions in a module and only one of the
functions is exported, the other two are private. I tend to use __ to preix my private functions so I can identify them quickly.
Also, in the Update-ServerConfiguration function I add default values for the database server and the database name... this makes it
easier to use. I removed them here since they I don't feel like sharing my server and database names with everyone!
#>
function __connect-SQL{
param(
[string]$connectionString
)
try{
Write-Verbose "Setting up SQL Connection using $connectionString"
$sqlConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = $connectionString
Write-Verbose "Connected to $Database on $DatabaseServer"
Write-Output $sqlConnection
}
catch{
Throw [System.Exception] $Error[0]
}
}
function __update-SQLData{
param(
[System.Data.SqlClient.SqlConnection]$SqlConnection,
[System.String]$Query
)
Write-Verbose "Running query: $Query"
$SqlConnection.open()
Write-Debug "SQLConnection in Update private function: $($SqlConnection.State)"
$sqlCommand = New-Object "System.data.sqlclient.sqlcommand"
$sqlCommand.Connection = $SqlConnection
#$command = $sqlConnection.CreateCommand()
$sqlCommand.CommandTimeout = 3000
$sqlCommand.CommandText = $Query
Write-Verbose "Query Command Created"
Write-Verbose "Updating data"
Write-Debug "Query: $Query"
Write-Debug "SQLCommand CommandText: $($sqlCommand.CommandText)"
$rowsAffected = $sqlCommand.ExecuteNonQuery()
Write-Output $rowsAffected
}
function Update-ServerConfiguration{
<#
.SYNOPSIS
Updates a server's GUID in the Configuration Database
.DESCRIPTION
Updats the Configuration management Database with the NEw GUID for the target machine
.PARAMETER ComputerName
Target server
.PARAMETER GUID
GUID to assign the target server
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[string]$ComputerName,
[string]$GUID,
[string]$DataBaseServer,
[string]$DataBase
)
BEGIN{
[string]$connectionString = "server=$DataBaseServer;database=$DataBase;trusted_connection=True"
try{
$sqlConnection = __connect-SQL -connectionString $connectionString
}
catch{
Throw [System.Exception] $Error[0]
}
}
PROCESS{
[string]$query = "Update Server `
Set ConfigInstanceGUID = '$GUID'`
Where Name = '$ComputerName'"
if($PSCmdlet.ShouldProcess("$ComputerName`: Updating to $GUID")){
Write-Debug "SQLCOnnection Connection String: $($sqlConnection.ConnectionString)"
Write-Debug "SQLConnection State: $($sqlConnection.State)"
$rowsAffected = __update-SQLData -SqlConnection $sqlConnection -Query $Query
Write-Verbose "Update Complete. row(s) affected: $rowsAffected"
}
}
END{
Write-Verbose "Closing SQL Connection"
$sqlConnection.Close()
}
}
|
PowerShellCorpus/GithubGist/dfinke_064c149320244f62520c_raw_91ac3d66d0f0259085bfa31e6fd46132b6109e6a_MagicSquares.ps1
|
dfinke_064c149320244f62520c_raw_91ac3d66d0f0259085bfa31e6fd46132b6109e6a_MagicSquares.ps1
|
1..10 | ForEach {
$r = 0..($_-1) -join ''
$exp = "$($r)*9+$_"
"{0,15}={1}" -f $exp, ($exp|Invoke-Expression)
}
''
1..9 | ForEach {
$r = 1..($_) -join ''
$exp = "$($r)*8+$_"
"{0,15}={1}" -f $exp, ($exp|Invoke-Expression)
}
|
PowerShellCorpus/GithubGist/zachbonham_2635944_raw_ae1c17030bd71cbe23c9829a7d1b4e1bbe7763bf_remote.ps1
|
zachbonham_2635944_raw_ae1c17030bd71cbe23c9829a7d1b4e1bbe7763bf_remote.ps1
|
function invoke-remoteexpression($computer = “\\$ENV:ComputerName”, [ScriptBlock] $expression = $(throw “Please specify an expression to invoke.”), [switch] $noProfile , $username, $password)
{
$commandLine = “echo . | powershell “
if($noProfile)
{
$commandLine += “-NoProfile “
}
<#
some commands may cause encoding problems so we base64.
#>
$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($expression)
$encodedCommand = [Convert]::ToBase64String($commandBytes)
$commandLine += “-EncodedCommand $encodedCommand”
psexec /acceptEula -u $username -p $password $computer cmd /c $commandLine
}
|
PowerShellCorpus/GithubGist/XPlantefeve_75bde89c6967569d218f_raw_e93d18d7c38b5cd8b59f1d4cccfb16459b712661_Convert-CSVtoXLS.ps1
|
XPlantefeve_75bde89c6967569d218f_raw_e93d18d7c38b5cd8b59f1d4cccfb16459b712661_Convert-CSVtoXLS.ps1
|
#requires -version 4.0
Function Convert-CSVtoXLS {
<#
.SYNOPSIS
This function converts a CSV file to an Excel workbook.
.DESCRIPTION
Convert-CSVtoXLS converts a csv file to a Excel workbook.
The first line of the CSV file is turned into a filtering header.
Excel must be installed on the computer.
.EXAMPLE
PS C:\> Convert-CSVtoXLS myfile.csv
myfile.csv will be converted to myfile.xslx
.EXAMPLE
PS C:\> foreach ($file in (ls *.csv)) { Convert-CSVtoXLS $file }
All csv files in the current folder will be converted.
.NOTES
NAME : Convert-CSVtoXLS
VERSION : 0.8
LAST UPDATED: 20/02/2015
AUTHOR : Xavier Plantefève
.LINK
http://xavier.plantefeve.fr
.INPUTS
Either the file name of the string to be converted (System.String) or the file object (System.IO.FileInfo)
.OUTPUTS
No output.
#>
[CmdletBinding(DefaultParameterSetName='fromstring')]
Param(
# Path of the CSV file to be converted.
[Parameter(Mandatory=$True,Position=0,ValueFromPipeline=$True,ParameterSetName='fromstring')]
[string]$Path,
# CSV file to be converted. Accepts pipeline.
[Parameter(Mandatory=$True,Position=0,ValueFromPipeline=$True,ParameterSetName='fromfile')]
[System.IO.FileInfo]$File,
# The source CSV file will be deleted.
[switch]$DeleteSource,
# If used, the Excel worksheet will be saved to the 97-2003 format.
[switch]$LegacyFormat,
# Delimiter used in the CSV. Defaults to 'SemiColon'
[String][ValidateSet('Comma','Semicolon','Space','Tab')]$Delimiter = 'Semicolon',
# Provides a way to use a non-standard delimiter char. Voids the -Delimiter parameter.
[char]$DelimiterChar,
# A name for the resulting excel worksheet. Defaults to the file base name.
[string]$Name,
# Full path (including filename) of the resulting Excel file.
[string]$DestinationPath,
# Allows overwriting of the Excel file.
[switch]$Force
)
if ( $Path ) {
$File = Get-Item -Path $Path
}
# We set $Path even if it exists, to translate it to a full path.
$Path = $File.FullName
# Format constants: https://msdn.microsoft.com/en-us/library/office/ff198017.aspx
If ($LegacyFormat) {
$XLfilext = '.xls'
$FileFormat = 56
} else {
$XLfilext = '.xlsx'
$FileFormat = 51
}
$excel = New-Object -ComObject excel.application
$excel.Visible = $PSBoundParameters['Verbose']
# Workbook creation
$workbooks = $excel.Workbooks.Add()
$worksheets = $workbooks.Worksheets
$worksheets.Item(3).delete()
$worksheets.Item(2).delete()
$worksheet = $worksheets.Item(1)
if ($Name) {
$worksheet.Name = $Name
} else {
$worksheet.Name = $File.BaseName
}
# CSV Import.
$TxtConnector = ("TEXT;${Path}")
$CellRef = $worksheet.Range('A1')
$Connector = $worksheet.QueryTables.add($TxtConnector,$CellRef)
if ($DelimiterChar) {
$worksheet.QueryTables.Item($Connector.Name).TextFileOtherDelimiter = $DelimiterChar
} else {
$worksheet.QueryTables.Item($Connector.Name)."TextFile${Delimiter}Delimiter" = $true
}
$worksheet.QueryTables.Item($Connector.Name).TextFileParseType = 1
[void] $worksheet.QueryTables.Item($Connector.Name).Refresh()
[void] $worksheet.QueryTables.Item($Connector.Name).delete()
If ($worksheet.Cells.Item(1,1).Text -like '#TYPE*') {
[void] $worksheet.Rows.Item(1).Delete()
}
# A bit of formatting, because we're shallow and like when things look nice.
# (I'm joking, this is for the managers to be happy)
[void] $worksheet.UsedRange.EntireColumn.AutoFit()
$worksheet.Rows.Item(1).Font.Bold = $true
[void] $worksheet.Rows.Item(1).AutoFilter()
[void] $workSheet.Activate()
$worksheet.Application.ActiveWindow.SplitRow = 1;
$workSheet.Application.ActiveWindow.FreezePanes = $true;
# We save the file and quit.
if (!$DestinationPath) {
$DestinationPath = "$($File.DirectoryName)\$($File.BaseName)${XLfilext}"
} else {
If ((Split-Path -Path $DestinationPath) -in '.','') {
$DestinationPath = "$($pwd.ProviderPath)\$(Split-Path -Path $DestinationPath -Leaf)"
}
}
If ($Force -AND (Test-Path -Path $DestinationPath)) { Remove-Item -Path $DestinationPath }
$workbooks.SaveAs($DestinationPath,$FileFormat)
$excel.quit()
[void] [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
If ($DeleteSource) { Remove-Item -Path $Path }
} #function
# creates an alias for the function
Set-Alias -Name csv2xls -Value Convert-CSVtoXLS
|
PowerShellCorpus/GithubGist/jstangroome_519103_raw_b0722820dc1ebe562f58c6761c0ee95e69c5e28b_Import-PSISEProfile.ps1
|
jstangroome_519103_raw_b0722820dc1ebe562f58c6761c0ee95e69c5e28b_Import-PSISEProfile.ps1
|
if ($psise) {
if (!(test-path $profile)) { new-item $profile -fo -it file }
$e = $psise.CurrentPowerShellTab.Files.Add($profile).Editor
$col = $e.GetLineLength($e.LineCount)+1
$e.Select($e.LineCount,$col,$e.LineCount,$col)
$e.InsertText("`n" + (new-object Net.WebClient).DownloadString(
'http://gist.github.com/raw/518638/3e0beb7a5a6ddc19446d5a6d38c8267794c92eba/Microsoft.PowerShellISE_profile.ps1'
))
} else { throw 'Run this script using the ISE' }
|
PowerShellCorpus/GithubGist/pkskelly_e102177227b214500fff_raw_87713dab5af279d839fc35c0228e5d195fed72e6_TW-CreateBlankClientExtranetSite.ps1
|
pkskelly_e102177227b214500fff_raw_87713dab5af279d839fc35c0228e5d195fed72e6_TW-CreateBlankClientExtranetSite.ps1
|
# =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
# Script: TW-CreateBlankClientExtranetSite.ps1
#
# Author: Pete Skelly
# Twitter: ThreeWillLabs
# http://www.threewill.com
#
# Description: Add a blank site collection to an Office 365 tenant in SharePoint Online
#
# WARNING: Script provided AS IS with no warranty. Your mileage will vary. Use
# this script on a production list AT YOUR OWN RISK.
#
#
#
# NOTES / CREDITS: Script based on (among others) http://alexbrassington.com/2014/08/20/creating-sharepoint-site-collection-through-powershell-csom/
# Next to incorporate is the use of a WSP for Client Extranets like http://blogs.msdn.com/b/frank_marasco/archive/2014/08/10/upload-and-activate-sandbox-solutions-using-csom.aspx
#
# =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
#Add the dlls required for working with Office 365
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.Online.SharePoint.Client.Tenant.dll"
#URLs and prerequisites
$adminSiteUrl = "<tenant-admin-url>"
$newsiteUrl = "<tenant-url> + /teams/ + <site_name>" #OR whatever you wish
$username = "<username>"
$password = Read-Host "Please enter your Password" -AsSecureString
Write-Host "Establishing Connection to Office 365."
#Get the context and feed in the credentials
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($adminSiteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials
Write-Host "Configuring the new Site Collection"
#Get the tenant object
$tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant($ctx)
#Set the Site Creation Properties values
$properties = New-Object Microsoft.Online.SharePoint.TenantAdministration.SiteCreationProperties
$properties.Url = $newsiteUrl
## TODO: DO NOT Set this and wait until the site template can be added
$properties.Template = "STS#0"
$properties.Owner = $username
$properties.StorageMaximumLevel = 500
$properties.UserCodeMaximumLevel = 100
#Create the site using the properties
## this is the original script
##--- $tenant.CreateSite($properties) | Out-Null
#retrieve the SPO Operation return value during creation
$spOnlineOperation = $tenant.CreateSite($properties)
#load the tenant object
$ctx.Load($tenant)
#load the SPO operation
$ctx.Load($spOnlineOperation)
#run the command
$ctx.ExecuteQuery()
#wait for SPO Operation to complete
while($spOnlineOperation.IsComplete -eq $false)
{
write-host “Waiting…” -ForegroundColor Yellow
Start-Sleep 10
$spOnlineOperation.RefreshLoad()
$tenantCtx.ExecuteQuery()
}
Write-Host "Completed creation of site collection."
|
PowerShellCorpus/GithubGist/bkeele_2491944_raw_7c48bbfec20e8b29a2db2b60a04f857ef2ae131f_PreDeploy.ps1
|
bkeele_2491944_raw_7c48bbfec20e8b29a2db2b60a04f857ef2ae131f_PreDeploy.ps1
|
Import-Module WebAdministration
$port = 80
$ssl = $false
$wa = Get-Website | Where {$_.Name -eq $OctopusWebSiteName}
$ap = Get-WebAppPoolState | Where {$_.Name -eq $appPoolName}
if($wa -eq $null)
{
write-host "no web application setup, creating..."
if($ap -eq $null)
{
write-host "no App Pool creating..."
New-WebAppPool $appPoolName
Set-ItemProperty IIS:\AppPools\$appPoolName managedRuntimeVersion v4.0
}
$webApp = New-Website -Name $OctopusWebSiteName -Port $port -HostHeader $hostHeader -ApplicationPool $appPoolName -Ssl:$ssl -PhysicalPath c:\inetpub\wwwroot
if($hostHeaderAlt -ne $null)
{
write-host "adding alt host header"
New-WebBinding -Name $siteName -IPAddress "*" -Port $port -HostHeader $hostHeaderAlt
}
}
else
{
write-host "Web Application Already setup, skipping..."
}
if($webApplication -ne $null)
{
write-host "Web Application defined. Checking if it already exists."
$app = Get-WebApplication -Site $OctopusWebSiteName -Name $webApplication
if ($app -eq $null)
{
write-host "Web Application does not exist. Creating ..."
New-WebApplication -Site $OctopusWebSiteName -Name $webApplication -PhysicalPath "D:\Octopus\Tentacle\Applications\$OctopusPackageNameAndVersion" -ApplicationPool $appPoolName
}
else
{
write-host "Web Application does exist. Updating physical path ..."
$path = 'IIS:\Sites\' + $OctopusWebsiteName + '\' + $webApplication
write-host "Looking for $path"
Set-ItemProperty $path -Name PhysicalPath -Value "D:\Octopus\Tentacle\Applications\$OctopusPackageNameAndVersion"
}
}
if($allowWindowsAuth)
{
$windowsAuthServer = Get-WebConfigurationLock -PSPath "IIS:\" -Filter //windowsAuthentication #-Name enabled
Write-Host "value: " $windowsAuthServer.Value
if($windowsAuthServer.Value -ne $null)
{
Write-Host "Unlocking Windows Auth Override on Server"
Remove-WebConfigurationLock -PSPath "IIS:\" -Filter //windowsAuthentication
}
else
{
Write-Host "Windows Auth Override on Server already set to Allow, skipping..."
}
$webAppSetForWindowAuth = Get-WebConfigurationProperty -filter /system.WebServer/security/authentication/windowsAuthentication -name enabled -location $OctopusWebSiteName
if(!$webAppSetForWindowAuth.Value)
{
Write-Host "Windows Auth not set for this web app, enabling"
Set-WebConfigurationProperty -filter /system.WebServer/security/authentication/windowsAuthentication -name enabled -value true -location $OctopusWebSiteName
}
else
{
Write-Host "Windows Auth is already enabled for the web app $OctopusWebsiteName , skipping..."
}
}
else
{
Write-Host "Use WindowsAuth Not configured, moving on"
}
# I don't think this is needed anymore since all apps by default allow anonymous auth
#cmd /c %windir%\system32\inetsrv\appcmd unlock config /section:anonymousAuthentication
$original_file = 'Web.config'
$destination_file = 'Web.config'
$searchText = 'ELMAH_EMAIL_SUBJECT'
$newText = $OctopusProjectName + ' - Env:' + $OctopusEnvironmentName + ' Server: ' + $OctopusMachineName + ' Ver: ' + $OctopusPackageVersion
Write-Host "Setting Elmah Email Subject to: " + $newText
(Get-Content $original_file) | Foreach-Object {
$_ -replace $searchText, $newText
} | Set-Content $destination_file
Write-Host "Setting ACLs for App_Data folder to let Pulse log correctly"
$directory = "D:\Octopus\Tentacle\Applications\" + $OctopusPackageNameAndVersion + "\App_Data\Pulse.sdf"
Write-Host "checking ACL on: " $directory
if (Test-Path $directory)
{
$acl = Get-Acl $directory
$permission = "IIS AppPool\$appPoolName","Read,ExecuteFile,Write","Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
Write-Host "Setting ACL on: " $directory
$acl.SetAccessRule($accessRule)
$acl | Set-Acl $directory
}
else
{
throw "The dir/file $directory can't be found"
}
|
PowerShellCorpus/GithubGist/boblogdk_6258085_raw_96b9f9ad3da539146f8e8da1cf2f19723c88437b_gistfile1.ps1
|
boblogdk_6258085_raw_96b9f9ad3da539146f8e8da1cf2f19723c88437b_gistfile1.ps1
|
################################################################################################################################
# #
# Generates script of database tables only #
# #
# USAGE: ".\UmbracoCurrentDB.ps1" directly from Visual Studio Console :) #
# #
# ALERT: DOES NOT WORK OUTSIDE VISUAL STUDIO - As it depends on environment variables given by VisualStudio #
# #
################################################################################################################################
####### BEGIN : CONFIGURABLE OPTIONS #######
$server = "."
$database = "Nearmiss_Umbraco_605"
$schema = "dbo"
$output_path = ($(SolutionDir) +"\DBScripts\")
$fileName = "UmbracoCurrentDB.sql"
####### END : CONFIGURABLE OPTIONS #######
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$srv = New-Object ("Microsoft.SqlServer.Management.SMO.Server") ($server)
$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)
# Get the database and table objects
$db = $srv.Databases[$database]
$tbl = $db.tables | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject }
# Set scripter options to ensure schema and data is scripted currectly :)
$scripter.Options.ScriptSchema = $true
$scripter.Options.ScriptData = $true
$scripter.Options.IncludeIfNotExists = $true
$scripter.Options.IncludeDatabaseContext = $true
$scripter.Options.NoCommandTerminator = $false
$scripter.Options.ToFileOnly = $true
$scripter.Options.AppendToFile = $true
$scripter.Options.Indexes = $true
$scripter.Options.DriAll = $true
$scripter.Options.SchemaQualify = $true
$scripter.Options.SchemaQuaiflyForeignKeyReferences = $true
function CopyObjectsToFiles($objects, $outDir) {
if (-not (Test-Path $outDir)) {
[System.IO.Directory]::CreateDirectory($outDir)
}
if (Test-Path $outDir$fileName){
Remove-Item $outDir$fileName
}
$scripter.Options.FileName = $outDir + $fileName
foreach ($o in $objects) {
if ($o -ne $null) {
$schemaPrefix = ""
if ($o.Schema -ne $null -and $o.Schema -ne "") {
$schemaPrefix = $o.Schema + "."
}
Write-Host "Scripting Drop for" $o
#SCRIPT DROPS
$scripter.Options.ScriptDrops = $true
$scripter.EnumScript($o)
}
$scripter.Options.IncludeDatabaseContext = $false
}
foreach ($o in $objects) {
if ($o -ne $null) {
$schemaPrefix = ""
if ($o.Schema -ne $null -and $o.Schema -ne "") {
$schemaPrefix = $o.Schema + "."
}
Write-Host "Scripting Schema And Data for" $o
# SCRIPT CREATES
$scripter.Options.ScriptDrops = $false
$scripter.EnumScript($o)
}
}
}
# Output the scripts
CopyObjectsToFiles $tbl $output_path
Write-Host "All Done"
|
PowerShellCorpus/GithubGist/growse_4745746_raw_3e1780cd62d67eefe612f44dcd689b4ab51f3513_gistfile1.ps1
|
growse_4745746_raw_3e1780cd62d67eefe612f44dcd689b4ab51f3513_gistfile1.ps1
|
Add-Type -Assembly System.ServiceModel.Web,System.Runtime.Serialization
function Read-Stream {
PARAM(
[Parameter(Position=0,ValueFromPipeline=$true)]$Stream
)
process {
$bytes = $Stream.ToArray()
[System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}}
function New-Json {
[CmdletBinding()]
param([Parameter(ValueFromPipeline=$true)][HashTable]$InputObject)
begin {
$ser = @{}
$jsona = @()
}
process {
$jsoni =
foreach($input in $InputObject.GetEnumerator() | Where { $_.Value } ) {
if($input.Value -is [Hashtable]) {
'"'+$input.Key+'": ' + (New-JSon $input.Value)
} else {
$type = $input.Value.GetType()
if(!$Ser.ContainsKey($Type)) {
$Ser.($Type) = New-Object System.Runtime.Serialization.Json.DataContractJsonSerializer $type
}
$stream = New-Object System.IO.MemoryStream
$Ser.($Type).WriteObject( $stream, $Input.Value )
'"'+$input.Key+'": ' + (Read-Stream $stream)
}
}
$jsona += "{`n" +($jsoni -join ",`n")+ "`n}"
}
end {
if($jsona.Count -gt 1) {
"[$($jsona -join ",`n")]"
} else {
$jsona
}
}}
$date=(Get-Date).ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss");
@{BuildNumber="%build.number%"; SvnRevision="%env.BUILD_VCS_NUMBER%"; BuildTime=$date} | New-Json > build.json
|
PowerShellCorpus/GithubGist/peaeater_e1f6a611f61b893ca560_raw_73ff00f2f08a9e23d454ab21ffe8f2d76b817cbe_raw-ocr.ps1
|
peaeater_e1f6a611f61b893ca560_raw_73ff00f2f08a9e23d454ab21ffe8f2d76b817cbe_raw-ocr.ps1
|
<#
Processes raw source pdfs, producing per page: 1 txt, 1 hocr, 1 jpg.
Requires imagemagick w/ ghostscript, tesseract.
Subscripts: pdf2png.ps1, ocr.ps1, hocr.ps1, png2jpg.ps1
#>
param(
[string]$indir = ".",
[string]$outbase = $indir
)
function WebSafe([string]$s) {
return $s.ToLowerInvariant().Replace(" ", "-").Replace("&", "-")
}
$files = ls "$indir\*.*" -include *.pdf
foreach ($file in $files) {
# get metadata from filename
$split = $file.BaseName.Split("_")
$uni = $split[0]
$col = $split[1]
$title = $split[2]
# convert pdf to png per page
& .\pdf2png.ps1 -in $file.FullName
# convert png to txt
& .\ocr.ps1 -ext "png" -indir "$indir\png" -outdir "$indir\txt"
# convert png to xml (hocr)
& .\hocr.ps1 -ext "png" -indir "$indir\png" -outdir "$indir\xml"
# rename hocr extension .html => .xml
ls "$indir\xml\*.html" | foreach-object { ren $_.FullName ((join-path $_.DirectoryName $_.BaseName) + ".xml")}
# create path for jpgs
$uniSafe = WebSafe($uni)
$colSafe = WebSafe($col)
$titleSafe = WebSafe($title)
$jpgdir = "$outbase\$uniSafe\$colSafe\$titleSafe"
if (!(test-path $jpgdir)) {
mkdir $jpgdir
}
# convert .png to .jpg
& .\png2jpg.ps1 -size 1000 -indir "$indir\png" -outdir $jpgdir
# get page count
$pagecount = (ls "$jpgdir\*.*" -include *.jpg).Count
# write metadata to manifest.xml
$manifest = get-content ("$indir\manifest.xml")
$manifest | foreach-object {
$_ -replace '{UNIVERSE}', $uni `
-replace '{COLLECTION}', $col `
-replace '{TITLE}', $title `
-replace '{PAGECOUNT}', $pagecount `
-replace '{OCRTYPE}', 'hocr'
} | set-content "$indir\manifest.xml"
# clean up
rm "$indir\png" -recurse
}
|
PowerShellCorpus/GithubGist/jpoehls_1281866_raw_c2f788bd05f2bc2242d7189060e301456caf9ac9_tortoise-svn.ps1
|
jpoehls_1281866_raw_c2f788bd05f2bc2242d7189060e301456caf9ac9_tortoise-svn.ps1
|
# Helper function for opening the Tortoise SVN GUI from a PowerShell prompt.
# Put this into your PowerShell profile.
# Ensure Tortoise SVN is in your PATH (usually C:\Program Files\TortoiseSVN\bin).
function Svn-Tortoise([string]$Command = "commit") {
<#
.SYNOPSIS
Launches TortoiseSVN with the given command.
Opens the commit screen if no command is given.
List of supported commands can be found at:
http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-automation.html
#>
TortoiseProc.exe /command:$Command /path:"$pwd"
}
Set-Alias tsvn "Svn-Tortoise"
|
PowerShellCorpus/GithubGist/smasterson_ea1fc73f439acb1ec90e_raw_41228f89752fe909381a80bcd58b926624f2c522_VeeamSingleBackupv8.ps1
|
smasterson_ea1fc73f439acb1ec90e_raw_41228f89752fe909381a80bcd58b926624f2c522_VeeamSingleBackupv8.ps1
|
# Load Veeam snapin
Add-PsSnapin -Name VeeamPSSnapIn -ErrorAction SilentlyContinue
Clear-Host
Write-Host "Veeam Single VM Backup Script`n"
Write-Host "Notes:"
Write-Host "VM must be explicitly defined in the job"
Write-Host "VM can not be inherited by a folder, datastore or other object"
Write-Host "else it will get excluded as well and job will be empty."
Write-Host "Always confirm job completion via Veeam BR Console!"
# Check Veeam Version (Must be v8)
If ((Get-PSSnapin VeeamPSSnapin).Version.Major -ne 8) {
Write-Host "You must be running VBR v8 to run this script...Exiting"
Exit
}
# User Input
$jobName = Read-Host "Enter Job Name"
$vmName = Read-Host "Enter VM Name"
# Find the job that has our VM
$job = Get-VBRJob | ?{$_.Name -eq $jobName}
# Get all objects in job apart from our target VM
$execObjs = $job.GetObjectsInJob() | ?{$_.Name -ne $vmName}
# Exclude the objects from the job
Remove-VBRJobObject -Objects $execObjs
# Start the job only backing up the target VM
$runJob = Start-VBRJob -Job $job
# Find the exclude job objects
$incObjs = $job.GetObjectsInJob() | ?{$_.Type -eq "Exclude"}
# Delete the exclude objects and re-add to job
foreach ($obj in $incObjs) {
$Excitem = Find-VBRViEntity -Name $obj.Name
Add-VBRViJobObject -job $Job -Entities $Excitem | Out-Null
$obj.Delete()
}
Write-Host "`nBackup Complete"
|
PowerShellCorpus/GithubGist/senpost_9514766_raw_dd8b97aa5ea867dd6004fade8c2fa520ba091ead_gistfile1.ps1
|
senpost_9514766_raw_dd8b97aa5ea867dd6004fade8c2fa520ba091ead_gistfile1.ps1
|
$tags = @"
FFFEE000
FFFEE00D
FFFEE0DD
"@
$tags -split '\n' | foreach{
$_.Insert(4,', ') | echo
};
#Formatted output will look like this
<#
FFFE, E000
FFFE, E00D
FFFE, E0DD
#>
|
PowerShellCorpus/GithubGist/stej_507000_raw_b60391568c1ede87d3f6a1e4d2d41c1ab03e31f8_table%20formatting,%20vomitting%20allowed.ps1
|
stej_507000_raw_b60391568c1ede87d3f6a1e4d2d41c1ab03e31f8_table%20formatting,%20vomitting%20allowed.ps1
|
if ( $psc -eq $null ) { $psc = $pscmdlet } ; if (-not $PSBoundParameters.psc) {$PSBoundParameters.add("psc",$psc)}
if ( $image.count -gt 1 ) { [Void]$PSBoundParameters.Remove("Image") ; $image | ForEach-object {Save-Image -Image $_ @PSBoundParameters } ; return}
if ($filename -is [scriptblock]) {$fname = Invoke-Expression $(".{$filename}") }
else {$fname = $filename }
if (test-path $fname) {if ($noclobber) {write-warning "$fName exists and WILL NOT be overwritten"; if ($passthru) {$image} ; Return }
elseIF ($pscmdlet.shouldProcess($FName,"Delete file")) {Remove-Item -Path $fname -Force -Confirm:$false }
else {Return}
}
if ((Test-Path -Path $Fname -IsValid) -and ($pscmdlet.shouldProcess($FName,"Write image"))) { $image.SaveFile($FName) }
if ($passthru) {$image}
|
PowerShellCorpus/GithubGist/pkirch_bc290caca7aa5e065ac0_raw_2bbc40b68e5bf17eba64780a9031300e9204dff6_MVA05-BlobSnapshot.ps1
|
pkirch_bc290caca7aa5e065ac0_raw_2bbc40b68e5bf17eba64780a9031300e9204dff6_MVA05-BlobSnapshot.ps1
|
# step 1: get file
$blobFile = Get-AzureStorageBlob -Container source | Where-Object -Property Name -eq "version.txt"
# step 2: create snapshot
$cloudBlob = $blobFile.ICloudBlob
$cloudBlob.CreateSnapshot()
# step 3: get snapshots
$snapshot = Get-AzureStorageBlob -Container source | Where-Object -Property SnapshotTime
# step 4: download snapshot
$snapshot[0] | Get-AzureStorageBlobContent
|
PowerShellCorpus/GithubGist/ssilva_e3c5f9eee2f26549adc2_raw_f93b452718ad76906ae2eec261ec92b8eb3c16ff_DisableEnableNetworkAdapter.ps1
|
ssilva_e3c5f9eee2f26549adc2_raw_f93b452718ad76906ae2eec261ec92b8eb3c16ff_DisableEnableNetworkAdapter.ps1
|
# Get the network adapter object
$adapter = Get-WmiObject -Class Win32_NetworkAdapter |
Where-Object {$_.Name -eq "TP-LINK Wireless USB Adapter"}
# Disable it
Write-Host -nonew "Disabling $($adapter.Name)... ";
$result = $adapter.Disable()
if ($result.ReturnValue -eq -0) {
Write-Host "Success.";
} else {
Write-Host "Failed.";
}
# Wait 2 seconds
Start-Sleep -s 2
# Enable it
Write-Host -nonew "Enabling $($adapter.Name)... ";
$result = $adapter.Enable()
if ($result.ReturnValue -eq -0) {
Write-Host "Success.";
} else {
Write-Host "Failed.";
}
|
PowerShellCorpus/GithubGist/mitchelldavis_33570d3d31df70a76f9d_raw_bf61bb2bd4729f7f6545c7de095918e0ad1e016c_get-hash.ps1
|
mitchelldavis_33570d3d31df70a76f9d_raw_bf61bb2bd4729f7f6545c7de095918e0ad1e016c_get-hash.ps1
|
param(
[string] $file = $(throw 'a filename is required'),
[string] $algorithm = 'sha256'
)
$fileStream = [system.io.file]::openread((resolve-path $file))
$hasher = [System.Security.Cryptography.HashAlgorithm]::create($algorithm)
$hash = $hasher.ComputeHash($fileStream)
$fileStream.close()
$fileStream.dispose()
[system.bitconverter]::tostring($hash).Replace("-","").ToLower()
|
PowerShellCorpus/GithubGist/pkirch_5fa217a4b56d0cd215cf_raw_1d9a1f3122e3576a65d7fab55ebeaedac3c06fec_RelatedAzureVM.ps1
|
pkirch_5fa217a4b56d0cd215cf_raw_1d9a1f3122e3576a65d7fab55ebeaedac3c06fec_RelatedAzureVM.ps1
|
Get-Command -Module Azure -Noun AzureVM
<# Output
CommandType Name ModuleName
----------- ---- ----------
Cmdlet Export-AzureVM Azure
Cmdlet Get-AzureVM Azure
Cmdlet Import-AzureVM Azure
Cmdlet New-AzureVM Azure
Cmdlet Remove-AzureVM Azure
Cmdlet Restart-AzureVM Azure
Cmdlet Start-AzureVM Azure
Cmdlet Stop-AzureVM Azure
Cmdlet Update-AzureVM Azure
#>
|
PowerShellCorpus/GithubGist/acauamontiel_f801746c75b62b201faa_raw_6ffea5fdd129d50706a6800c88238d980fa5eaaa_replace.ps1
|
acauamontiel_f801746c75b62b201faa_raw_6ffea5fdd129d50706a6800c88238d980fa5eaaa_replace.ps1
|
$file = '.\fileName.lst' # Caminho relativo do arquivo
$oldName = 'Old Name' # Nome a ser alterado
$newName = Read-Host 'Novo nome'
(gc $file).replace($oldName, $newName) | sc $file
|
PowerShellCorpus/GithubGist/ullet_47c738d52406c1f20391_raw_94b80b6d6d6217c71b0096c3f3614b5bfb4a199f_DoNotExit.ps1
|
ullet_47c738d52406c1f20391_raw_94b80b6d6d6217c71b0096c3f3614b5bfb4a199f_DoNotExit.ps1
|
# From Stack Overflow answer by Roman Kuzmin (http://stackoverflow.com/users/323582/roman-kuzmin)
# to question @ http://stackoverflow.com/questions/9362722/stop-powershell-from-exiting
param($Work)
# restart PowerShell with -noexit, the same script, and 1
if (!$Work) {
powershell -noexit -file $MyInvocation.MyCommand.Path 1
return
}
# now the script does something
# this script just outputs this:
'I am not exiting'
|
PowerShellCorpus/GithubGist/nolim1t_660449_raw_20c92fbf3a2c770a515c62a74bb2b6d99d713521_Tweet.ps1
|
nolim1t_660449_raw_20c92fbf3a2c770a515c62a74bb2b6d99d713521_Tweet.ps1
|
# This is a powershell script which uses
# TwitProxy (https://twitproxy.heroku.com/) for updating twitter.
# Twittering using Windows Powershel
# Usage: .\Tweet.ps1 <the tweet>
[System.Reflection.Assembly]::LoadWithPartialName("System.Web") | out-null
$text = [System.Web.HttpUtility]::UrlEncode($args);
# Use your token here!
# Go to https://twitproxy.heroku.com/ and get one
$the_token = "";
$the_secret = "";
# Yes this needs to be filled in (TwitProxy is still a Beta)
$some_random_location = "&lat=0.000000&long=0.000000";
$url = "https://twitproxy.heroku.com/update?token=" + $the_token + "&secret=" + $the_secret + "&msg=" + $text + $some_random_location;
$r = [System.Net.WebRequest]::Create($url)
$resp = $r.GetResponse()
$reqstream = $resp.GetResponseStream()
$sr = new-object System.IO.StreamReader $reqstream
$result = $sr.ReadToEnd()
write-host $result
|
PowerShellCorpus/GithubGist/johnallers_4548e4316deff13da00b_raw_373486fa70c13923c9d7f1d107b761359b7520f5_Use-Impersonation.ps1
|
johnallers_4548e4316deff13da00b_raw_373486fa70c13923c9d7f1d107b761359b7520f5_Use-Impersonation.ps1
|
param(
[String] $domain,
[String] $username,
[String] $password,
[ScriptBlock] $scriptBlock
)
<#
.SYNOPSIS
Impersonates a user and executes a script block as that user. This is an interactive script
and a window will open in order to securely capture credentials.
.EXAMPLE
Use-Impersonation.ps1 mydomain.com testuser testpassword {Get-ChildItem 'C:\' | Foreach { Write-Host $_.Name }}
This writes the contents of 'C:\' impersonating the user that is entered.
#>
$logonUserSignature =
@'
[DllImport( "advapi32.dll", SetLastError=true )]
public static extern bool LogonUser( String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken );
'@
$AdvApi32 = Add-Type -MemberDefinition $logonUserSignature -Name "AdvApi32" -Namespace "PsInvoke.NativeMethods" -PassThru
$closeHandleSignature =
@'
[DllImport( "kernel32.dll", CharSet = CharSet.Auto )]
public static extern bool CloseHandle( IntPtr handle );
'@
$Kernel32 = Add-Type -MemberDefinition $closeHandleSignature -Name "Kernel32" -Namespace "PsInvoke.NativeMethods" -PassThru
try
{
$Logon32ProviderDefault = 0
$Logon32LogonInteractive = 2
$tokenHandle = [IntPtr]::Zero
$success = $false
try
{
$success = $AdvApi32::LogonUser($userName, $domain, $password, $Logon32LogonInteractive, $Logon32ProviderDefault, [Ref] $tokenHandle)
}
finally
{
}
if (!$success )
{
$retVal = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
Write-Host "LogonUser was unsuccessful. Error code: $retVal"
return
}
Write-Host "LogonUser was successful."
Write-Host "Value of Windows NT token: $tokenHandle"
$identityName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host "Current Identity: $identityName"
$newIdentity = New-Object System.Security.Principal.WindowsIdentity( $tokenHandle )
$context = $newIdentity.Impersonate()
$identityName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Host "Impersonating: $identityName"
Write-Host "Executing custom script"
& $scriptBlock
}
catch [System.Exception]
{
Write-Host $_.Exception.ToString()
}
finally
{
if ( $context -ne $null )
{
$context.Undo()
}
if ( $tokenHandle -ne [System.IntPtr]::Zero )
{
$Kernel32::CloseHandle( $tokenHandle )
}
}
|
PowerShellCorpus/GithubGist/crancker_5493489_raw_c3307609b0ca83d4675b1a7986b846ccf5e542af_deltemp.ps1
|
crancker_5493489_raw_c3307609b0ca83d4675b1a7986b846ccf5e542af_deltemp.ps1
|
Function delete{
Get-Childitem $Env:temp | Remove-Item -Recurse -Force
write-host "All temp files have been successfuly deleted."
}
$select = Read-Host "Do you want to delete all TEMP files? (yes, no)"
$temp = Get-Childitem $Env:temp
$temp
if ($select -eq "yes"){
delete
}
elseif ($select -eq "no"){
write-host "Canceled."
}
|
PowerShellCorpus/GithubGist/nkrumm_7031035_raw_b67d590adf0eb54b59d882424c4484b82b85ce5d_gistfile1.ps1
|
nkrumm_7031035_raw_b67d590adf0eb54b59d882424c4484b82b85ce5d_gistfile1.ps1
|
# set this to your head node hostname (run hostname)
HEAD_NODE_NAME=master
if [ `hostname` = $HEAD_NODE_NAME ]; then
NODES=`qconf -sel | grep -v $HEAD_NODE_NAME`
for NODE in $NODES; do
SCRIPT_PATH=`readlink -f $0`
qsub -l h=$NODE $SCRIPT_PATH
done
else
# YOUR COMMANDS YOU WANT TO EXECUTE HERE
fi
|
PowerShellCorpus/GithubGist/dfinke_4011813_raw_427c8da6f2c5e57855d974390ea9db694fde2939_gistfile1.ps1
|
dfinke_4011813_raw_427c8da6f2c5e57855d974390ea9db694fde2939_gistfile1.ps1
|
# Which do you think takes less time to multiply the #'s 1 to 55?
function Test-Timings {
param(
$iterations=5,
$type,
$sb
)
1..$iterations | ForEach {
$TotalMilliseconds = (Measure-Command {& $sb} ).TotalMilliseconds/1000
[pscustomobject]@{
Type = $type
TotalMilliseconds = "{0:N7}" -f $TotalMilliseconds
}
}
}
$(
Test-Timings 5 "IEX Join" { iex (1..55 -join "*") }
Test-Timings 5 "ForEach Pipeline" { 1..55|% {$s=1} {$s*=$_} {$s} }
)
|
PowerShellCorpus/GithubGist/codecontemplator_4638774_raw_6199b18686c142c0a0dc229e2f3850f5784b83fa_hronparser.ps1
|
codecontemplator_4638774_raw_6199b18686c142c0a0dc229e2f3850f5784b83fa_hronparser.ps1
|
function Parse-String([ref]$lines, $indent)
{
$sb = New-Object System.Text.StringBuilder
while($lines.Value[0] -match "(?<indent>^\t*)(?<value>.*)" -and $matches.indent.Length -eq $indent)
{
$lines.Value = $lines.Value[1..($lines.Value.Length)]
$sb.AppendLine($matches.value) | Out-Null
}
return $sb.ToString()
}
function AddOrExtend-Member($object, $member, $value)
{
if ($object | Get-Member $member)
{
if ($object -is [array])
{
$object.$member += $value
}
else
{
$object.$member = $object.$member, $value
}
}
else
{
$object | Add-Member NoteProperty $member $value
}
}
function Parse-Members([ref]$lines, $object, $indent)
{
while
(
($lines.Value.Count -gt 0) -and
($lines.Value[0] -match "(?<indent>^\t*)(?<controlchar>@|=)(?<membername>.*)") -and
($indent -eq $matches.indent.Length)
)
{
$lines.Value = $lines.Value[1..($lines.Value.Length)]
$value = $null
switch($matches.controlchar)
{
"@"
{
$value = New-Object PSObject
Parse-Members $lines $value ($indent+1)
}
"="
{
$value = Parse-String $lines ($indent+1)
}
}
AddOrExtend-Member $object $matches.membername $value
}
}
function ConvertFrom-HRON($text_and_comments)
{
$lines = $text_and_comments | ? { !$_.StartsWith("#") } | ? { ![string]::IsNullOrEmpty($_.Trim()) }
$result = New-Object psobject
Parse-Members ([ref]$lines) $result 0
return $result
}
#$text = Get-Content .\sample.hron
#ConvertFrom-HRON $text
|
PowerShellCorpus/GithubGist/kujotx_5447088_raw_c1601652ccea7dd94048722a32bfa1e2ff18efe9_gistfile1.ps1
|
kujotx_5447088_raw_c1601652ccea7dd94048722a32bfa1e2ff18efe9_gistfile1.ps1
|
# from : http://blog.uwe.elflein.eu/?p=42
$check = Test-Path -PathType Container xyz
if($check -eq $false){
New-Item 'xyz' -type Directory
}
|
PowerShellCorpus/GithubGist/Touichirou_a1ca4c647012c6fc5901_raw_02a877ad9e21630f9a7f5b8d2acfcf081098b393_create-windows-user.ps1
|
Touichirou_a1ca4c647012c6fc5901_raw_02a877ad9e21630f9a7f5b8d2acfcf081098b393_create-windows-user.ps1
|
& net.exe user vagrant vagrant /add
& net.exe user vagrant
|
PowerShellCorpus/GithubGist/gowland_3043141_raw_cf901573204b4291f1e112d2db408b3529ef0567_FileFTP.ps1
|
gowland_3043141_raw_cf901573204b4291f1e112d2db408b3529ef0567_FileFTP.ps1
|
#Upload the given file via FTP to the given server with the given credentials
function FTPFile
{
Param(
#Ensure $Filename exists and is not a folder
[ValidateScript({Test-Path $_ -PathType 'Leaf'})]
[string]
$FilePath
,
[ValidateNotNullOrEmpty()]
[string]
$FTPUser
,
[ValidateNotNullOrEmpty()]
[string]
$FTPPassword
,
[ValidateNotNullOrEmpty()]
[string]
$FTPServerPath
)
#Create the URI
$Filename = Split-Path $FilePath -leaf
$FTPUrl = "ftp://$FTPUser`:$FTPPassword`@$FTPServerPath$Filename"
$WebClient = New-Object System.Net.WebClient
$URI = New-Object System.Uri($FTPUrl)
#Attempt to upload the file
Notify "Uploading $FilePath"
try
{
$ErrorActionPreference = "Stop"; #Make all errors terminating
$WebClient.UploadFile($URI, $FilePath)
Notify "Upload for $Filename was successful."
Start-Sleep -Seconds 5
}
catch
{
Warn "Error. Could not upload file $Filename!"
Start-Sleep -Seconds 5
Throw
}
finally
{
$ErrorActionPreference = "Continue"; #Reset the error action pref to default
}
}
|
PowerShellCorpus/GithubGist/tkmtmkt_5786513_raw_701b1a84b8cb39868fc3c9e39193ef5c800492e4_gistfile1.ps1
|
tkmtmkt_5786513_raw_701b1a84b8cb39868fc3c9e39193ef5c800492e4_gistfile1.ps1
|
cd ~/apps/coherence/lib
mvn install:install-file `
-D groupId=com.oracle.coherence `
-D artifactId=coherence `
-D version=3.7.1.7 `
-D file=coherence.jar `
-D packaging=jar `
-D generatePom=true
|
PowerShellCorpus/GithubGist/mrcaron_282014_raw_abd171a840cce0bd2c3d57c0d9908b539dc81056_Powershell_Prompt.ps1
|
mrcaron_282014_raw_abd171a840cce0bd2c3d57c0d9908b539dc81056_Powershell_Prompt.ps1
|
# Powershell Prompt
$global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
function prompt
{
$un = [Regex]::Match($CurrentUser.Name,"SOLIDWORKS\\+(.*)").Groups[1].Value
$hn = [Net.DNS]::GetHostName()
$host.ui.rawui.WindowTitle = $un + "@" + $hn #+ " Line: " + $host.UI.RawUI.CursorPosition.Y
Write-Host($un + "@" + $hn + " ") -foregroundcolor Green -nonewline; Write-Host ($(get-location)) -foregroundcolor Yellow
Write-Host(">") -nonewline -foregroundcolor Green
return " "
}
|
PowerShellCorpus/GithubGist/gravejester_f464ef9eaab17d30ff3b_raw_bc0d5b00374df796be5fcd57439442733ac9aff9_Get-WebFile.ps1
|
gravejester_f464ef9eaab17d30ff3b_raw_bc0d5b00374df796be5fcd57439442733ac9aff9_Get-WebFile.ps1
|
function Get-WebFile {
<#
.SYNOPSIS
Download a file from the internet.
.DESCRIPTION
Download a file from the internet.
.PARAMETER Url
URL of file being downloaded
.PARAMETER TargetPath
Target path where the downloaded file will be saved. Defaults to the current folder.
.PARAMETER Timeout
Request timeout in milliseconds. Default is 100000.
.EXAMPLE
Get-WebFile http://some.server.com/file_to_download.zip
Description
-----------
Download file_to_download.zip to the current folder
.NOTES
Name: Get-WebFile
Author: Øyvind Kallstad
Date: 26.02.2014
Version: 1.0
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$Url,
[Parameter(Position = 1)]
[ValidateScript({Test-Path $_ -PathType Container})]
[string]$TargetPath = (Get-Location).Path,
[Parameter()]
[int]$Timeout
)
try{
$target = Join-Path -Path $TargetPath -ChildPath (Split-Path -Leaf $url)
# Create a web request object.
$request = [System.Net.WebRequest]::Create($url)
# Configure timeout if specified. Otherwise default value will be used.
if($Timeout){
$request.Timeout = $Timeout
Write-Verbose "Request timeout set to $Timeout milliseconds"
}
# Get a response from the server
$response = $request.GetResponse()
if(-not($response.Server)){
$server = ($response.ResponseUri.ToString()).Split("/")[2]
}
else{
$server = $response.Server
}
# Check that the response is ok before continuing.
if($response.StatusCode -ne 'OK'){
Write-Warning "A problem occured. The server responded with the following code: $($response.StatusCode)"
break
}
else{
Write-Verbose "Got a response back from $server"
}
# Get a response stream from the server
$responseStream = $response.GetResponseStream()
# Check that we are able to read the stream before continuing
if(-not($responseStream.CanRead)){
Write-Warning 'Unable to read from server'
break
}
# Set up a target stream. This will also create the destination file.
$targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $target, Create
Write-Verbose "Successfully created $target"
# Set up a small buffer and start to read.
$buffer = New-Object byte[] 10KB
$read = $responseStream.Read($buffer,0,$buffer.length)
# Take a note of the total downloaded bytes.
$downloadedBytes = $read
# As long as there are bytes that have have been read...
while($read -gt 0){
# ... write data to the destination file
$targetStream.Write($buffer,0,$read)
# New read
$read = $responseStream.Read($buffer,0,$buffer.length)
# Recalculate the total downloaded bytes
$downloadedBytes = $downloadedBytes + $read
# Calculate percent complete
$percentComplete = (($downloadedBytes/$response.ContentLength))*100
# Write progress bar
Write-Progress -Activity "Downloading '$(Split-Path -Leaf $url)' from $($server)" -Status "Downloaded $($downloadedBytes) of $($response.ContentLength) bytes." -PercentComplete $percentComplete
}
Write-Progress -Activity "Finished downloading file '$(Split-Path -Leaf $url)'" -Completed
Write-Verbose 'Finished downloading file'
# Let's clean up
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Close()
$responseStream.Dispose()
Write-Verbose 'Finished closing connections'
}
catch{
# Catching any exceptions
Write-Warning $_.Exception.Message
}
}
|
PowerShellCorpus/GithubGist/VertigoRay_6091753_raw_c1bec64a3dfc875ca2356eda586f2926748fa890_gistfile1.ps1
|
VertigoRay_6091753_raw_c1bec64a3dfc875ca2356eda586f2926748fa890_gistfile1.ps1
|
[string] $Path = 'OU=foo,OU=test,DC=domain,DC=com'
try {
if (!([adsi]::Exists("LDAP://$Path"))) {
Throw('Supplied Path does not exist.')
} else {
Write-Debug "Path Exists: $Path"
}
} catch {
# If invalid format, error is thrown.
Throw("Supplied Path is invalid.`n$_")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.