Wat staat er in uw PowerShell `profile.ps1`-bestand?

Welke essentiële dingen (functies, aliassen, opstartscripts) heb je in je profiel?


Antwoord 1, autoriteit 100%

Ik merk dat ik vaak wat basisaggregaten nodig heb om sommige dingen te tellen/optellen. Ik heb deze functies gedefinieerd en gebruik ze vaak, ze werken heel goed aan het einde van een pijplijn:

#
# useful agregate
#
function count
{
    BEGIN { $x = 0 }
    PROCESS { $x += 1 }
    END { $x }
}
function product
{
    BEGIN { $x = 1 }
    PROCESS { $x *= $_ }
    END { $x }
}
function sum
{
    BEGIN { $x = 0 }
    PROCESS { $x += $_ }
    END { $x }
}
function average
{
    BEGIN { $max = 0; $curr = 0 }
    PROCESS { $max += $_; $curr += 1 }
    END { $max / $curr }
}

Om tijd en pad met kleuren in mijn prompt te krijgen:

function Get-Time { return $(get-date | foreach { $_.ToLongTimeString() } ) }
function prompt
{
    # Write the time 
    write-host "[" -noNewLine
    write-host $(Get-Time) -foreground yellow -noNewLine
    write-host "] " -noNewLine
    # Write the path
    write-host $($(Get-Location).Path.replace($home,"~").replace("\","/")) -foreground green -noNewLine
    write-host $(if ($nestedpromptlevel -ge 1) { '>>' }) -noNewLine
    return "> "
}

De volgende functies zijn gestolen van een blog en aangepast aan mijn smaak, maar ls met kleuren is erg mooi :

# LS.MSH 
# Colorized LS function replacement 
# /\/\o\/\/ 2006 
# http://mow001.blogspot.com 
function LL
{
    param ($dir = ".", $all = $false) 
    $origFg = $host.ui.rawui.foregroundColor 
    if ( $all ) { $toList = ls -force $dir }
    else { $toList = ls $dir }
    foreach ($Item in $toList)  
    { 
        Switch ($Item.Extension)  
        { 
            ".Exe" {$host.ui.rawui.foregroundColor = "Yellow"} 
            ".cmd" {$host.ui.rawui.foregroundColor = "Red"} 
            ".msh" {$host.ui.rawui.foregroundColor = "Red"} 
            ".vbs" {$host.ui.rawui.foregroundColor = "Red"} 
            Default {$host.ui.rawui.foregroundColor = $origFg} 
        } 
        if ($item.Mode.StartsWith("d")) {$host.ui.rawui.foregroundColor = "Green"}
        $item 
    }  
    $host.ui.rawui.foregroundColor = $origFg 
}
function lla
{
    param ( $dir=".")
    ll $dir $true
}
function la { ls -force }

En enkele sneltoetsen om echt repetitieve filtertaken te vermijden:

# behave like a grep command
# but work on objects, used
# to be still be allowed to use grep
filter match( $reg )
{
    if ($_.tostring() -match $reg)
        { $_ }
}
# behave like a grep -v command
# but work on objects
filter exclude( $reg )
{
    if (-not ($_.tostring() -match $reg))
        { $_ }
}
# behave like match but use only -like
filter like( $glob )
{
    if ($_.toString() -like $glob)
        { $_ }
}
filter unlike( $glob )
{
    if (-not ($_.tostring() -like $glob))
        { $_ }
}

Antwoord 2, autoriteit 44%

Dit herhaalt een PSDrive-script en dot-sourcet alles wat begint met “lib-“.

### ---------------------------------------------------------------------------
### Load function / filter definition library
### ---------------------------------------------------------------------------
    Get-ChildItem scripts:\lib-*.ps1 | % { 
      . $_
      write-host "Loading library file:`t$($_.name)"
    }

Antwoord 3, autoriteit 41%

Om mijn Visual Studio-bouwomgeving vanuit PowerShell in te stellen, heb ik de VsVars32 van hier. en gebruik het de hele tijd.

############################################### ################################
# Toont de omgevingsvariabelen in een batch en stelt ze in deze PS-sessie in 
###################################################################### #############################
functie Get-Batchfile($file)
{
  $theCmd = "`"$file`" & set"
  cmd /c $theCmd | Foreach-Object {
    $thePath, $theValue = $_.split('=')
    Set-Item -path env:$thePath -value $theValue
  }
}
###################################################################### #############################
# Stelt de VS-variabelen in die deze PS-sessie moet gebruiken
###################################################################### #############################
functie VsVars32($versie = "9.0")
{
  $theKey = "HKLM:SOFTWARE\Microsoft\VisualStudio\" + $versie
  $theVsKey = get-ItemProperty $theKey
  $theVsInstallPath = [System.IO.Path]::GetDirectoryName ($theVsKey.InstallDir)
  $theVsToolsDir = [System.IO.Path]::GetDirectoryName ($theVsInstallPath)
  $theVsToolsDir = [System.IO.Path]::Combine($theVsToolsDir, "Tools")
  $theBatchFile = [System.IO.Path]::Combine($theVsToolsDir, "vsvars32.bat")
  Get-Batchfile $theBatchFile
  [System.Console]::Title = "Visual Studio" + $versie + "Windows Powershell"
}

Antwoord 4, autoriteit 37%

start-transcript. Hiermee wordt je hele sessie weggeschreven naar een tekstbestand. Geweldig voor het trainen van nieuwe medewerkers in het gebruik van Powershell in de omgeving.


Antwoord 5, autoriteit 37%

Mijn prompt bevat:

$width = ($Host.UI.RawUI.WindowSize.Width - 2 - $(Get-Location).ToString().Length)
$hr = New-Object System.String @('-',$width)
Write-Host -ForegroundColor Red $(Get-Location) $hr

Dat geeft me een scheiding tussen commando’s die gemakkelijk te zien is als ik terug scrol. Het laat me ook de huidige map zien zonder horizontale spatie te gebruiken op de regel waarop ik typ.

Bijvoorbeeld:

C:\Users\Jay ---------------------------------- -------------------------------------------------- ----------------------
[1] PS>


Antwoord 6, autoriteit 30%

# ----------------------------------------------------------
# msdn search for win32 APIs.
# ----------------------------------------------------------
function Search-MSDNWin32
{
    $url = 'http://search.msdn.microsoft.com/?query=';
    $url += $args[0];
    for ($i = 1; $i -lt $args.count; $i++) {
        $url += '+';
        $url += $args[$i];
    }
    $url += '&locale=en-us&refinement=86&ac=3';
    Open-IE($url);
}
# ----------------------------------------------------------
# Open Internet Explorer given the url.
# ----------------------------------------------------------
function Open-IE ($url)
{    
    $ie = new-object -comobject internetexplorer.application;
    $ie.Navigate($url);
    $ie.Visible = $true;
}

Antwoord 7, autoriteit 30%

Ik gebruik een paar functies en aangezien ik een module-auteur ben, laad ik meestal een console en moet ik dringend weten wat waar is.

write-host "Your modules are..." -ForegroundColor Red
Get-module -li

Die hard nerding:

function prompt
{
    $host.UI.RawUI.WindowTitle = "ShellPower"
    # Need to still show the working directory.
    #Write-Host "You landed in $PWD"
    # Nerd up, yo.
    $Str = "Root@The Matrix"
    "$str> "
}

De verplichte alles wat ik kan PowerShell I zal-functies gaan hier…

# Explorer command
function Explore
{
    param
        (
            [Parameter(
                Position = 0,
                ValueFromPipeline = $true,
                Mandatory = $true,
                HelpMessage = "This is the path to explore..."
            )]
            [ValidateNotNullOrEmpty()]
            [string]
            # First parameter is the path you're going to explore.
            $Target
        )
    $exploration = New-Object -ComObject shell.application
    $exploration.Explore($Target)
}

Ik ben NOG STEEDS een beheerder, dus ik moet…

Function RDP
{
    param
        (
            [Parameter(
                    Position = 0,
                    ValueFromPipeline = $true,
                    Mandatory = $true,
                    HelpMessage = "Server Friendly name"
            )]
            [ValidateNotNullOrEmpty()]
            [string]
            $server
        )
    cmdkey /generic:TERMSRV/$server /user:$UserName /pass:($Password.GetNetworkCredential().Password)
    mstsc /v:$Server /f /admin
    Wait-Event -Timeout 5
    cmdkey /Delete:TERMSRV/$server
}

Soms wil ik verkenner starten als iemand anders dan de ingelogde gebruiker…

# Restarts explorer as the user in $UserName
function New-Explorer
{
    # CLI prompt for password
    taskkill /f /IM Explorer.exe
    runas /noprofile /netonly /user:$UserName explorer
}

Dit is gewoon omdat het grappig is.

Function Lock-RemoteWorkstation
{
    param(
        $Computername,
        $Credential
    )
    if(!(get-module taskscheduler))
    {
        Import-Module TaskScheduler
    }
    New-task -ComputerName $Computername -credential:$Credential |
        Add-TaskTrigger -In (New-TimeSpan -Seconds 30) |
        Add-TaskAction -Script `
        {
            $signature = @"
            [DllImport("user32.dll", SetLastError = true)]
            public static extern bool LockWorkStation();
            "@
                $LockWorkStation = Add-Type -memberDefinition $signature -name "Win32LockWorkStation" -namespace Win32Functions -passthru
                $LockWorkStation::LockWorkStation() | Out-Null
        } | Register-ScheduledTask TestTask -ComputerName $Computername -credential:$Credential
}

Ik heb er ook een voor mij, aangezien Win+ Lte ver weg is…

Function llm # Lock Local machine
{
    $signature = @"
    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool LockWorkStation();
    "@
        $LockWorkStation = Add-Type -memberDefinition $signature -name "Win32LockWorkStation" -namespace Win32Functions -passthru
        $LockWorkStation::LockWorkStation() | Out-Null
}

Een paar filters? Ik denk het wel…

filter FileSizeBelow($size){if($_.length -le $size){ $_ }}
 filter FileSizeAbove($size){if($_.Length -ge $size){$_}}

Ik heb er ook een paar die ik nog niet kan plaatsen, omdat ze nog niet klaar zijn, maar ze zijn in feite een manier om referenties tussen sessies te behouden zonder ze als een versleuteld bestand weg te schrijven.


Antwoord 8, autoriteit 26%

Hier is mijn niet zo subtiele profiel


    #==============================================================================
# Jared Parsons PowerShell Profile ([email protected]) 
#==============================================================================
#==============================================================================
# Common Variables Start
#==============================================================================
$global:Jsh = new-object psobject 
$Jsh | add-member NoteProperty "ScriptPath" $(split-path -parent $MyInvocation.MyCommand.Definition) 
$Jsh | add-member NoteProperty "ConfigPath" $(split-path -parent $Jsh.ScriptPath)
$Jsh | add-member NoteProperty "UtilsRawPath" $(join-path $Jsh.ConfigPath "Utils")
$Jsh | add-member NoteProperty "UtilsPath" $(join-path $Jsh.UtilsRawPath $env:PROCESSOR_ARCHITECTURE)
$Jsh | add-member NoteProperty "GoMap" @{}
$Jsh | add-member NoteProperty "ScriptMap" @{}
#==============================================================================
#==============================================================================
# Functions 
#==============================================================================
# Load snapin's if they are available
function Jsh.Load-Snapin([string]$name) {
    $list = @( get-pssnapin | ? { $_.Name -eq $name })
    if ( $list.Length -gt 0 ) {
        return; 
    }
    $snapin = get-pssnapin -registered | ? { $_.Name -eq $name }
    if ( $snapin -ne $null ) {
        add-pssnapin $name
    }
}
# Update the configuration from the source code server
function Jsh.Update-WinConfig([bool]$force=$false) {
    # First see if we've updated in the last day 
    $target = join-path $env:temp "Jsh.Update.txt"
    $update = $false
    if ( test-path $target ) {
        $last = [datetime] (gc $target)
        if ( ([DateTime]::Now - $last).Days -gt 1) {
            $update = $true
        }
    } else {
        $update = $true;
    }
    if ( $update -or $force ) {
        write-host "Checking for winconfig updates"
        pushd $Jsh.ConfigPath
        $output = @(& svn update)
        if ( $output.Length -gt 1 ) {
            write-host "WinConfig updated.  Re-running configuration"
            cd $Jsh.ScriptPath
            & .\ConfigureAll.ps1
            . .\Profile.ps1
        }
        sc $target $([DateTime]::Now)
        popd
    }
}
function Jsh.Push-Path([string] $location) { 
    go $location $true 
}
function Jsh.Go-Path([string] $location, [bool]$push = $false) {
    if ( $location -eq "" ) {
        write-output $Jsh.GoMap
    } elseif ( $Jsh.GoMap.ContainsKey($location) ) {
        if ( $push ) {
            push-location $Jsh.GoMap[$location]
        } else {
            set-location $Jsh.GoMap[$location]
        }
    } elseif ( test-path $location ) {
        if ( $push ) {
            push-location $location
        } else {
            set-location $location
        }
    } else {
        write-output "$loctaion is not a valid go location"
        write-output "Current defined locations"
        write-output $Jsh.GoMap
    }
}
function Jsh.Run-Script([string] $name) {
    if ( $Jsh.ScriptMap.ContainsKey($name) ) {
        . $Jsh.ScriptMap[$name]
    } else {
        write-output "$name is not a valid script location"
        write-output $Jsh.ScriptMap
    }
}
# Set the prompt
function prompt() {
    if ( Test-Admin ) { 
        write-host -NoNewLine -f red "Admin "
    }
    write-host -NoNewLine -ForegroundColor Green $(get-location)
    foreach ( $entry in (get-location -stack)) {
        write-host -NoNewLine -ForegroundColor Red '+';
    }
    write-host -NoNewLine -ForegroundColor Green '>'
    ' '
}
#==============================================================================
#==============================================================================
# Alias 
#==============================================================================
set-alias gcid      Get-ChildItemDirectory
set-alias wget      Get-WebItem
set-alias ss        select-string
set-alias ssr       Select-StringRecurse 
set-alias go        Jsh.Go-Path
set-alias gop       Jsh.Push-Path
set-alias script    Jsh.Run-Script
set-alias ia        Invoke-Admin
set-alias ica       Invoke-CommandAdmin
set-alias isa       Invoke-ScriptAdmin
#==============================================================================
pushd $Jsh.ScriptPath
# Setup the go locations
$Jsh.GoMap["ps"]        = $Jsh.ScriptPath
$Jsh.GoMap["config"]    = $Jsh.ConfigPath
$Jsh.GoMap["~"]         = "~"
# Setup load locations
$Jsh.ScriptMap["profile"]       = join-path $Jsh.ScriptPath "Profile.ps1"
$Jsh.ScriptMap["common"]        = $(join-path $Jsh.ScriptPath "LibraryCommon.ps1")
$Jsh.ScriptMap["svn"]           = $(join-path $Jsh.ScriptPath "LibrarySubversion.ps1")
$Jsh.ScriptMap["subversion"]    = $(join-path $Jsh.ScriptPath "LibrarySubversion.ps1")
$Jsh.ScriptMap["favorites"]     = $(join-path $Jsh.ScriptPath "LibraryFavorites.ps1")
$Jsh.ScriptMap["registry"]      = $(join-path $Jsh.ScriptPath "LibraryRegistry.ps1")
$Jsh.ScriptMap["reg"]           = $(join-path $Jsh.ScriptPath "LibraryRegistry.ps1")
$Jsh.ScriptMap["token"]         = $(join-path $Jsh.ScriptPath "LibraryTokenize.ps1")
$Jsh.ScriptMap["unit"]          = $(join-path $Jsh.ScriptPath "LibraryUnitTest.ps1")
$Jsh.ScriptMap["tfs"]           = $(join-path $Jsh.ScriptPath "LibraryTfs.ps1")
$Jsh.ScriptMap["tab"]           = $(join-path $Jsh.ScriptPath "TabExpansion.ps1")
# Load the common functions
. script common
. script tab
$global:libCommonCertPath = (join-path $Jsh.ConfigPath "Data\Certs\jaredp_code.pfx")
# Load the snapin's we want
Jsh.Load-Snapin "pscx"
Jsh.Load-Snapin "JshCmdlet" 
# Setup the Console look and feel
$host.UI.RawUI.ForegroundColor = "Yellow"
if ( Test-Admin ) {
    $title = "Administrator Shell - {0}" -f $host.UI.RawUI.WindowTitle
    $host.UI.RawUI.WindowTitle = $title;
}
# Call the computer specific profile
$compProfile = join-path "Computers" ($env:ComputerName + "_Profile.ps1")
if ( -not (test-path $compProfile)) { ni $compProfile -type File | out-null }
write-host "Computer profile: $compProfile"
. ".\$compProfile"
$Jsh.ScriptMap["cprofile"] = resolve-path ($compProfile)
# If the computer name is the same as the domain then we are not 
# joined to active directory
if ($env:UserDomain -ne $env:ComputerName ) {
    # Call the domain specific profile data
    write-host "Domain $env:UserDomain"
    $domainProfile = join-path $env:UserDomain "Profile.ps1"
    if ( -not (test-path $domainProfile))  { ni $domainProfile -type File | out-null }
    . ".\$domainProfile"
}
# Run the get-fortune command if JshCmdlet was loaded
if ( get-command "get-fortune" -ea SilentlyContinue ) {
    get-fortune -timeout 1000
}
# Finished with the profile, go back to the original directory
popd
# Look for updates
Jsh.Update-WinConfig
# Because this profile is run in the same context, we need to remove any 
# variables manually that we don't want exposed outside this script


Antwoord 9, autoriteit 19%

ik voeg deze functie toe zodat ik het schijfgebruik gemakkelijk kan zien:

function df {
    $colItems = Get-wmiObject -class "Win32_LogicalDisk" -namespace "root\CIMV2" `
    -computername localhost
    foreach ($objItem in $colItems) {
        write $objItem.DeviceID $objItem.Description $objItem.FileSystem `
            ($objItem.Size / 1GB).ToString("f3") ($objItem.FreeSpace / 1GB).ToString("f3")
    }
}

Antwoord 10, autoriteit 19%

behoorlijk.

Hoewel ik denk dat dit is vervangen door een recente of aanstaande release.

############################################################################## 
## Search the PowerShell help documentation for a given keyword or regular 
## expression.
## 
## Example:
##    Get-HelpMatch hashtable
##    Get-HelpMatch "(datetime|ticks)"
############################################################################## 
function apropos {
    param($searchWord = $(throw "Please specify content to search for"))
    $helpNames = $(get-help *)
    foreach($helpTopic in $helpNames)
    {
       $content = get-help -Full $helpTopic.Name | out-string
       if($content -match $searchWord)
       { 
          $helpTopic | select Name,Synopsis
       }
    }
}

Antwoord 11, autoriteit 19%

Ik bewaar een beetje van alles. Meestal stelt mijn profiel alle omgevingen in (inclusief aanroepende scripts om mijn .NET/VS- en Java-ontwikkelomgeving in te stellen).

Ik herdefinieer ook de functie prompt()met mijn eigen stijl (zie het in actie), stel verschillende aliassen in voor andere scripts en commando’s. en verander waar $HOMEnaar verwijst.

Hier is mijn volledige profielscript.


Antwoord 12, autoriteit 15%

Set-PSDebug -Strict 

Je profiteert ervan als je ooit naar een stomme typfout hebt gezocht, bijv. $varsometext uitvoeren in plaats daarvan $var sometext


Antwoord 13, autoriteit 11%

############################################################################## 
# Get an XPath Navigator object based on the input string containing xml
function get-xpn ($text) { 
    $rdr = [System.IO.StringReader] $text
    $trdr = [system.io.textreader]$rdr
    $xpdoc = [System.XML.XPath.XPathDocument] $trdr
    $xpdoc.CreateNavigator()
}

Nuttig voor het werken met xml, zoals uitvoer van svn-opdrachten met –xml.


Antwoord 14, autoriteit 11%

Hiermee wordt een scripts: drive gemaakt en toegevoegd aan uw pad. Let op, u dient de map zelf aan te maken. De volgende keer dat u er weer op terug moet komen, typt u gewoon “scripts:” en drukt u op enter, net als elke stationsletter in Windows.

$env:path += ";$profiledir\scripts"
New-PSDrive -Name Scripts -PSProvider FileSystem -Root $profiledir\scripts

Antwoord 15, autoriteit 11%

Hiermee worden de door u geïnstalleerde snapins toegevoegd aan uw powershell-sessie. De reden waarom u zoiets wilt doen, is dat het gemakkelijk te onderhouden is en goed werkt als u uw profiel op meerdere systemen synchroniseert. Als er geen snapin is geïnstalleerd, krijg je geen foutmelding te zien.

———————————————– —————————-

Snapins van derden toevoegen

———————————————– —————————-

$snapins = @(
    "Quest.ActiveRoles.ADManagement",
    "PowerGadgets",
    "VMware.VimAutomation.Core",
    "NetCmdlets"
)
$snapins | ForEach-Object { 
  if ( Get-PSSnapin -Registered $_ -ErrorAction SilentlyContinue ) {
    Add-PSSnapin $_
  }
}

Antwoord 16, autoriteit 11%

Ik plaats al mijn functies en aliassen in aparte scriptbestanden en plaats ze vervolgens in mijn profiel:

. c:\scripts\posh\jdh-functions.ps1


Antwoord 17, autoriteit 7%

De functie om de volledige geschiedenis van getypte commando’s te bekijken (Get-History, en zijn alias h tonen standaard slechts 32 laatste commando’s):

function ha {
    Get-History -count $MaximumHistoryCount
}

Antwoord 18, autoriteit 7%

Je kunt mijn PowerShell-profiel zien op http://github.com/jamesottaway/windowspowershell

Als je Git gebruikt om mijn repo naar je Documenten-map te klonen (of welke map dan ook boven ‘WindowsPowerShell’ in je $PROFILE-variabele), krijg je al mijn goedheid.

De hoofdmap profile.ps1stelt de submap met de naam Addonsin als een PSDriveen vindt vervolgens alle .ps1-bestanden onder die map om te laden.

Ik vind het go-commando, dat een woordenboek met steno-locaties opslaat om gemakkelijk te bezoeken, erg goed. go vspbrengt me bijvoorbeeld naar C:\Visual Studio 2008\Projects.

Ik vind het ook leuk om de cmdlet Set-Locationte negeren om zowel Set-Locationals Get-ChildItemuit te voeren.

Mijn andere favoriet is het kunnen doen van een mkdirdie Set-Location xyzdoet na het uitvoeren van New-Item xyz -Type Directory.


Antwoord 19, autoriteit 7%

onder vele andere dingen:

function w {
    explorer .
}

opent een verkennervenster in de huidige map

function startover {
    iisreset /restart
    iisreset /stop

    rm "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\*.*" -recurse -force -Verbose

    iisreset /start
}

verwijdert alles in mijn tijdelijke asp.net-bestanden (handig voor het werken aan beheerde code die afhankelijk is van onbeheerde code met fouten)

function edit($x) {
    . 'C:\Program Files (x86)\Notepad++\notepad++.exe' $x
}

bewerkt $x in kladblok++


Antwoord 20, autoriteit 7%

Ik bewaar de mijne eigenlijk op github.


Antwoord 21, autoriteit 7%

Function funcOpenPowerShellProfile
{
    Notepad $PROFILE
}
Set-Alias fop funcOpenPowerShellProfile

Alleen een sagaciously-luie individu zou u vertellen dat fopzo veel gemakkelijker is om te typen dan Notepad $PROFILEBij de prompt, tenzij u natuurlijk “FOP” associeert met een 17e eeuw Engels ninny .


Als u wilde, kunt u het een stap verder brengen en het enigszins nuttig maken:

Function funcOpenPowerShellProfile
{
    $fileProfileBackup = $PROFILE + '.bak'
    cp $PROFILE $fileProfileBackup
    PowerShell_ISE $PROFILE # Replace with Desired IDE/ISE for Syntax Highlighting
}
Set-Alias fop funcOpenPowerShellProfile

Voor het voldoen aan Survivalist-Paranoia:

Function funcOpenPowerShellProfile
{
    $fileProfilePathParts = @($PROFILE.Split('\'))
    $fileProfileName = $fileProfilePathParts[-1]
    $fileProfilePathPartNum = 0
    $fileProfileHostPath = $fileProfilePathParts[$fileProfilePathPartNum] + '\'
    $fileProfileHostPathPartsCount = $fileProfilePathParts.Count - 2
        # Arrays start at 0, but the Count starts at 1; if both started at 0 or 1, 
        # then a -1 would be fine, but the realized discrepancy is 2
    Do
    {
        $fileProfilePathPartNum++
        $fileProfileHostPath = $fileProfileHostPath + `
            $fileProfilePathParts[$fileProfilePathPartNum] + '\'
    }
    While
    (
        $fileProfilePathPartNum -LT $fileProfileHostPathPartsCount
    )
    $fileProfileBackupTime = [string](date -format u) -replace ":", ""
    $fileProfileBackup = $fileProfileHostPath + `
        $fileProfileBackupTime + ' - ' + $fileProfileName + '.bak'
    cp $PROFILE $fileProfileBackup
    cd $fileProfileHostPath
    $fileProfileBackupNamePattern = $fileProfileName + '.bak'
    $fileProfileBackups = @(ls | Where {$_.Name -Match $fileProfileBackupNamePattern} | `
        Sort Name)
    $fileProfileBackupsCount = $fileProfileBackups.Count
    $fileProfileBackupThreshold = 5 # Change as Desired
    If
    (
        $fileProfileBackupsCount -GT $fileProfileBackupThreshold
    )
    {
        $fileProfileBackupsDeleteNum = $fileProfileBackupsCount - `
            $fileProfileBackupThreshold
        $fileProfileBackupsIndexNum = 0
        Do
        {
            rm $fileProfileBackups[$fileProfileBackupsIndexNum]
            $fileProfileBackupsIndexNum++;
            $fileProfileBackupsDeleteNum--
        }
        While
        (
            $fileProfileBackupsDeleteNum -NE 0
        )
    }
    PowerShell_ISE $PROFILE
        # Replace 'PowerShell_ISE' with Desired IDE (IDE's path may be needed in 
        # '$Env:PATH' for this to work; if you can start it from the "Run" window, 
        # you should be fine)
}
Set-Alias fop funcOpenPowerShellProfile

Antwoord 22, Autoriteit 7%

Jeffrey Snover’s start-newscope Omdat het opnieuw lanceren van de shell een sleep is.

Ik heb nooit op je gemak gesteld met de Dirrus opties, dus :

function Get-FolderSizes { # poor man's du
  [cmdletBinding()]
  param(
    [parameter(mandatory=$true)]$Path,
    [parameter(mandatory=$false)]$SizeMB,
    [parameter(mandatory=$false)]$ExcludeFolders,
    [parameter(mandatory=$false)][switch]$AsObject
  ) #close param
  # http://blogs.technet.com/b/heyscriptingguy/archive/2013/01/05/weekend-scripter-sorting-folders-by-size.aspx
  # uses Christoph Schneegans' Find-Files https://schneegans.de/windows/find-files/ because "gci -rec" follows junctions in "special" folders
  $pathCheck = test-path $path
  if (!$pathcheck) { Write-Error "Invalid path. Wants gci's -path parameter."; return }
  if (!(Get-Command Find-Files)) { Write-Error "Required function Find-Files not found"; return }
  $fso = New-Object -ComObject scripting.filesystemobject
  $parents = Get-ChildItem $path -Force | where { $_.PSisContainer -and $ExcludeFolders -notContains $_.name -and !$_.LinkType }
  $folders = Foreach ($folder in $parents)
  {
    $getFolder = $fso.getFolder( $folder.fullname.tostring() )
    if (!$getFolder.Size)
    { 
      #for "special folders" like appdata
      # maybe "-Attributes !ReparsePoint" works in v6? https://stackoverflow.com/a/59952913/
      # what about https://superuser.com/a/650476/ ?
      # abandoned because it follows junctions, distorting results # $length = gci $folder.FullName -Recurse -Force -EA SilentlyContinue | Measure -Property Length -Sum
      $length = Find-Files $folder.FullName -EA SilentlyContinue | Measure -Property Length -Sum -EA SilentlyContinue
      $sizeMBs = "{0:N0}" -f ($length.Sum /1mb)
    } #close if size property is null
    else { $sizeMBs = "{0:N0}" -f ($getFolder.size /1mb) }
    New-Object -TypeName psobject -Property @{
      Name = $getFolder.Path
      SizeMB = $sizeMBs
    } #close new obj property
  } #close foreach folder
  #here's the output
  $foldersObj = $folders | Sort @{E={[decimal]$_.SizeMB}} -Descending | ? {[Decimal]$_.SizeMB -gt $SizeMB}
  if (!$AsObject) { $foldersObj | Format-Table -AutoSize } else { $foldersObj }
  #calculate the total including contents
  $sum = $folders | Select -Expand SizeMB | Measure -Sum | Select -Expand Sum
  $sum += ( gci $path | where {!$_.psIsContainer} | Measure -Property Length -Sum | Select -Expand Sum ) / 1mb
  $sumString = "{0:n2}" -f ($sum /1kb)
  $sumString + " GB total" 
} #end function
Set-Alias gfs Get-FolderSizes
function Find-Files
{
    <# by Christoph Schneegans https://schneegans.de/windows/find-files/ - used in Get-FolderSizes aka gfs
    .SYNOPSIS
        Lists the contents of a directory. Unlike Get-ChildItem, this function does not recurse into symbolic links or junctions in order to avoid infinite loops.
    #>
    param (
        [Parameter( Mandatory=$false )]
        [string]
        # Specifies the path to the directory whose contents are to be listed. By default, the current working directory is used.
        $LiteralPath = (Get-Location),
        [Parameter( Mandatory=$false )]
        # Specifies a filter that is applied to each file or directory. Wildcards ? and * are supported.
        $Filter,
        [Parameter( Mandatory=$false )]
        [boolean]
        # Specifies if file objects should be returned. By default, all file system objects are returned.
        $File = $true,
        [Parameter( Mandatory=$false )]
        [boolean]
        # Specifies if directory objects should be returned. By default, all file system objects are returned.
        $Directory = $true,
        [Parameter( Mandatory=$false )]
        [boolean]
        # Specifies if reparse point objects should be returned. By default, all file system objects are returned.
        $ReparsePoint = $true,
        [Parameter( Mandatory=$false )]
        [boolean]
        # Specifies if the top directory should be returned. By default, all file system objects are returned.
        $Self = $true
    )
    function Enumerate( [System.IO.FileSystemInfo] $Item ) {
        $Item;
        if ( $Item.GetType() -eq [System.IO.DirectoryInfo] -and ! $Item.Attributes.HasFlag( [System.IO.FileAttributes]::ReparsePoint ) ) {
            foreach ($ChildItem in $Item.EnumerateFileSystemInfos() ) {
                Enumerate $ChildItem;
            }
        }
    }
    function FilterByName {
        process {
            if ( ( $Filter -eq $null ) -or ( $_.Name -ilike $Filter ) ) {
                $_;
            }
        }
    }
    function FilterByType {
        process {
            if ( $_.GetType() -eq [System.IO.FileInfo] ) {
                if ( $File ) { $_; }
            } elseif ( $_.Attributes.HasFlag( [System.IO.FileAttributes]::ReparsePoint ) ) {
                if ( $ReparsePoint ) { $_; }
            } else {
                if ( $Directory ) { $_; }
            }
        }
    }
    $Skip = if ($Self) { 0 } else { 1 };
    Enumerate ( Get-Item -LiteralPath $LiteralPath -Force ) | Select-Object -Skip $Skip | FilterByName | FilterByType;
} # end function find-files

Het meest waardevolle stuk hierboven is Christoph Schneegans’ Find-Fileshttps: //schneegans.de/windows/find-files

Om naar dingen te wijzen:

function New-URLfile {
  param( [parameter(mandatory=$true)]$Target, [parameter(mandatory=$true)]$Link )
  if ($target -match "^\." -or $link -match "^\.") {"Full paths plz."; break}
  $content = @()
  $header = '[InternetShortcut]'
  $content += $header
  $content += "URL=" + $target
  $content | out-file $link  
  ii $link
} #end function
function New-LNKFile {
  param( [parameter(mandatory=$true)]$Target, [parameter(mandatory=$true)]$Link )
  if ($target -match "^\." -or $link -match "^\.") {"Full paths plz."; break}
  $WshShell = New-Object -comObject WScript.Shell
  $Shortcut = $WshShell.CreateShortcut($link)
  $Shortcut.TargetPath = $target
  $shortCut.save()
} #end function new-lnkfile

Arme man’s grep? Voor het zoeken naar grote txt-bestanden.

function Search-TextFile {
  param( 
    [parameter(mandatory=$true)]$File,
    [parameter(mandatory=$true)]$SearchText
  ) #close param
  if ( !(Test-path $File) )
  { 
    Write-Error "File not found: $file" 
    return
  }
  $fullPath = Resolve-Path $file | select -Expand ProviderPath
  $lines = [System.IO.File]::ReadLines($fullPath)
  foreach ($line in $lines) { if ($line -match $SearchText) {$line} }
} #end function Search-TextFile
Set-Alias stf Search-TextFile

Een lijst van programma’s die op een externe computer zijn geïnstalleerd.

function Get-InstalledProgram { [cmdletBinding()] #http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/13/use-powershell-to-quickly-find-installed-software.aspx
      param( [parameter(mandatory=$true)]$Comp,[parameter(mandatory=$false)]$Name )
      $keys = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall','SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
      TRY { $RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Comp) }
      CATCH {
        $rrSvc = gwmi win32_service -comp $comp -Filter {name='RemoteRegistry'}
        if (!$rrSvc) {"Unable to connect. Make sure that this computer is on the network, has remote administration enabled, `nand that both computers are running the remote registry service."; break}
        #Enable and start RemoteRegistry service
        if ($rrSvc.State -ne 'Running') {
          if ($rrSvc.StartMode -eq 'Disabled') { $null = $rrSvc.ChangeStartMode('Manual'); $undoMe2 = $true }
          $null = $rrSvc.StartService() ; $undoMe = $true       
        } #close if rrsvc not running
          else {"Unable to connect. Make sure that this computer is on the network, has remote administration enabled, `nand that both computers are running the remote registry service."; break}
        $RegBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Comp)  
      } #close if failed to connect regbase
      $out = @()
      foreach ($key in $keys) {
         if ( $RegBase.OpenSubKey($Key) ) { #avoids errors on 32bit OS
          foreach ( $entry in $RegBase.OpenSubKey($Key).GetSubkeyNames() ) {
            $sub = $RegBase.OpenSubKey( ($key + '\' + $entry) )
            if ($sub) { $row = $null
              $row = [pscustomobject]@{
                Name = $RegBase.OpenSubKey( ($key + '\' + $entry) ).GetValue('DisplayName')
                InstallDate = $RegBase.OpenSubKey( ($key + '\' + $entry) ).GetValue('InstallDate')
                Version = $RegBase.OpenSubKey( ($key + '\' + $entry) ).GetValue('DisplayVersion')
              } #close row
              $out += $row
            } #close if sub
          } #close foreach entry
        } #close if key exists
      } #close foreach key
      $out | where {$_.name -and $_.name -match $Name}
      if ($undoMe) { $null = $rrSvc.StopService() }
      if ($undoMe2) { $null = $rrSvc.ChangeStartMode('Disabled') }
    } #end function

Meta gaan, het evangelie verspreiden, wat dan ook

function Copy-ProfilePS1 ($Comp,$User) {
  if (!$User) {$User = $env:USERNAME}
  $targ = "\\$comp\c$\users\$User\Documents\WindowsPowershell\"
  if (Test-Path $targ)
  {
    $cmd = "copy /-Y $profile $targ"
    cmd /c $cmd
  } else {"Path not found! $targ"}
} #end function CopyProfilePS1

Antwoord 23, autoriteit 4%

$MaximumHistoryCount=1024 
function hist {get-history -count 256 | %{$_.commandline}}
New-Alias which get-command
function guidConverter([byte[]] $gross){ $GUID = "{" + $gross[3].ToString("X2") + `
$gross[2].ToString("X2") + $gross[1].ToString("X2") + $gross[0].ToString("X2") + "-" + `
$gross[5].ToString("X2") + $gross[4].ToString("X2") + "-" + $gross[7].ToString("X2") + `
$gross[6].ToString("X2") + "-" + $gross[8].ToString("X2") + $gross[9].ToString("X2") + "-" +` 
$gross[10].ToString("X2") + $gross[11].ToString("X2") + $gross[12].ToString("X2") + `
$gross[13].ToString("X2") + $gross[14].ToString("X2") + $gross[15].ToString("X2") + "}" $GUID }

Antwoord 24, autoriteit 4%

Ik houd mijn profiel leeg. In plaats daarvan heb ik mappen met scripts die ik kan navigeren om functionaliteit en aliassen in de sessie te laden. Een map zal modulair zijn, met bibliotheken van functies en samenstellingen. Voor ad-hocwerk heb ik een script om aliassen en functies te laden. Als ik gebeurtenislogboeken wil verwijderen, navigeer ik naar een map scripts\eventlogs en voer ik deze uit

PS > . .\DotSourceThisToLoadSomeHandyEventLogMonitoringFunctions.ps1

Ik doe dit omdat ik scripts met anderen moet delen of ze van machine naar machine moet verplaatsen. Ik vind het leuk om een ​​map met scripts en assemblages te kunnen kopiëren en het gewoon op elke machine en voor elke gebruiker te laten werken.

Maar je wilt een leuke verzameling trucs. Hier is een script waarvan veel van mijn “profielen” afhankelijk zijn. Het staat oproepen toe naar webservices die zelfondertekende SSL gebruiken voor ad-hocverkenning van webservices in ontwikkeling. Ja, ik mix vrijelijk C# in mijn powershell-scripts.

# Using a target web service that requires SSL, but server is self-signed.  
# Without this, we'll fail unable to establish trust relationship. 
function Set-CertificateValidationCallback
{
    try
    {
       Add-Type @'
    using System;
    public static class CertificateAcceptor{
        public static void SetAccept()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = AcceptCertificate;
        }
        private static bool AcceptCertificate(Object sender,
                        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                        System.Security.Cryptography.X509Certificates.X509Chain chain,
                        System.Net.Security.SslPolicyErrors policyErrors)
            {
                Console.WriteLine("Accepting certificate and ignoring any SSL errors.");
                return true;
            }
    }
'@
    }
    catch {} # Already exists? Find a better way to check.
     [CertificateAcceptor]::SetAccept()
}

Antwoord 25

Goede vraag. Omdat ik te maken heb met verschillende PowerShell-hosts, log ik een beetje in op elk van de verschillende profielen, alleen om de context van andere berichten duidelijker te maken. In profile.ps1heb ik momenteel alleen dat, maar ik verander het soms op basis van context:

if ($PSVersionTable.PsVersion.Major -ge 3) {
    Write-Host "Executing $PSCommandPath"
}

Mijn favoriete host is de ISE, in Microsoft.PowerShellIse_profile.ps1, ik heb:

if ($PSVersionTable.PsVersion.Major -ge 3) {
    Write-Host "Executing $PSCommandPath"
}
if ( New-PSDrive -ErrorAction Ignore One FileSystem `
        (Get-ItemProperty hkcu:\Software\Microsoft\SkyDrive UserFolder).UserFolder) { 
    Write-Host -ForegroundColor Green "PSDrive One: mapped to local OneDrive/SkyDrive folder"
    }
Import-Module PSCX
$PSCX:TextEditor = (get-command Powershell_ISE).Path
$PSDefaultParameterValues = @{
    "Get-Help:ShowWindow" = $true
    "Help:ShowWindow" = $true
    "Out-Default:OutVariable" = "0"
}
#Script Browser Begin
#Version: 1.2.1
Add-Type -Path 'C:\Program Files (x86)\Microsoft Corporation\Microsoft Script Browser\System.Windows.Interactivity.dll'
Add-Type -Path 'C:\Program Files (x86)\Microsoft Corporation\Microsoft Script Browser\ScriptBrowser.dll'
Add-Type -Path 'C:\Program Files (x86)\Microsoft Corporation\Microsoft Script Browser\BestPractices.dll'
$scriptBrowser = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add('Script Browser', [ScriptExplorer.Views.MainView], $true)
$scriptAnalyzer = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add('Script Analyzer', [BestPractices.Views.BestPracticesView], $true)
$psISE.CurrentPowerShellTab.VisibleVerticalAddOnTools.SelectedAddOnTool = $scriptBrowser
#Script Browser End

Antwoord 26

Van alles wat nog niet is vermeld, Start-steroïden moet mijn favoriet zijn, behalve voor misschien start-transcript.

(http://www.powertheshell.com/isesteroids2-2/ )

Other episodes