PowerShellの `profile.ps1`ファイルには何が含まれていますか?[閉まっている]


85

プロファイルにはどのような重要なもの(関数、エイリアス、起動スクリプト)がありますか?

回答:


23

いくつかのことを数えたり合計したりするために、いくつかの基本的な集計が必要になることがよくあります。これらの関数を定義して頻繁に使用します。パイプラインの最後で非常にうまく機能します。

#
# 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 }
}

プロンプトで色を使用して時間とパスを取得できるようにするには:

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 "> "
}

次の関数はブログから盗まれ、私の好みに合うように変更されていますが、色付きのlsはとてもいいです:

# 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 }

そして、本当に反復的なフィルタリングタスクを回避するためのいくつかのショートカット:

# 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))
        { $_ }
}

2
このコメントは何の価値もありませんが、あなたのユーザー名は素晴らしいと言いたいだけです。
chrisf 2013年

スコープの問題はありませんか?PowerShellスクリプトを含む、スクリプト内で定義されたすべての関数(またはエイリアス)は、スクリプトの実行にスコープされ、呼び出し元のシェルで蒸発しませんか?これは私のマシンの場合です。私は何をすべきか?
ウリ

10

PowerShellからVisualStudioビルド環境をセットアップするために、ここからVsVars32を取得しました。いつも使っています。

