您的PowerShell`profile.ps1`文件中包含什么?[关闭]


85

您的个人资料中有哪些基本内容(功能,别名,启动脚本)?

Answers:


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
此评论没有任何价值,但我只想说您的用户名很棒。
克里斯夫

没有范围问题吗?脚本(包括PowerShell脚本)中定义的所有函数(或别名)是否不限于脚本执行范围,并在调用shell上消失?我的机器上就是这种情况。我该怎么办?
乌里(Uri)

10

要从PowerShell设置我的Visual Studio构建环境,我从这里安装了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,“工具”)
    $ theBatchFile = [System.IO.Path] :: Combine($ theVsToolsDir,“ vsvars32.bat”)
    获取批处理文件$ theBatchFile
    [System.Console] :: Title =“ Visual Studio” + $ version +“ Windows Powershell”
}

1
我使用leeholmes.com/blog/…来调用vcvars。
杰伊·巴祖兹

上面的脚本在64位Windows上不起作用(由于WOW64注册表重定向)。
Govert,2012年

在这种情况下,只需在32位WOW64 cmd.exe Shell中运行它。那不可能吗?
djangofan 2012年

10

这将通过脚本PSDrive进行迭代,并以点源方式源以“ lib-”开头的所有内容。

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

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

9

开始成绩单。这会将整个会话写到一个文本文件中。非常适合培训新员工如何在环境中使用Powershell。


2
+1感谢您的提示...这刚刚解决了我在控制台和日志文件中记录持续集成版本的问题。令我感到失望的是,“ Windows Powershell袖珍参考”或“ Windows PowerShell in Action”中都没有对此进行很好的记录。我想这是您从实践中学到的东西。
彼得·沃克

请注意,并非所有PowerShell主机都提供Start-Transcript命令,因此将其放入独立于主机的配置文件(profile.ps1)在某些情况下可能会产生错误。它在特定于主机的配置文件(例如(Microsoft.PowerShellISE_profile.ps1))中可能很有用。
Burt_Harris

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

@Kiquenet,只需重新启动Powershell会话即可。
Christopher Douglas

+1,细分非常好。谢谢。
萨本库

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距离太远了...

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

@jkdba原来我将它们写到一个文件中,但只有我的会话可以解密该文件,并且只能在我的计算机上使用。试一试,让我知道是否适合您。
Christopher Douglas

1
嗯,有趣的是,我使用的想法基本相同,但是我要做的是使用keepass数据库,然后将我的配置文件配置为打开与数据库的连接,并检索我的凭据作为安全字符串并创建凭据对象。我一直在为他们的sdk开发豪华的keepass代码包装程序,您可以使用我的用户名在git上找到它,该仓库名为PSKeePass(现在检查出dev分支)。它可以很容易地扩展为使用网络登录名和密钥文件额外但简单的安全性,可达到与您正在执行的操作类似的效果。
jkdba

@jkdba多数民众赞成在真棒!如果可以的话,我肯定会检查您的代码并做出贡献。我是keepass的忠实拥护者,但从未有机会将其SDK与PS结合使用。谢谢!
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
而不是Open-IE使用的内置ii别名Invoke-Item
杰伊·巴祖兹

1
ii“ google.com ”不起作用。您如何使用Jay?
凯文·贝里奇

尝试start http://google.com
orad

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代替$ var sometext


我经常会犯O型错误。意识到仅更改12次左右的代码就可以以每种方式起作用,这让我非常谦卑,但您甚至都无法正确拼写属性名称。
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()
}

对于使用xml很有用,例如带--xml的svn命令的输出。


3

这将创建一个脚本:驱动器并将其添加到您的路径。注意,您必须自己创建文件夹。下次您需要重新使用它时,只需键入“ scripts:”并按回车即可,就像Windows中的任何驱动器号一样。

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


2

用于查看键入命令的整个历史记录的功能(Get-History和他的别名h仅显示默认的最后32条命令):

function ha {
    Get-History -count $MaximumHistoryCount
}

2

您可以在http://github.com/jamesottaway/windowspowershell上查看我的PowerShell配置文件

如果您使用Git将我的存储库克隆到Documents文件夹(或$ PROFILE变量中“ WindowsPowerShell”上方的任何文件夹)中,您将大受好评。

主体profile.ps1将子文件夹的名称设置AddonsPSDrive,然后在该文件夹下找到所有要加载的.ps1文件。

我非常喜欢该go命令,该命令存储了一个简明位置字典,可以轻松访问。例如,go vsp带我去C:\Visual Studio 2008\Projects

我也很喜欢重写Set-Locationcmdlet来同时运行Set-LocationGet-ChildItem

我的另一个最喜欢的是能够做mkdir这做Set-Location xyz跑后New-Item xyz -Type Directory


2
Function funcOpenPowerShellProfile
{
    Notepad $PROFILE
}

Set-Alias fop funcOpenPowerShellProfile

只有一个懒惰的人会告诉您,这fopNotepad $PROFILE在提示符下键入要容易得多,除非您将“ fop”与17世纪的英语ninny相关联。


如果您愿意,可以更进一步,使其更有用:

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

Jeffrey Snover的Start-NewScope,因为重新启动外壳可能会很麻烦

我从不满意脏污选项,所以

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

可怜的男人?用于搜索大型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

我将个人资料保留为空。相反,我有一些脚本文件夹,可以浏览以将功能和别名加载到会话中。文件夹将是模块化的,带有功能和程序集库。对于临时工作,我将有一个脚本来加载别名和函数。如果要清除事件日志,请导航到脚本\ 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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.