Powershell 执行文件和脚本 15


象运行可执行文件一样,Powershell运行文件和脚本,也必须使用绝对路径或者相对路径,或者要运行的文件必须定义在可受信任的环境变量中。

关于脚本

脚本和批处理都属于伪可执行文件,它们只是包含了若干命令行解释器能够解释和执行的命令行代码。

执行批处理文件

批处理是扩展名为”.bat”的文本文件,它可以包含任何cmd控制台能够处理的命令。当批处理文件被打开,Cmd控制台会逐行执行每条命令。那Powershell能够直接执行批处理吗?
将下列命令保存为ping.bat

@echo off
echo batch File Test
pause
Dir %windir%/system

然后执行ping
屏幕会打印ping命令帮助,说明调用的ping cmd 而不是ping.bat。
改为:

PS C:\PS> ./ping
batch File Test
Press any key to continue . . .
 Volume in drive C has no label.
 Volume Serial Number is 4E9B-D846

 Directory of C:Windowssystem

2009/06/11  05:21            69,584 avicap.dll
2009/06/11  05:21           109,456 avifile.dll
2009/07/14  05:41            32,816 COMMDLG.DLL
2009/07/14  05:41             2,000 keyboard.drv
2009/06/11  05:42             9,936 lzexpand.dll
2009/06/11  05:21            73,376 mciavi.drv
2009/06/11  05:21            25,264 mciseq.drv
2009/06/11  05:21            28,160 mciwave.drv
2009/07/14  05:41            68,992 MMSYSTEM.DLL
2009/07/14  05:41             1,152 mmtask.tsk
2009/07/14  05:41             2,032 mouse.drv
2009/06/11  05:21           126,912 msvideo.dll
2009/06/11  05:42            82,944 olecli.dll
2009/07/14  05:41            24,064 OLESVR.DLL
2009/07/14  05:41             5,120 SHELL.DLL
2009/07/14  05:41             1,744 sound.drv
2009/06/11  05:25             5,532 stdole.tlb
2009/07/14  05:41             3,360 system.drv
2009/07/14  05:41             4,048 TIMER.DRV
2009/06/11  05:42             9,008 ver.dll
2009/07/14  05:41             2,176 vga.drv
2009/07/14  05:41            12,704 WFWNET.DRV
              22 File(s)        700,380 bytes
               2 Dir(s)  75,927,420,928 bytes free

这时运行的是批处理。

通过cmd进入cmd控制台输入ping发现执行的不是ping命令,而是直接运行ping.bat ,也就是说可以通过.bat 覆盖cmd命令。这种机制很危险,如果有人侵入电脑,并将系统内部命令篡改成自己批处理,那就太悲剧了。 这种命令与脚本的混淆不会发生在powershell中,因为powershell有更安全的机制。

执行VB脚本文件

将下列命令保存为test.vbs

Set wmi = GetObject("winmgmts:")
Set collection = wmi.ExecQuery("select * from Win32_Process")
For Each process in collection
WScript.Echo process.getObjectText_
Next

执行 .\test.vbs 会遍历当前Win32进程,并把每个进程的详细信息通过窗口显示出来。
怎样让VB脚本的通过控制台输出呢?
Wscript //H:CScript
怎样还原VB脚本通过窗口输出呢?
WScript //H:WScript
在powershell中执行VB脚本

PS C:\PS> cscript.exe .test.vbs
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.

instance of Win32_Process
{
        Caption = "System Idle Process";
        CreationClassName = "Win32_Process";
        CSCreationClassName = "Win32_ComputerSystem";
        CSName = "test-me-01";
        Description = "System Idle Process";
        Handle = "0";
        HandleCount = 0;
        KernelModeTime = "484113379271";
        Name = "System Idle Process";
        OSCreationClassName = "Win32_OperatingSystem";
        OSName = "Microsoft Windows 7 Enterprise |C:Windows|DeviceHarddisk0Partition2";
        OtherOperationCount = "0";
        OtherTransferCount = "0";
        PageFaults = 0;
        PageFileUsage = 0;
        ParentProcessId = 0;
        PeakPageFileUsage = 0;
        PeakVirtualSize = "0";
        PeakWorkingSetSize = 0;
        Priority = 0;
        PrivatePageCount = "0";
        ProcessId = 0;
        QuotaNonPagedPoolUsage = 0;
        QuotaPagedPoolUsage = 0;
        QuotaPeakNonPagedPoolUsage = 0;
        QuotaPeakPagedPoolUsage = 0;
        ReadOperationCount = "0";
        ReadTransferCount = "0";
        SessionId = 0;
        ThreadCount = 2;
        UserModeTime = "0";
        VirtualSize = "0";
        WindowsVersion = "6.1.7601";
        WorkingSetSize = "24576";
        WriteOperationCount = "0";
        WriteTransferCount = "0";
};