################################################## #############################
#環境変数をバッチで公開し、このPSセッションで設定します
################################################## #############################
関数Get-Batchfile($ file) 
{{
    $ theCmd = "` "$ file`"&set " 
    cmd / c $ theCmd | Foreach-オブジェクト{
        $ thePath、$ theValue = $_。split( '=')
        Set-Item -path env:$ thePath -value $ theValue
    }
}


################################################## #############################
#このPSセッションで使用するVS変数を設定します
################################################## #############################
関数VsVars32($ version = "9.0")
{{
    $ theKey = "HKLM:SOFTWARE \ Microsoft \ VisualStudio \" + $ version
    $ 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" + $ version + "Windows Powershell"
}

1
leeholmes.com/blog/…を使用してvcvarsを呼び出します。
ジェイバズジ2008

上記のスクリプトは、64ビットWindowsでは機能しません(WOW64レジストリリダイレクトのため)。
Govert 2012年

その場合は、32ビットのWOW64cmd.exeシェルで実行するだけです。それは不可能でしたか?
djangofan 2012

10

これは、スクリプトPSDriveを反復処理し、「lib-」で始まるすべてのものをドットソースします。

### ---------------------------------------------------------------------------
### Load function / filter definition library
### ---------------------------------------------------------------------------

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

9

start-transcript。これにより、セッション全体がテキストファイルに書き出されます。環境でPowershellを使用する方法について新入社員をトレーニングするのに最適です。


2
+1ヒントをありがとう...これで、継続的インテグレーションビルドをコンソールとログファイルの両方に記録する際の問題が修正されました。「WindowsPowershellポケットリファレンス」または「WindowsPowerShellinAction」のいずれにも十分に文書化されていなかったのは残念です。それはあなたが練習から学ぶことだと思います。
Peter Walke

ヘッドアップとして、Start-TranscriptコマンドはすべてのPowerShellホストで使用できるわけではないため、ホストに依存しないプロファイル(profile.ps1)に配置すると、一部のコンテキストでエラーが発生する可能性があります。(Microsoft.PowerShellISE_profile.ps1)のようなホスト固有のプロファイルで役立つ場合があります。
Burt_Harris 2014

9

私のプロンプトには次のものが含まれています。

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

これにより、スクロールバックしたときに見やすいコマンド間の仕切りが得られます。また、入力している行に水平方向のスペースを使用せずに、現在のディレクトリが表示されます。

例えば:

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


7

これは私のそれほど微妙ではないプロファイルです


    #==============================================================================
# Jared Parsons PowerShell Profile (jaredp@rantpack.org) 
#==============================================================================

#==============================================================================
# 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


profile.ps1をコピーする場所は?マシンを再起動するか、winrmサービスを再起動する必要がありますか?
Kiquenet 2013

@ Kiquenet、PowerShellセッションを再起動するだけです。
クリストファーダグラス

+1、非常にうまくセグメント化されています。ありがとう。
サブンチュ2013年

7

私はいくつかの関数をロックします。私はモジュールの作成者なので、通常はコンソールをロードし、何がどこにあるのかを必死に知る必要があります。

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

ダイハードオタク:

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> "
}

PowerShellで機能する必須のものはすべてここにあります...

# 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)
}

私はまだ管理者なので、必要です...

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
}

ログインしたユーザー以外の誰かとしてエクスプローラーを開始したい場合があります...

# 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
}

これは面白いからです。

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
}

Win+Lが遠すぎるので、私も1つ持っています...

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
}

いくつかのフィルター?私はそう思う...

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

また、まだ投稿できないものもいくつかあります。これらは完了していないためですが、基本的には、暗号化されたファイルとして書き出すことなく、セッション間で資格情報を保持する方法です。


ここで素晴らしいことです。ファイルに書き込まずにセッション間で資格情報を永続化するソリューションに興味があります。
jkdba 2016

@jkdbaは、私がそれらをファイルに書き込んだことがわかりました。キャッチは、私のセッションだけがファイルを復号化でき、私のコンピューター上でのみです。そのショットを与えて、それがあなたのために働くかどうか私に知らせてください。
クリストファーダグラス

1
うーん興味深いことに、私は基本的に同じアイデアで遊んだことがありますが、代わりに、keepassデータベースを使用し、データベースへの接続を開いて資格情報を安全な文字列として取得し、資格情報オブジェクトを作成するようにプロファイルを構成しました。私は彼らのSDK用の豪華なkeepassコードラッパーに取り組んでいます。gitでPSKeePassという名前のリポジトリを見つけることができます(今のところdevブランチをチェックしてください)。ネットワークログインとキーファイルを使用するように簡単に拡張できます。あなたがしていることと同様の効果を達成するための追加の、しかし簡単なセキュリティ。
jkdba 2016

@jkdbaそれは素晴らしいです!私は間違いなくあなたのコードをチェックして、できれば貢献するつもりです。私はkeepassの大ファンですが、PSでSDKを使用する機会はありませんでした。ありがとう!
クリストファーダグラス

6
# ----------------------------------------------------------
# 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;
}

2
代わりにOpen-IE、の組み込みiiエイリアスを使用しInvoke-Itemます。
ジェイバズジ2010年

1
ii「google.com」が機能しません。ジェイをどのように使っていますか?
ケビンベリッジ2011年

試してみてくださいstart http://google.com
orad 2015

5

ディスク使用量を簡単に確認できるように、この関数を追加します。

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")

    }
}

5

ところで。

これは最近のリリースまたは今後のリリースに取って代わられたと思いますが。

############################################################################## 
## 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
       }
    }
}

はい、Get-Helpはトピックコンテンツを検索するようになりました。
キース・ヒル

5

私はすべてを少しだけ保持します。ほとんどの場合、私のプロファイルはすべての環境をセットアップします(.NET / VSおよびJava開発環境をセットアップするためのスクリプトの呼び出しを含む)。

またprompt()、独自のスタイルで関数を再定義し(実際の動作を参照)、他のスクリプトやコマンドのエイリアスをいくつか設定します。何を$HOME指すかを変更します。

これが私の完全なプロファイルスクリプトです。


4
Set-PSDebug -Strict 

あなたはあなたが愚かなタイプミスを探したことがある私に利益をもたらすでしょう。$ varsometextの代わりに$ varsometextを出力します


私は定期的にタイプOエラーを起こします。約12回変更したコードがそれぞれの方法で機能することを理解するのは非常に謙虚ですが、それでもプロパティ名を正しく綴ることさえできません。
クリストファーダグラス

3
############################################################################## 
# 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()
}

--xmlを使用したsvnコマンドからの出力など、xmlの操作に役立ちます。


3

これにより、scripts:driveが作成され、パスに追加されます。自分でフォルダを作成する必要があることに注意してください。次に戻る必要があるときは、Windowsのドライブ文字と同じように、「scripts:」と入力してEnterキーを押します。

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

3

これにより、インストールしたスナップインがPowerShellセッションに追加されます。このようなことをしたい理由は、メンテナンスが簡単で、複数のシステム間でプロファイルを同期する場合にうまく機能するためです。スナップインがインストールされていない場合、エラーメッセージは表示されません。

-------------------------------------------------- -------------------------

サードパーティのスナップインを追加する

-------------------------------------------------- -------------------------

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

3

すべての関数とエイリアスを別々のスクリプトファイルに入れてから、プロファイルにドットソースします。

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


2

入力したコマンドの履歴全体を表示する関数(Get-Historyとそのエイリアスhは、デフォルトで最後の32個のコマンドのみを表示します):

function ha {
    Get-History -count $MaximumHistoryCount
}

2

私のPowerShellプロファイルは次の場所で確認できます。 http://github.com/jamesottaway/windowspowershellます

Gitを使用してリポジトリをDocumentsフォルダー(または$ PROFILE変数の「WindowsPowerShell」の上にあるフォルダー)に複製すると、私のすべての利点が得られます。

メインprofile.ps1セットの名前を持つサブフォルダAddonsAなどPSDrive、その後、とは負荷に、そのフォルダの下にすべての.ps1というファイルを検索します。

go簡単にアクセスできる速記の場所の辞書を保存するコマンドがとても気に入っています。たとえば、go vsp私をに連れて行きますC:\Visual Studio 2008\Projectsます。

私も上書きなどのSet-Location両方を実行するコマンドレットをSet-Locationし、Get-ChildItemです。

私の他のお気に入りは行うことができることですmkdirしているをSet-Location xyz実行した後New-Item xyz -Type Directory


2
Function funcOpenPowerShellProfile
{
    Notepad $PROFILE
}

Set-Alias fop funcOpenPowerShellProfile

もちろん、「fop」を17世紀の英語のバカと関連付けない限り、それはプロンプトよりもはるかに簡単に入力できると言うのは、賢明に怠惰な人だけですfopNotepad $PROFILE


必要に応じて、さらに一歩進めて、いくらか便利にすることができます。

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

Set-Alias fop funcOpenPowerShellProfile

サバイバリスト-パラノイアを満足させるために:

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

2

他の多くのものの中で:

function w {
    explorer .
}

現在のディレクトリにエクスプローラウィンドウを開きます

function startover {
    iisreset /restart
    iisreset /stop

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

    iisreset /start
}

一時的なasp.netファイル内のすべてを削除します(バグのあるアンマネージコードに依存するマネージコードでの作業に役立ちます)

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

メモ帳++で$ xを編集します



2

シェルの再起動はドラッグになる可能性があるため、JeffreySnoverのStart-NewScope

私はdiruseオプションに慣れることがなかったので

function Get-FolderSizes {
  [cmdletBinding()]
  param(
    [parameter(mandatory=$true)]$Path,
    [parameter(mandatory=$false)]$SizeMB,
    [parameter(mandatory=$false)]$ExcludeFolder
  ) #close param
  $pathCheck = test-path $path
  if (!$pathcheck) {"Invalid path. Wants gci's -path parameter."; break}
  $fso = New-Object -ComObject scripting.filesystemobject
  $parents = Get-ChildItem $path -Force | where { $_.PSisContainer -and $_.name -ne $ExcludeFolder }
  $folders = Foreach ($folder in $parents) {
    $getFolder = $fso.getFolder( $folder.fullname.tostring() )
    if (!$getFolder.Size) { #for "special folders" like appdata
      $lengthSum = gci $folder.FullName -recurse -force -ea silentlyContinue | `
        measure -sum length -ea SilentlyContinue | select -expand sum
      $sizeMBs = "{0:N0}" -f ($lengthSum /1mb)      
    } #close if size property is null
      else { $sizeMBs = "{0:N0}" -f ($getFolder.size /1mb) }
      #else {$sizeMBs = [int]($getFolder.size /1mb) }
    New-Object -TypeName psobject -Property @{
       name = $getFolder.path;
      sizeMB = $sizeMBs
    } #close new obj property
  } #close foreach folder
  #here's the output
  $folders | sort @{E={[decimal]$_.sizeMB}} -Descending | ? {[decimal]$_.sizeMB -gt $SizeMB} | ft -auto
  #calculate the total including contents
  $sum = $folders | select -expand sizeMB | measure -sum | select -expand sum
  $sum += ( gci -file $path | 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 get-drivespace {
  param( [parameter(mandatory=$true)]$Computer)
  if ($computer -like "*.com") {$cred = get-credential; $qry = Get-WmiObject Win32_LogicalDisk -filter drivetype=3 -comp $computer -credential $cred }
  else { $qry = Get-WmiObject Win32_LogicalDisk -filter drivetype=3 -comp $computer }  
  $qry | select `
    @{n="drive"; e={$_.deviceID}}, `
    @{n="GB Free"; e={"{0:N2}" -f ($_.freespace / 1gb)}}, `
    @{n="TotalGB"; e={"{0:N0}" -f ($_.size / 1gb)}}, `
    @{n="FreePct"; e={"{0:P0}" -f ($_.FreeSpace / $_.size)}}, `
    @{n="name"; e={$_.volumeName}} |
  format-table -autosize
} #close drivespace

ものを指すために:

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

貧乏人のgrep?大きなtxtファイルを検索するため。

function Search-TextFile {
  param( 
    [parameter(mandatory=$true)]$File,
    [parameter(mandatory=$true)]$SearchText
  ) #close param
  if ( !(test-path $File) ) {"File not found:" + $File; break}
  $fullPath = resolve-path $file | select -expand path
  $lines = [system.io.file]::ReadLines($fullPath)
  foreach ($line in $lines) { if ($line -match $SearchText) {$line} }
} #end function Search-TextFile

リモートコンピュータにインストールされているプログラムを一覧表示します。

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

メタに行き、福音を広め、

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

1
$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 }

1

プロファイルを空のままにします。代わりに、機能とエイリアスをセッションにロードするためにナビゲートできるスクリプトのフォルダーがあります。フォルダーはモジュール式で、関数とアセンブリのライブラリがあります。アドホックな作業のために、エイリアスと関数をロードするスクリプトがあります。イベントログを変更したい場合は、scripts \ eventlogsフォルダーに移動して実行します

PS > . .\DotSourceThisToLoadSomeHandyEventLogMonitoringFunctions.ps1

スクリプトを他の人と共有したり、マシン間で移動したりする必要があるため、これを行います。スクリプトとアセンブリのフォルダーをコピーして、任意のユーザーの任意のマシンで機能させることができるのが好きです。

しかし、あなたはトリックの楽しいコレクションが必要です。これが私の「プロファイル」の多くが依存しているスクリプトです。これにより、自己署名SSLを使用するWebサービスへの呼び出しが可能になり、開発中のWebサービスをアドホックに探索できます。はい、PowerShellスクリプトでC#を自由に組み合わせることができます。

# 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()
}

0

素晴らしい質問です。私はいくつかの異なるPowerShellホストを扱っているため、他のメッセージのコンテキストを明確にするために、いくつかのプロファイルのそれぞれに少しログインします。でprofile.ps1、私は現在それしか持っていませんが、コンテキストに基づいて変更することがあります。

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

私のお気に入りのホストはISEです、でMicrosoft.PowerShellIse_profile.ps1、私は持っています:

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

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.