- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有几个使用hashbang将其标识为Python3脚本的python3脚本。基于文件扩展名的脚本不能被识别为python,因为它们没有任何脚本(就像在其他* nix系统中一样)。
我已经研究过相关的问题,但是它们并不能满足这一特殊需求,并且似乎依赖于*.py
扩展名进行识别。
Set up Python on Windows to not type "python" in cmd
How to make python scripts executable on Windows?
所以我的脚本名为:myscript
,文件的第一行是:
#!/usr/bin/env python3
...
C:\Python3.7
中的python解释器运行它?
pip install
与本机Windows Python3一起使用时,第一行hashbang被自动替换为:
#!c:\python37\python.exe
test4script.ps1
:
Param([parameter(Mandatory=$true, HelpMessage="Need a valid filename")] $fileName)
$firstLine = Get-Content -Path $fileName -TotalCount 1
$SHEBANG="^#!"
$shes=@("python3","python2","python","bash","sh","perl","pwsh")
If ($firstLine -match $SHEBANG) {
Write-Host "DEBUG: checking for common shebangs" -ForegroundColor Green
foreach ($i in $shes) {
If ($firstLine -match $i) {
Write-Host "DEBUG: found shebang for: $i" -ForegroundColor Green
C:\python37\python.exe $fileName
break
}
}
} else {
Write-Host "File is not a known script. No shebang fund in file!" -ForegroundColor Red
return
}
Write-Host "DEBUG: Done" -ForegroundColor Green
$ Get-Content -Path nonscript -TotalCount 3
#This aint right
echo "hello"
$ Get-Content -Path pip-describe -TotalCount 3
#!c:\python37\python.exe
# pip-describe - Show full text package description from PyPI
# -*- coding: utf-8 -*-
$ .\test4script.ps1 nonscript
File is not a known script. No shebang fund in file!
$ .\test4script.ps1 pip-describe
DEBUG: checking for common shebangs
DEBUG: found shebang for: python3
Usage: pip-describe <package-name>
This will return the full-text package description (usually the README)
as found on PyPI, for any given <package-name>.
...
.
关联:
cmd /c assoc .=unknown
cmd /c "ftype unknown=""C:\mybin\test4script.ps1"" %1"
最佳答案
eryksun在问题注释中提供了很好的指针,根据它们进行的编辑显示了安装通用的,机器范围的shebang-line-aware启动器的方法,该启动器用于通过将.
添加到
有关此方法的注意事项:
PowerShell当前(从PowerShell Core 6.2.0开始)始终在新的控制台窗口中执行无扩展名的文件,这使该配置在PowerShell中无用-尽管确实可以按
$env:PATHEXT
的要求运行。
PowerShell的行为应视为错误,并且已在
this GitHub issue中报告。
该机制存在潜在的安全风险,因为任何不带带有shebang行的扩展名的纯文本文件都将有效地变为可执行文件,从而有可能绕过专注于具有已知可执行文件扩展名的安全功能。
通过[PowerShell]脚本实现文件类型定义的默认操作,总是需要使用脚本文件的解释器创建子进程,在这种情况下,这意味着使用其
cmd.exe
参数调用
powershell.exe
。
-File
的启动性能成本是微不足道的,这会延迟执行时间。
如果您确实想实现这种通用机制,请参阅底部的
powershell.exe
脚本。
鉴于以上所述,这是一种更轻量级的,特定于Python的方法,基于自动为无扩展的shebang-line Python脚本创建单个
Install-ShebangSupport.ps1
包装器脚本:
这利用了PowerShell仅允许按文件名执行自己的
*.ps1
脚本文件这一事实。
局限性:
您需要至少运行一次wrapper-script-generation脚本(如下所示),并且每次添加新的无扩展Python脚本时。
可以想象,可以使用文件系统监视程序来触发生成脚本,但是进行设置并不是一件容易的事。
从好的方面来说,包装脚本比基于通用文件类型的解决方案执行得更快,因为不涉及额外的PowerShell实例(子进程)。
从无扩展Python脚本所在的目录中运行以下脚本[1]:
Get-ChildItem -File | Where-Object Extension -eq '' | % {
if ((Get-Content -LiteralPath $_.fullname -First 1) -match '^#!.*\bpython') {
@'
py.exe ($PSCommandPath -replace '\.ps1$') $Args; exit $LASTEXITCODE
'@ > ($_.FullName + '.ps1')
}
}
*.ps1
,都会创建一个伴随
somescript
文件,该文件将
somescript.ps1
以及任何命令行参数传递给Python启动器
somescript
。
py.exe
确保通过
exit $LASTEXTICODE
的退出代码。
py.exe
应该能够解释shebang行以调用适当的Python可执行文件。
py.exe
文件将它们加载到每个会话中才能使用:
Get-ChildItem -File | Where-Object Extension -eq '' | % {
if ((Get-Content -LiteralPath $_.FullName -First 1) -match '^#!.*\bpython') {
Invoke-Expression @"
Function global:$($_.Name) {
py.exe "$($_.FullName)" `$Args
}
"@
}
}
$PROFILE
中列出的目录中一样-无论当前目录是否在此列出。
$env:PATH
包装器脚本文件方法允许在给定目录中进行定向调用,例如
*.ps1
。
.\foo
的这种特殊用法是安全的-基于可扩展字符串定义函数-但
Invoke-Expression
should generally be avoided。
Invoke-Expression
用于安装通用支持,以在Windows上直接执行无扩展名的基于shebang行的脚本:
Install-ShebangSupport.ps1
)或在所有用户级别(使用
-Scope CurrentUser
,需要以admin身份运行)进行安装。
-Scope AllUsers
以获得基本帮助。
Get-Help .\Install-ShebangSupport
会执行安装而不会提示您进行确认。
-Force
;请注意,您必须匹配安装期间使用的(隐含的)
-Uninstall
值。
-Scope
-内部命令
cmd.exe
和
assoc
定义无扩展名文件类型始终对所有用户有效,因为定义存储在注册表中的
ftype
中。同样,因此调用总是需要提升权限(管理特权)。
<#
.SYNOPSIS
Support for direct execution of extension-less script files with shebang lines
on Windows.
.DESCRIPTION
For details, invoke this script without arguments: the confirmation prompt
will show the required modifications to your system. Submit "N" to opt out
of the installation.
Note that extension-less files that do not have a shebang line will open in
the default text editor.
.PARAMETER Scope
Whether to install support for the current user only (the default) or
for all users (requires invocation as admin).
.PARAMETER Uninstall
Uninstalls previously installed support.
Note that the (implied) -Scope value must match the one that was used during
installation.
.PARAMETER Force
Bypasses the confirmation prompt that is shown by default.
.EXAMPLE
Install-ShebangSupport
Installation for the current user that requires answering a confirmation prompt.
.EXAMPLE
Install-ShebangSupport -Scope AllUsers -Force
Installation for all users without confirmation prompt. Requires invocation
as admin.
.EXAMPLE
Install-ShebangSupport -Uninstall
Uninstallation for the current user with confirmation prompt.
#>
[CmdletBinding(PositionalBinding=$false)]
param(
[ValidateSet('CurrentUser', 'AllUsers')]
[string] $Scope = 'CurrentUser'
,
[switch] $Force
,
[switch] $Uninstall
)
$ErrorActionPreference = 'Stop'; Set-StrictMode -Version 1
if ($env:OS -ne 'Windows_NT') { Throw ("This script can only run on Windows.")}
# ---------------------- BEGIN: Internal helper functions
# === INSTALL
function install {
Write-Verbose ('Installing shebang-script support for {0}:' -f ('the current user', 'ALL users')[$forAllUsers])
# NOTE:
# * assoc and ftype only ever operate on HKEY_LOCAL_MACHINE\Software\Classes, not HKEY_CURRENT_USER\Software\Classes - both on reading and writing.
# * *HKEY_CURRENT_USER*-level definitions DO work, but *neither assoc nor ftype report them or can update them*.
# Therefore, we perform direct registry manipulation below.
Write-Verbose 'Creating file type for extension-less file names via the registry...'
# Map the "extension-less extension", "." to the name of the new file type to be created below.
# Caveat: Sadly, New-Item -Force blindly recreates the registry key if it already exists, discarding
# all existing content in the process.
$key = New-Item -Force -Path $regkeyExtensionToFileType
$null = New-ItemProperty -LiteralPath $key.PSPath -Name '(default)' -Value $fileTypeName
# Define the new file type:
$key = New-Item -Force -Path "$regkeyFileType\Shell\Open\Command"
$null = New-ItemProperty -LiteralPath $key.PSPath -Name '(default)' -Value ('powershell.exe -noprofile -file "{0}" "%1" %*' -f $helperScriptFullName)
# Get the current $env:PATHEXT definition from the registry.
$currPathExt = [Environment]::GetEnvironmentVariable('PATHEXT', ('User', 'Machine')[$forAllUsers])
if (-not $forAllUsers -and -not $currPathExt) {
Write-Verbose "Creating a static user-level copy of the machine-level PATHEXT environment variable..."
$currPathExt = [Environment]::GetEnvironmentVariable('PATHEXT', 'Machine')
}
# Add "." as an executable extension to $env:PATHEXT so as to support
# direct execution of extension-less files.
if ($currPathExt -split ';' -notcontains '.') {
Write-Verbose "Appending '.' to PATHEXT..."
[Environment]::SetEnvironmentVariable('PATHEXT', $currPathExt + ';.', ('User', 'Machine')[$forAllUsers])
# Also define it for the running session
$env:PATHEXT += ';.'
} else {
Write-Verbose "'.' is already contained in PATHEXT."
}
# The following here-string is the source code for the
# $helperScriptFullName script to create.
# To debug and/or modify it:
# * Edit and/or debug $helperScriptFullName
# * After applying fixes / enhancements, replace the here-string
# below with the updated source code.
@'
# When invoked by direct execution of a script file via the file-type definition, the arguments are:
# * The full path of the script file being invoked.
# * Arguments passed to the script file on invocation, if any.
# CAVEAT: PowerShell's own parsing of command-line arguments into $args
# breaks unquoted tokens such as >> -true:blue << and >> -true.blue << into *2* arguments
# ('-true:', 'blue' and '-true', '.blue', respectively).
# The only way to avoid that is to pass the argument *quoted*: '-true:blue' and '-true.blue'
# See https://github.com/PowerShell/PowerShell/issues/6360
# Parse the arguments into the script
param(
[Parameter(Mandatory=$true)] [string] $LiteralPath,
[Parameter(ValueFromRemainingArguments=$true)] [array] $passThruArgs
)
$ErrorActionPreference = 'Stop'; Set-StrictMode -Version 1
# Note: When invoked via the file-type definition, $LiteralPath is guaranteed to be a full path.
# To also support interactive use of this script (for debugging), we resolve the script
# argument to a full path.
# Note that if you pass just a script filename (<script>), it'll be interpreted relative
# to the current directory rather than based on an $env:PATH search; to do the latter,
# pass (Get-Command <script>).Source
if ($LiteralPath -notmatch '^(?:[a-z]:)?[\\/]') { $LiteralPath = Convert-Path -LiteralPath $LiteralPath }
# Check the script's first line for a shebang.
$shebangLine = ''
switch -Regex -File $LiteralPath {
'^#!\s*(.*)\s*$' { # Matches a shebang line.
# Save the shebang line and its embedded command.
$shebangLine = $_
$cmdLine = $Matches[1]
Write-Verbose "Shebang line found in '$LiteralPath': $shebangLine"
break # We're done now that we have the shebang line.
}
default { # no shebang line found -> open with default text editor
# Note: We cannot use Invoke-Item or Start-Process, as that would
# reinvoke this handler, resulting in an infinite loop.
# The best we can do is to open the file in the default text editor.
Write-Verbose "No shebang line, opening with default text editor: $LiteralPath"
# Obtain the command line for the default text editor directly from the registry
# at HKEY_CLASSES_ROOT\txtfile\shell\Open\command rather than via `cmd /c ftype`,
# because assoc and ftype only ever report on and update the *machine-level* definitions at
# HKEY_LOCAL_MACHINE\Software\Classes
$cmdLine = [environment]::ExpandEnvironmentVariables((((Get-ItemProperty -EA Ignore registry::HKEY_CLASSES_ROOT\txtfile\shell\Open\command).'(default)') -split '=')[-1])
if (-not $cmdLine) { $cmdLine = 'NOTEPAD.EXE %1' } # Fall back to Notepad.
break # We're done now that we know this file doesn't have a shebang line.
}
}
# Parse the shebang line's embedded command line or the default-text-editor's command line into arguments.
# Note: We use Invoke-Expression and Write-Output so as to support *quoted*
# arguments as well - though presumably rare in practice.
# If supporting quoted tokens isn't necessary, the next line can be replaced
# with a strictly-by-whitespace splitting command:
# $cmdArgs = -split $cmdLine
[array] $cmdArgs = (Invoke-Expression "Write-Output -- $($cmdLine -replace '\$', "`0")") -replace "`0", '$'
if ($shebangLine) {
# Extract the target executable name or path.
# If the first argument is '/usr/bin/env', we skip it, as env (on Unix-like platforms) is merely used
# to locate the true target executable in the Path.
$exeTokenIndex = 0 + ($cmdArgs[0] -eq '/usr/bin/env')
$exeNameOrPath = $cmdArgs[$exeTokenIndex]
$exeFullPath = ''
# Note: We do NOT pass any remaining arguments from the shebang line through.
# (Such arguments are rare anyway.)
# The rationale is that an interpreter that understands shebang lines will
# also respect such arguments when reading the file - this is true of at
# least py.exe, the Python launcher, and ruby.exe
# Python is a special case: the Python launcher, py.exe, is itself
# capable of interpreting shebang lines, so we defer to it.
if ($exeNameOrPath -match '\bpython\d?') {
# Ensure that 'py.exe' is available; if not, we fall back to the same approach
# as for all other executables.
$exeFullPath = (Get-Command -CommandType Application py.exe -ErrorAction Ignore).Source
}
if (-not $exeFullPath) {
# Try the executable spec. as-is first, should it actually contain a *Windows* path name.
$exeFullPath = (Get-Command -CommandType Application $exeNameOrPath -ErrorAction Ignore).Source
if (-not $exeFullPath) {
# If not found, assume it is a Unix path that doesn't apply, and try to locate the hopefully
# appropriate executable by its filename only, in the Path.
$exeFullPath = (Get-Command -CommandType Application (Split-Path -Leaf -LiteralPath $exeNameOrPath) -ErrorAction Ignore).Source
}
}
# Abort, if we can't find a suitable executable.
if (-not $exeFullPath) { Throw "Could not find a suitable executable to run '$LiteralPath' based on its shebang line: $shebangLine" }
# Synthesize the complete list of arguments to pass to the target exectuable.
$passThruArgs = , $LiteralPath + $passThruArgs
} else { # NON-shebang-line files: invocation of default text editor
$exeFullPath, [array] $editorArgs = $cmdArgs -replace '%1', ($LiteralPath -replace '\$', '$$')
# Synthesize the complete list of arguments to pass to the target exectuable.
# Replace the '%1' placeholder with the script's path.
# Note that we don't really expect additional arguments to have been passed in this scenario,
# and such arguments may be interpreted as additional file arguments by the editor.
$passThruArgs = ($editorArgs -replace '"?%1"?', ($LiteralPath -replace '\$', '$$$$')) + $passThruArgs
# If the editor is a GUI application, $LASTEXITCODE won't be set by PowerShell.
# We set it to 0 here, as it has no value by default, and referencing it below with exit
# would cause an error due to Set-StrictMode -Version 1.
$LASTEXITCODE = 0
}
Write-Verbose "Executing: $exeFullPath $passThruArgs"
# Invoke the target executable with all arguments.
# Important:
# * We need to manually \-escape embeded " chars. in arguments
# because PowerShell, regrettably, doesn't do that automatically.
# However, even that may fail in edge cases in Windows PowerShell (fixed in PS Core),
# namely when an unbalanced " char. is part of the first word - see https://stackoverflow.com/a/55604316/45375
& $exeFullPath ($passThruArgs -replace '"', '\"')
# Pass the target executable's exit code through.
# (In the case of invoking the default editor for non-shebang-line files, it
# won't have been set, if the editor is a GUI application.)
exit $LASTEXITCODE
'@ |
Set-Content -Encoding Utf8 -LiteralPath $helperScriptFullName
}
# === UNINSTALL
function uninstall {
Write-Verbose ('Uninstalling shebang-script support for {0}:' -f ('the current user', 'ALL users')[$forAllUsers])
Write-Verbose 'Removing file type information from the registry...'
foreach ($regKey in $regkeyExtensionToFileType, $regkeyFileType) {
if (Test-Path -LiteralPath $regKey) {
Remove-Item -Force -Recurse -LiteralPath $regkey
}
}
# Get the current $env:PATHEXT definition from the registry.
$currPathExt = [Environment]::GetEnvironmentVariable('PATHEXT', ('User', 'Machine')[$forAllUsers])
# Remove the "." entry from $env:PATHEXT
$newPathExt = ($currPathExt -split ';' -ne '.') -join ';'
if ($newPathExt -eq $currPathExt) {
Write-Verbose "'.' is not contained in PATHEXT; nothing to do."
} else {
# For user-level uninstallations: as a courtesy, we compare the new PATHEXT value
# to the machine-level one, and, if they're now the same, simply REMOVE the user-level definition.
Write-Verbose "Removing '.' from PATHEXT..."
if (-not $forAllUsers) {
$machineLevelPathExt = [Environment]::GetEnvironmentVariable('PATHEXT', 'Machine')
if ($newPathExt -eq $machineLevelPathExt) { $newPathExt = $null }
Write-Verbose "User-level PATHEXT no longer needed, removing..."
}
[Environment]::SetEnvironmentVariable('PATHEXT', $newPathExt, ('User', 'Machine')[$forAllUsers])
# Also update for the running session
$env:PATHEXT = if ($newPathExt) { $newPathExt } else { $machineLevelPathExt }
}
Write-Verbose "Removing helper PowerShell script..."
if (Test-Path -LiteralPath $helperScriptFullName) {
Remove-Item -Force -LiteralPath $helperScriptFullName
}
}
# ---------------------- END: Internal helper functions
$forAllUsers = $Scope -eq 'AllUsers'
$verb = ('install', 'uninstall')[$Uninstall.IsPresent]
$operation = $verb + 'ation'
# If -Scope AllUsers was passed, ensure that the session is elevated.
$mustElevate = $forAllUsers -and -not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole('BUILTIN\Administrators')
if ($mustElevate) {
Throw "In order to $verb for ALL users, you must run this script WITH ELEVATED PRIVILEGES (Run As Administrator)."
}
# --- Define names, registry and file locations.
# The path of the generic shebang runner script that we'll create below.
$helperScriptFullName = Join-Path ($HOME, $env:ALLUSERSPROFILE)[$forAllUsers] 'Invoke-ShebangScript.ps1'
# The name of the file type to create for extension-less files.
$fileTypeName = 'ShebangScript'
# Registry keys that need to be modified.
# "." represents extension-less files
$regkeyExtensionToFileType = 'registry::{0}\SOFTWARE\Classes\.' -f ('HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE')[$forAllUsers]
$regkeyFileType = 'registry::{0}\SOFTWARE\Classes\{1}' -f ('HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE')[$forAllUsers], $fileTypeName
# ---
# Prompt for confirmation, unless -Force was passsed.
if ($Uninstall) { # UNINSTALL
if (-not $Force -and -not $PSCmdlet.ShouldContinue(@"
You are about to UNINSTALL support for direct execution of extension-less
script files that have shebang lines.
Uninstallation will be performed for $(("the CURRENT USER only`n(invoke as admin with -Scope AllUsers to change that)", 'ALL USERS')[$forAllUsers]).
IMPORTANT: Uninstallation will only be effective if it is performed in the same
(implied) -Scope as the original installation.
The following modifications to your system will be performed:
* "." will be persistently REMOVED from your `$env:PATHEXT variable.
* The following registry keys will be REMOVED:
$($regkeyExtensionToFileType -replace '^registry::')
$($regkeyFileType -replace '^registry::')
* The following helper PowerShell script will be REMOVED:
$helperScriptFullName
Press ENTER to proceed, or Ctrl-C to abort.
"@, "Shebang-Script Direct-Execution Support - Uninstallation")) { # , $true, [ref] $null, [ref] $null)) {
exit 1
}
# Call the uninstallation helper function
uninstall
} else { # INSTALL
if (-not $Force -and -not $PSCmdlet.ShouldContinue(@"
You are about to install support for direct execution of Unix-style scripts
that do not have a filename extension and instead define the interpreter to run
them with via shebangline ("#!/path/to/interpreter").
Support will be installed for $(("the CURRENT USER only`n(invoke as admin with -Scope AllUsers to change that)", 'ALL USERS')[$forAllUsers]).
Once installed, you will be able to run such scripts by direct invocation,
via a helper PowerShell script that analyzes the shebang line and calls the
appropriate interpreter.
CAVEATS:
* ENABLING THIS INVOCATION MECHANISM IS A SECURITY RISK, because any
plain-text file without an extension that has a shebang line
effectively becomes executable, potentially bypassing security features
that focus on files that have extensions known to be executable.
* AS OF POWERSHELL CORE 6.2.0, direct execution of such extension-less files
from PowerShell INVARIABLY RUNS IN A NEW CONSOLE WINDOW, WHICH MAKES USE
FROM POWERSHELL VIRTUALLY USELESS.
However, this is a BUG that should be fixed; see:
https://github.com/PowerShell/PowerShell/issues/7769
The following modifications to your system will be performed:
* "." will be added persistently to your `$env:PATHEXT variable, to enable
direct execution of filenames without extension.
NOTE: If you install with -Scope CurrentUser (the default), a static
user-level copy of the machine-level PATHEXT environment variable is
created, unless already present.
* The following registry locations will be created or replaced to define a
new file type for extension-less filenames:
$($regkeyExtensionToFileType -replace '^registry::')
$($regkeyFileType -replace '^registry::')
* The helper PowerShell script will be created in:
$helperScriptFullName
NOTE: Any existing registry definitions or helper script will be REPLACED.
Press ENTER to proceed, or CTRL-C to abort.
"@, "Shebang-Script Direct-Execution Support - Installation")) {
# !! The prompt defaults to *Yes* (!)
# !! Sadly, if we wanted the prompt to be default to *No*, we'de be forced
# !! to also present pointless 'Yes/No to *All*' prompts, which would be confusing.
# !! See https://github.com/PowerShell/PowerShell/issues/9428
exit 1
}
# Call the installation helper function
install
}
Write-Verbose "Shebang-support ${operation} completed."
if (-not $Force) {
Write-Host "Shebang-support ${operation} completed."
}
exit 0
HKEY_LOCAL_MACHINE\Software\Classes
来更方便,更有效地查找无扩展名的文件,但是此功能在PowerShell Core v6.2.0及更高版本中已失效-请参见
this GitHub issue。
关于python - 如何基于python shebang从powershell运行python程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55601446/
我正在寻找实现 PowerShell 提供程序 在 电源外壳。 我一直在想,如果我只是定义类型,然后将它们导入我的 session (导入模块),我应该能够让它们可用。 例如,这个 不工作但它沿着我想
我创建的脚本使用了组件,这些组件仅在32位版本的Powershell中可用。 默认情况下,Windows使用Powershell x64执行脚本,这会导致一些错误。 是一种在脚本开头设置值以强制Win
是否可以从 Powershell 中检测它是否是嵌套 shell? 如果我打开 Powershell 或 cmd.exe 窗口,然后输入 powershell 在那里,是否有一个神奇的 $host.s
随着 PowerShell Core 的发布,应用程序在使用托管自动化库 (system.management.automation) 时如何选择调用哪个版本的 Powershell(Powershe
最近,我加入了我企业的 Windows 团队,凭借我的开发人员背景(一般是 Java、.NET 和 Web),我很快就对 PowerShell 产生了兴趣。我可以看到它比普通的旧批处理文件、VB 更有
假设我有一个 powershell 脚本,它在我当前路径的相对路径中包含一个 Powershell 哈希。让我们称之为“name.ps1”,它包含: $names = @{ "bob" = "b
我想为我正在构建的自定义 Powershell Commandlet 使用 SqlServerCmdletSnapin。如果我将以下代码添加到 PSM1 的开头: if ( (Get-PSSnapin
如何调用从 PowerShell 脚本中获取命名参数的 PowerShell 脚本? foo.ps1: param( [Parameter(Mandatory=$true)][String]$a=''
我即将为 Windows 管理员编写一个 PowerShell 脚本,以帮助他们完成与部署 Web 应用程序相关的某些任务。 有什么理由让我应该赞成或排除开发 PowerShell 模块 (.psm1
我的 powershell 模块有一个函数,我希望它返回一个非零退出代码。但是,作为一个模块函数,当我运行 Import-Module 时,它会加载到 powershell 控制台的上下文中。所以,当
我在这个问题上花了最后 4 个小时,非常感谢您提供的任何意见。 我需要使用不同的凭据调用 powershell 脚本并将参数传递给该脚本。 安装 WISEScript 中包装的程序后,此脚本开始收集机
我有一个场景,我需要将 powershell 命令的命令和输出转发到另一个进程以进行日志记录和处理。 我希望这个控制台尽可能接近 powershell,因此不希望将它简单地托管在另一个控制台程序中。
我正在尝试让一个主 PowerShell 脚本运行所有其他脚本,同时等待 30-60 秒以确保完成任务。我尝试过的所有其他操作都不会停止/等待第一个脚本及其进程完成,然后才能同时完成所有其他脚本,并且
我正在编写一个脚本来使用多个 plink (PuTTY) session 作为 Windows 版本的 clustersh。然而,我陷入困境,因为我想从 powershell 打开多个 Powersh
我读了这个答案:How to Open Powershell from Powershell start powershell 这将打开基础的大分辨率 PS 实例。如何打开 PS(x86)? 最佳答案
我很想知道我们是否可以在 Powershell 中做到这一点。 使用 Out-File 命令,我们可以通过管道将其输出写入文件。这样我就可以将我所有的历史命令发送到一个文本文件中。 问题是我可以在每次
我在 about_Pipelines 阅读了有关 PowerShell 中的管道工作原理的信息,并了解到管道一次传送一个对象。 所以,这个 Get-Service | Format-Table -Pr
我正在尝试像这样从 powershell 启动一个进程:- $proc = (start-process $myExe -argumentList '/myArg True' -windowStyle
## To run the script # .\get_status.ps1 -Hostname -Service_Action -Service_Name #$Hostname = "hos
让我们使用 powershell 命令 Write-Host "red text"-Fore red这会在红色前景中显示“红色文本”。 但是,您希望文本以稍微亮一点的方式显示字体颜色,浅红色。 有没有
我是一名优秀的程序员,十分优秀!