执行powershell脚本

Powershell拥有自己的脚本,扩展名为“.ps1”

PS C:\PS> echo "dir;Get-PSProvider;help dir" >test.ps1
PS C:\PS> Get-Content ./test.ps1
dir;Get-PSProvider;help dir
PS C:\PS> ./test.ps1

初次执行脚本时,可能会碰到一个异常:
File ” C:\PS\test.ps1″ cannot be loaded because the
execution of scripts is disabled on this system. Please see
“get-help about_signing” for more details.
At line:1 char:10
+ .test.ps1 <<<<

这是powershell的默认安全设置禁用了执行脚本,要启用这个功能需要拥有管理员的权限。

Powershell调用入口的优先级

别名:控制台首先会寻找输入是否为一个别名,如果是,执行别名所指的命令。因此我们可以通过别名覆盖任意powershell命令,因为别名的优先级最高。

函数:如果没有找到别名,会继续寻找函数,函数类似别名,只不过它包含了更多的powershell命令。因此可以自定义函数扩充cmdlet 把常用的参数给固化进去。

命令:如果没有找到函数,控制台会继续寻找命令,即cmdlet,powershell的内部命令。

脚本:没有找到命令,继续寻找扩展名为“.ps1”的Powershell脚本。

文件:没有找到脚本,会继续寻找文件,如果没有可用的文件,控制台会抛出异常。
The term ‘now’ is not recognized as the name of a cmdlet, function, script file, or operable program. Chec
g of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:4
+ now <<<<
+ CategoryInfo : ObjectNotFound: (now:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

本文链接: https://www.pstips.net/powershell-invoking-files-and-scripts.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

15 条评论 “Powershell 执行文件和脚本

  • jumpwinner

    请问,如何在cmd命令行下运行带参数的脚本?

    如github上的powercat.ps1脚本,需要加参数-l -p。
    本人在PS>下是可以带参数执行的,但是切换到cmd下想直接调用powershell执行,并不想进入PS>下。

  • 刘翰

    你好!多谢分享!但是,我按照您所说的“将下列命令保存为ping.bat

    @echo off
    echo batch File Test
    pause
    Dir %windir%/system”
    然后,执行ping,结果得到的结果是
    PS C:\> ./ping
    无法将“./ping”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后
    重试。
    所在位置 行:1 字符: 7
    + ./ping <<<<
    + CategoryInfo : ObjectNotFound: (./ping:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    请问是怎么回事?

    • 二了一霎那

      根据你的command, ping.bat 文件应该保存存放在C盘下边。
      另外在我目前的版本里边。
      PS C:\WINDOWS\system32> $PSVersionTable.PSVersion

      Major Minor Build Revision
      —– —– —– ——–
      5 1 14393 953
      在运行ping.bat 会给出如下提示:
      Suggestion [3,General]: The command ping.bat was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: “.\pi
      ng.bat”. See “get-help about_Command_Precedence” for more details.
      意味着修改后的command 应该是”.\ping.bat”, 是反斜杠而不是斜杠。

  • 平常心

    您好,按照文章中的提示,将下文保存为ping.bat。
    @echo off
    echo batch File Test
    pause
    Dir %windir%/system

    运行后产生了错误;powershell是2.0的
    PS C:\> ./ping
    batch File Test
    请按任意键继续. . .
    参数格式不正确 – “system”。
    PS C:\>

    • 肖俊平

      PS C:\> ./ping
      batch File Test
      请按任意键继续. . .
      驱动器 C 中的卷是 Windows
      卷的序列号是 B87A-E147

      C:\WINDOWS\system 的目录

      2016/07/16 19:47 .
      2016/07/16 19:47 ..
      2016/07/16 19:47 Speech
      0 个文件 0 字节
      3 个目录 32,682,995,712 可用字节
      PS C:\> type ping.bat
      @echo off
      echo batch File Test
      pause
      Dir %windir%\system
      PS C:\>
      最后一行的命令种的反斜杠有问题,改过来就行了

    • 肖俊平

      PS C:\> ./ping
      batch File Test
      请按任意键继续. . .
      驱动器 C 中的卷是 Windows
      卷的序列号是 B87A-E147

      C:\WINDOWS\system 的目录

      2016/07/16 19:47 .
      2016/07/16 19:47 ..
      2016/07/16 19:47 Speech
      0 个文件 0 字节
      3 个目录 32,682,995,712 可用字节
      PS C:\> type ping.bat
      @echo off
      echo batch File Test
      pause
      Dir %windir%\system
      PS C:\>
      最后一行system前面的斜杠有问题