Có gì trong tệp PowerShell `profile.ps1` của bạn? [đóng cửa]


85

Bạn có những thứ thiết yếu nào (chức năng, bí danh, tập lệnh khởi động) trong hồ sơ của mình?

Câu trả lời:


23

Tôi thường thấy mình cần một số agregate cơ bản để đếm / tổng một số thứ. Tôi đã xác định các hàm này và sử dụng chúng thường xuyên, chúng hoạt động rất hiệu quả ở cuối đường ống:

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

Để có thể nhận được thời gian và đường dẫn với màu sắc trong lời nhắc của tôi:

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

Các chức năng sau đây bị đánh cắp từ blog và được sửa đổi để phù hợp với sở thích của tôi, nhưng màu sắc rất đẹp:

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

Và một số phím tắt để tránh các tác vụ lọc thực sự lặp lại:

# 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
Nhận xét này không có giá trị gì, nhưng tôi chỉ muốn nói rằng tên người dùng của bạn thật tuyệt vời.
chrisf

Không có một vấn đề phạm vi? Không phải tất cả các chức năng (hoặc bí danh) được định nghĩa trong một tập lệnh, bao gồm cả tập lệnh PowerShell, đều thuộc phạm vi thực thi tập lệnh và biến mất trên trình bao gọi? Đây là trường hợp trên máy của tôi. Tôi nên làm gì?
Uri

10

Để thiết lập môi trường xây dựng Visual Studio của tôi từ PowerShell, tôi đã lấy VsVars32 từ đây . và sử dụng nó mọi lúc.

