如何判断调用.ps1脚本的父Shell是bash还是PowerShell?
区分调用.ps1脚本的Shell是bash还是PowerShell的方法
下面是几种可行的判断方式,可根据运行环境选择:
1. 检查父进程名称
直接获取当前PowerShell进程的父进程名称,这是最直接的判断方式:
Windows环境
$parentProcId = [System.Diagnostics.Process]::GetCurrentProcess().Parent.Id $parentProc = Get-CimInstance Win32_Process -Filter "ProcessId = $parentProcId" $parentName = $parentProc.Name.ToLower() if ($parentName -in 'bash.exe', 'sh.exe', 'zsh.exe') { Write-Host "调用Shell是bash类Shell" } elseif ($parentName -in 'pwsh.exe', 'powershell.exe') { Write-Host "调用Shell是PowerShell" }
Linux/macOS环境
$parentProc = (Get-Process -Id $PID).Parent if ($parentProc.Name -eq 'bash') { Write-Host "调用Shell是bash" } elseif ($parentProc.Name -in 'pwsh', 'powershell') { Write-Host "调用Shell是PowerShell" }
2. 检查环境变量
bash会自动设置BASH、BASH_VERSION这类独有环境变量,PowerShell中默认不会有这些变量,可直接检查:
if ($env:BASH -or $env:BASH_VERSION) { Write-Host "调用Shell是bash" } else { # 结合PowerShell独有变量二次确认 if ($env:PSHOME -and $host.Name -eq 'ConsoleHost') { Write-Host "调用Shell是PowerShell" } }
这种方法适合配合父进程检查,避免单一判断的误判。
3. 补充:检查启动方式(类Unix系统)
如果脚本通过#!/bin/pwsh设置了执行权限,在bash中直接用./test.ps1运行时,和PowerShell内部运行的调用格式有区别,可作为辅助判断:
$callLine = $MyInvocation.Line.Trim() if ($callLine -match '^\./[^ ]+\.ps1') { Write-Host "大概率是bash调用" } elseif ($callLine -match '^[^ ]+\.ps1') { Write-Host "大概率是PowerShell调用" }
内容的提问来源于stack exchange,提问作者Hashbrown
相关产品推荐
相关产品推荐

