欢迎各位兄弟 发布技术文章
这里的技术是共享的
powershell 窗口 如何运行 ps1 文件
在 PowerShell 窗口中运行 .ps1
文件可以通过以下几种方法实现:
开启执行权限(如果未设置过):
默认情况下,PowerShell 会限制脚本执行。以管理员身份运行 PowerShell,输入以下命令允许脚本运行:
powershellSet-ExecutionPolicy RemoteSigned -Scope CurrentUser
RemoteSigned
:允许本地脚本运行,远程脚本需签名。
其他选项:Unrestricted
(无限制,不安全)或 Bypass
(仅本次会话允许)。
运行脚本:
powershell& "C:\路径\脚本名.ps1"
或直接输入脚本路径:
powershellC:\路径\脚本名.ps1
powershell.exe
命令
(适用于旧版或需要额外参数时)
powershellpowershell.exe -File "C:\路径\脚本名.ps1"
附加参数:
-NoProfile
:不加载用户配置文件,加快启动。
-ExecutionPolicy Bypass
:临时绕过执行策略限制。
Invoke-Expression
(适用于动态脚本内容,但有安全风险)
powershellInvoke-Expression -Command (Get-Content "C:\路径\脚本名.ps1" -Raw)
报错“无法加载文件,因为在此系统上禁止运行脚本”
需先执行 Set-ExecutionPolicy
(见方法1)。
路径包含空格
用引号包裹路径:
powershell& "C:\我的文件夹\脚本.ps1"
以管理员身份运行脚本
手动:右键 PowerShell 图标 → “以管理员身份运行”,再执行脚本。
自动:在脚本内添加管理员权限检查:
powershellif (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Start-Process powershell.exe "-File `"$PSCommandPath`"" -Verb RunAs exit }
假设脚本路径为 D:\example.ps1
,步骤:
打开 PowerShell。
输入:
powershell& "D:\example.ps1"
通过以上方法,你可以灵活地在 PowerShell 中运行 .ps1
脚本。根据实际需求选择合适的方式即可!
& "D:\example.ps1" 其中 & 是什么意思
在 PowerShell 中,&
(称为调用运算符,Invoke Operator)用于执行命令、脚本或代码块,通常用于以下场景:
作用:将字符串(如脚本路径)当作命令执行。
示例:
powershell& "D:\example.ps1"
这里的 &
告诉 PowerShell:将 "D:\example.ps1"
解释为可执行命令(而非普通字符串)。
powershell$scriptPath = "D:\example.ps1" & $scriptPath # 执行变量中的路径
&
?路径包含特殊字符(如空格):
PowerShell 默认会尝试解析不带引号的字符串,而路径中的空格会导致歧义。例如:
powershellD:\My Scripts\example.ps1 # 可能报错:My 被误认为命令 & "D:\My Scripts\example.ps1" # 正确
区分“字符串”和“可执行对象”:
powershell"Get-Process" # 只是一个字符串,不会执行 & "Get-Process" # 实际运行 Get-Process 命令
运算符 | 用途 | 示例 |
---|---|---|
& | 执行命令或脚本(无新进程) | & "D:\example.ps1" |
. | 执行脚本并在当前作用域运行(变量共享) | . "D:\example.ps1" |
Start-Process | 启动新进程运行程序 | Start-Process "D:\example.ps1" |
能否省略 &
?
路径无空格或特殊字符(如 D:\example.ps1
)。
脚本位于当前目录时,需加 .\
(如 .\example.ps1
)。
可以,但需满足以下条件:
推荐始终使用 &
,避免意外行为。
& "D:\example.ps1"
中的 &
是调用运算符,确保字符串路径被正确执行为脚本。
它是 PowerShell 灵活性和安全性的重要设计之一,尤其在处理动态脚本或复杂路径时必不可少。