###################################################### ###############################
# Hiển thị các vars môi trường trong một loạt và đặt chúng trong phiên PS này
###################################################### ###############################
hàm Get-Batchfile ($ file) 
{
    $ theCmd = "` "$ file`" & set " 
    cmd / c $ theCmd | Foreach-Object {
        $ thePath, $ theValue = $ _. split ('=')
        Set-Item -path env: $ thePath -value $ theValue
    }
}


###################################################### ###############################
# Đặt các biến VS cho phiên PS này để sử dụng
###################################################### ###############################
hàm VsVars32 ($ version = "9.0")
{
    $ theKey = "HKLM: SOFTWARE \ Microsoft \ VisualStudio \" + $ phiên bản
    $ theVsKey = get-ItemProperty $ theKey
    $ theVsInstallPath = [System.IO.Path] :: GetDirectoryName ($ theVsKey.InstallDir)
    $ theVsToolsDir = [System.IO.Path] :: GetDirectoryName ($ theVsInstallPath)
    $ theVsToolsDir = [System.IO.Path] :: Kết hợp ($ theVsToolsDir, "Công cụ")
    $ theBatchFile = [System.IO.Path] :: Kết hợp ($ theVsToolsDir, "vsvars32.bat")
    Get-Batchfile $ theBatchFile
    [System.Console] :: Title = "Visual Studio" + $ phiên bản + "Windows Powershell"
}

1
Tôi sử dụng leeholmes.com/blog/… để gọi vcvars.
Jay Bazuzi

Tập lệnh trên không hoạt động trên Windows 64 bit (do chuyển hướng sổ đăng ký WOW64).
Govert

Trong trường hợp đó, chỉ cần chạy nó trong trình bao WOW64 cmd.exe 32-bit. Điều đó là không thể?
djangofan

10

Điều này lặp lại thông qua một PSDrive script và dot-source mọi thứ bắt đầu bằng "lib-".

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

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

9

bảng điểm bắt đầu . Điều này sẽ ghi toàn bộ phiên của bạn vào một tệp văn bản. Tuyệt vời để đào tạo nhân viên mới về cách sử dụng Powershell trong môi trường.


2
+1 Cảm ơn vì mẹo ... Điều đó vừa khắc phục sự cố của tôi với việc ghi nhật ký bản dựng Tích hợp liên tục vào bảng điều khiển và tệp nhật ký. Tôi thất vọng vì nó không được ghi lại đầy đủ trong "tài liệu tham khảo bỏ túi Windows Powershell" hoặc "Windows PowerShell in Action". Tôi đoán đó là điều bạn học được từ thực tế.
Peter Walke

Lưu ý, lệnh Start-Transcript không có sẵn trong tất cả các máy chủ PowerShell, vì vậy, việc đặt nó trong cấu hình độc lập với máy chủ (profile.ps1) có thể tạo ra lỗi trong một số ngữ cảnh. Nó có thể hữu ích trong các cấu hình dành riêng cho máy chủ như (Microsoft.PowerShellISE_profile.ps1).
Burt_Harris

9

Lời nhắc của tôi bao gồm:

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

Điều này cung cấp cho tôi một dải phân cách giữa các lệnh dễ thấy khi cuộn lại. Nó cũng hiển thị cho tôi thư mục hiện tại mà không sử dụng dấu cách ngang trên dòng mà tôi đang nhập.

Ví dụ:

C: \ Users \ Jay -------------------------------------------- -------------------------------------------------- ------------
[1] Tái bút>


7

Đây là hồ sơ không quá tinh tế của tôi


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


Tôi sao chép hồ sơ.ps1 ở đâu? Có yêu cầu khởi động lại máy o khởi động lại dịch vụ winrm không?
Kiquenet

@Kiquenet, chỉ cần khởi động lại phiên powershell của bạn.
Christopher Douglas

+1, được phân đoạn rất độc đáo. Cảm ơn.
Sabuncu

7

Tôi đá một vài chức năng và vì tôi là tác giả mô-đun, tôi thường tải một bảng điều khiển và rất cần biết những gì ở đâu.

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

Chết cứng:

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

Bất cứ điều gì bắt buộc tôi có thể PowerShell tôi sẽ thực hiện ở đây ...

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

Tôi VẪN là quản trị viên nên tôi cần ...

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
}

Đôi khi tôi muốn bắt đầu trình khám phá với tư cách là một người nào đó khác với người dùng đã đăng nhập ...

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

Đây chỉ là vì nó buồn cười.

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
}

Tôi cũng có một cái cho tôi, vì Win+ ở Lquá xa ...

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
}

Một vài bộ lọc? Tôi nghĩ vậy...

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

Tôi cũng có một vài điều tôi chưa thể đăng vì chúng chưa hoàn thành nhưng về cơ bản chúng là một cách để duy trì thông tin xác thực giữa các phiên mà không cần ghi chúng ra dưới dạng tệp được mã hóa.


Thật tuyệt ở đây, tôi sẽ quan tâm đến giải pháp của bạn để duy trì thông tin đăng nhập giữa các phiên mà không cần ghi chúng vào tệp.
jkdba

@jkdba hóa ra tôi đã ghi chúng ra một tệp, điều bắt buộc là chỉ phiên của tôi mới có thể giải mã tệp và chỉ trên máy tính của tôi. Hãy thử và cho tôi biết nếu nó phù hợp với bạn.
Christopher Douglas

1
Hmm Thật thú vị, tôi đã chơi với cùng một Ý tưởng về cơ bản, nhưng những gì tôi đã làm thay vào đó là sử dụng cơ sở dữ liệu keepass và sau đó định cấu hình hồ sơ của tôi để mở kết nối với cơ sở dữ liệu và truy xuất thông tin đăng nhập của tôi dưới dạng chuỗi an toàn và tạo đối tượng thông tin xác thực . Tôi đã làm việc trên một trình bao bọc mã keepass sang trọng cho sdk của họ, bạn có thể tìm thấy nó trên git với tên người dùng của tôi, repo được gọi là PSKeePass (kiểm tra chi nhánh nhà phát triển ngay bây giờ.) Nó có thể dễ dàng mở rộng để sử dụng đăng nhập mạng và keyfile cho bảo mật bổ sung nhưng dễ dàng để đạt được hiệu quả tương tự như những gì bạn đang làm.
jkdba

@jkdba thật TUYỆT VỜI! Tôi chắc chắn sẽ kiểm tra mã của bạn và đóng góp nếu tôi có thể. Tôi là một fan cuồng của keepass, nhưng chưa bao giờ có cơ hội sử dụng SDK của họ với PS. Cảm ơn!
Christopher Douglas

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
Thay vì Open-IEtôi sử dụng iibí danh tích hợp sẵn cho Invoke-Item.
Jay Bazuzi

1
ii " google.com " không hoạt động. Bạn đang sử dụng nó như thế nào Jay?
Kevin Berridge

Hãy thửstart http://google.com
orad

5

tôi thêm chức năng này để có thể dễ dàng xem việc sử dụng đĩa:

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

apropos.

Mặc dù tôi nghĩ rằng điều này đã được thay thế bởi một bản phát hành gần đây hoặc sắp tới.

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

Có, Get-Help bây giờ sẽ tìm kiếm nội dung chủ đề.
Keith Hill

5

Tôi giữ một chút của tất cả mọi thứ. Hầu hết, hồ sơ của tôi thiết lập tất cả môi trường (bao gồm cả việc gọi các tập lệnh để thiết lập môi trường phát triển .NET / VS và Java của tôi).

Tôi cũng xác định lại prompt()chức năng với phong cách của riêng mình ( xem nó trong thực tế ), thiết lập một số bí danh cho các tập lệnh và lệnh khác. và thay đổi $HOMEđiểm nào thành.

Đây là kịch bản hồ sơ hoàn chỉnh của tôi .


4
Set-PSDebug -Strict 

Bạn sẽ có lợi cho tôi mà bạn đã từng tìm kiếm một ví dụ Typo ngu ngốc. xuất ra $ varsometext thay vì $ var sometext


Tôi mắc lỗi type-o thường xuyên. Thật khiêm tốn khi nhận ra rằng mã bạn chỉ cần thay đổi khoảng 12 lần mỗi cách hoạt động, nhưng bạn vẫn không thể đánh vần đúng tên thuộc tính.
Christopher Douglas

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

Hữu ích khi làm việc với xml, chẳng hạn như đầu ra từ các lệnh svn với --xml.


3

Điều này tạo ra một script: drive và thêm nó vào đường dẫn của bạn. Lưu ý, bạn phải tự tạo thư mục. Lần tới khi bạn cần quay lại, chỉ cần nhập "scripts:" và nhấn enter, giống như bất kỳ ký tự ổ đĩa nào trong Windows.

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

3

Thao tác này sẽ thêm các snapin bạn đã cài đặt vào phiên powershell của mình. Lý do bạn có thể muốn làm điều gì đó như vậy là nó dễ bảo trì và hoạt động tốt nếu bạn đồng bộ hóa hồ sơ của mình trên nhiều hệ thống. Nếu một snapin chưa được cài đặt, bạn sẽ không thấy thông báo lỗi.

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

Thêm snapins của bên thứ ba

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

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

3

Tôi đặt tất cả các chức năng và bí danh của mình trong các tệp tập lệnh riêng biệt và sau đó chấm nguồn chúng trong hồ sơ của mình:

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


2

Chức năng xem toàn bộ lịch sử của lệnh đã nhập (Get-History và bí danh h của anh ta chỉ hiển thị mặc định 32 lệnh cuối cùng):

function ha {
    Get-History -count $MaximumHistoryCount
}

2

Bạn có thể xem hồ sơ PowerShell của tôi tại http://github.com/jamesottaway/windowspowershell

Nếu bạn sử dụng Git để sao chép repo của tôi vào thư mục Documents của bạn (hoặc bất kỳ thư mục nào nằm trên 'WindowsPowerShell' trong biến $ PROFILE của bạn), bạn sẽ nhận được tất cả lợi ích của tôi.

Chính profile.ps1đặt thư mục con với tên Addonslà a PSDrive, sau đó tìm tất cả các tệp .ps1 bên dưới thư mục đó để tải.

Tôi khá thích golệnh, nó lưu trữ từ điển các địa điểm tốc ký để truy cập dễ dàng. Ví dụ, go vspsẽ đưa tôi đến C:\Visual Studio 2008\Projects.

Tôi cũng thích ghi đè Set-Locationlệnh ghép ngắn để chạy cả Set-LocationGet-ChildItem.

Yêu thích khác của tôi là có thể làm một mkdirđiều Set-Location xyzsau khi chạy New-Item xyz -Type Directory.


2
Function funcOpenPowerShellProfile
{
    Notepad $PROFILE
}

Set-Alias fop funcOpenPowerShellProfile

Chỉ có một cá nhân lười biếng sa sút mới cho bạn biết điều fopđó dễ nhập hơn nhiều so với Notepad $PROFILElúc nhắc, tất nhiên, trừ khi bạn liên kết "fop" với một ninja Anh thế kỷ 17 .


Nếu bạn muốn, bạn có thể tiến thêm một bước nữa và làm cho nó trở nên hữu ích:

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

Set-Alias fop funcOpenPowerShellProfile

Để thỏa mãn người theo chủ nghĩa sinh tồn-hoang tưởng:

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

trong số nhiều thứ khác:

function w {
    explorer .
}

mở một cửa sổ thám hiểm trong thư mục hiện tại

function startover {
    iisreset /restart
    iisreset /stop

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

    iisreset /start
}

loại bỏ mọi thứ trong các tệp asp.net tạm thời của tôi (hữu ích để làm việc trên mã được quản lý có phụ thuộc vào mã không được quản lý có lỗi)

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

chỉnh sửa $ x trong notepad ++



2

Jeffrey Snover's Start-NewScope bởi vì việc khởi chạy lại shell có thể là một lực cản.

Tôi không bao giờ cảm thấy thoải mái với các tùy chọn bẩn , vì vậy :

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

Tương tự như vậy, tiện lợi để xem xét không gian đĩa:

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

Để chỉ vào nội dung:

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

Người nghèo? Để tìm kiếm các tệp txt lớn.

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

Liệt kê các chương trình được cài đặt trên máy tính từ xa.

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

Đi theo meta, truyền bá phúc âm, không

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

Tôi giữ hồ sơ của mình trống. Thay vào đó, tôi có các thư mục tập lệnh mà tôi có thể điều hướng để tải chức năng và bí danh vào phiên. Một thư mục sẽ có dạng mô-đun, với các thư viện chức năng và hội đồng. Đối với công việc đặc biệt, tôi sẽ có một tập lệnh để tải các bí danh và hàm. Nếu tôi muốn trộn các nhật ký sự kiện, tôi sẽ điều hướng đến một thư mục scripts \ eventlogs và thực thi

PS > . .\DotSourceThisToLoadSomeHandyEventLogMonitoringFunctions.ps1

Tôi làm điều này vì tôi cần chia sẻ tập lệnh với người khác hoặc di chuyển chúng từ máy này sang máy khác. Tôi muốn có thể sao chép một thư mục gồm các tập lệnh và tập hợp và nó chỉ hoạt động trên bất kỳ máy nào cho bất kỳ người dùng nào.

Nhưng bạn muốn có một bộ sưu tập thủ thuật thú vị. Đây là một kịch bản mà nhiều "hồ sơ" của tôi phụ thuộc vào. Nó cho phép các cuộc gọi đến các dịch vụ web sử dụng SSL tự ký để khám phá đặc biệt các dịch vụ web đang được phát triển. Có, tôi tự do trộn C # trong các tập lệnh quyền hạn của mình.

# 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

Câu hỏi tuyệt vời. Bởi vì tôi xử lý một số máy chủ PowerShell khác nhau, tôi thực hiện một chút đăng nhập vào từng cấu hình trong số một số cấu hình, chỉ để làm cho ngữ cảnh của bất kỳ thông báo nào khác rõ ràng hơn. Trong profile.ps1, tôi hiện chỉ có điều đó, nhưng đôi khi tôi thay đổi nó dựa trên ngữ cảnh:

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

Máy chủ yêu thích của tôi là ISE, trong Microsoft.PowerShellIse_profile.ps1, tôi có:

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

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.