在PowerShell出口上运行脚本

时间:2015-06-29 13:16:43

标签: windows powershell

我如何运行一个PowerShell脚本,该脚本可以在exit命令或shell关闭时运行。我希望这个脚本能够在每个shell上运行,而不仅仅是一个shell。

Script

3 个答案:

答案 0 :(得分:3)

试试这个:

    $url = "http://www.w3schools.com";

    if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
        echo("$url is a valid URL");
    } else {
        echo("$url is not a valid URL");
    }

答案 1 :(得分:2)

将其从函数中取出并在scriptblock中运行,如下所示:

Register-EngineEvent PowerShell.Exiting –Action {

$foo = @"
 .d8888b.  8888888888 8888888888      Y88b   d88P  .d88888b.  888     888
d88P  Y88b 888        888              Y88b d88P  d88P" "Y88b 888     888
 "Y888b.   8888888    8888888            Y888P    888     888 888     888
    "Y88b. 888        888                 888     888     888 888     888
      "888 888        888                 888     888     888 888     888
Y88b  d88P 888        888                 888     Y88b.  d88P Y88b. .d88P
 "Y8888P"  8888888888 8888888888          888      "Y88888P"   "Y88888P"
 .d8888b.  8888888b.     d8888  .d8888b.  8888888888
d88p  Y88b 888   Y88b   d88888 d88P  Y88b 888
 "Y888b.   888   d88P d88P 888 888        8888888
    "Y88b. 8888888P" d88P  888 888        888
      "888 888      d88P   888 888    888 888
Y88b  d88P 888     d8888888888 Y88b  d88P 888
 "Y8888P"  888    d88P     888  "Y8888P"  8888888888
 .d8888b.   .d88888b.  888       888 888888b.    .d88888b. Y88b   d88P
d88P  Y88b d88P" "Y88b 888   o   888 888  "88b  d88P" "Y88b Y88b d88P
888        888     888 888 d888b 888 8888888K.  888     888   Y888P
888        888     888 8888888888888 888  "Y88b 888     888    888
888    888 888     888 88888P Y88888 888    888 888     888    888
Y88b  d88P Y88b. .d88P 8888P   Y8888 888   d88P Y88b. .d88P    888
 "Y8888P"   "Y88888P"  888P     Y888 8888888P"   "Y88888P"     888
"@
 $file="c:\.seeyouspacecowboy"
 $foo | out-file $file
 $colour=("red","yellow","darkyellow","green","cyan","darkcyan","darkmagenta")
 [int]$num=-1
 $info = (get-content $file)
 Write-Host ""
 foreach($i in $info) 
    {
     [int]$perspective=($num / 3)
     write-host $i -foregroundcolor $colour[$perspective]
     $num++   
    }
 Write-Host ""

 }

*当然,请确保您在写入c:\

时具有管理员权限

答案 2 :(得分:0)

另一个选项是try-finally块,它将在错误或ctrl-c时执行finally块:

try {
    # Main code
} finally {
    # Code to run on exit
}