标签: powershell

将 .ps1 转换为 .bat 不会导致 cmd.exe 达到最大字符长度 - 但为什么呢?

根据相关问题和一些谷歌搜索/测试,很明显命令行的最大长度cmd.exe是8,191字符。然而......我的脚本似乎成功地超过了这个长度,我不明白它为什么有效。

所以我有:

  • 编写/保存为的脚本.ps1
  • 我正在使用将 PowerShell 转换为批处理中的方法将其转换为.bat
  • 如果我运行.bat- 似乎没有任何问题
  • 如果我尝试回显该命令或在运行之前$encoded删除- 很容易看到 的长度/内容已被截断...但它按预期工作@echo off.bat$encoded

我意识到这是一个有点奇怪的问题,因为我试图确定一些关于有效的东西与坏的东西的隐藏真相,但我想了解它为什么有效!

注意: 我为脚本创建 的主要原因.bat是因为我有许多小“程序”,需要在工作计算机上运行并与其他人共享。我们公司的执行策略不允许运行脚本,如果它是 a ,其他人使用我写的东西会更容易,.bat因为他们不需要理解/使用PowerShell. 他们只需将其放置.bat在正确的位置,单击两次,然后坐下来放松,直到发生事情。

编辑:这是窗口中被截断的命令cmd.exe。如果我从 Base64 转换回可读文本,它显然会丢失大约一半的脚本。然而 - 我没有注意到任何问题 截断命令

windows powershell cmd batch-file

3
推荐指数
1
解决办法
445
查看次数

使用 PowerShelll 将 Microsoft Edge 设置为默认浏览器

我正在编写一个脚本,将默认浏览器更改为 Microsoft Edge,我已经这样做了:

function Set-DefaultBrowser {
  Add-Type -AssemblyName 'System.Windows.Forms'
  Start-Process $env:windir\system32\control.exe -LoadUserProfile -Wait -ArgumentList '/name Microsoft.DefaultPrograms /page pageDefaultProgram\pageAdvancedSettings?pszAppName=MSEdgeHTM'
  Sleep 10
  [System.Windows.Forms.SendKeys]::SendWait("{TAB}{TAB}{TAB}{TAB}{TAB} {ENTER}{ENTER} ")
}
Set-DefaultBrowser
Run Code Online (Sandbox Code Playgroud)

但我不喜欢一个人打开菜单,我想做的事情而不像那样显示,可以这样做吗?

browser windows powershell microsoft-edge

3
推荐指数
1
解决办法
9785
查看次数

Powershell 模块不会自动加载 Linux 容器

我有一个 Powershell 模块,如下所示:

function SayHello
{
    echo "hello"
}
Run Code Online (Sandbox Code Playgroud)

我将其另存为say-hello.psm1并将其添加到 dockerfile 中,如下所示:

COPY --chmod=0755 say-hello.psm1 /root/.local/share/powershell/Modules/say-hello.psm1
Run Code Online (Sandbox Code Playgroud)

当我启动 docker 映像并运行时,SayHello它告诉我它找不到命令:

SayHello 无法识别

但是,如果我随后运行 Import-Module 命令并重试,它会起作用:

如果手动导入可以工作

我想也许我有错误的文件夹,但是当我运行时,$Env:PSModulePath我得到了/root/.local/share/powershell/Modules:/usr/local/share/powershell/Modules:/opt/microsoft/powershell/7/Modules. 根据文档,这就是模块应该放置的位置。(我把它放在第一个)

我需要做什么才能让我的 powershell 模块工作而无需手动导入?

linux powershell containers docker-container

3
推荐指数
1
解决办法
507
查看次数

Powershell 读取文件中的文本等待找到然后继续

我正在开发一个跨远程服务器启动某些服务的过程,但是服务器 2 无法启动,直到在服务器 1 日志中找到消息,服务器 3 才能启动,直到服务器 2 中找到相同的消息,等等。

我的问题是,是否可以在“循环”中读取文件,并且在找到该消息之前不继续进行初始循环(然后继续前进)?我想我可以在下面做,但是,虽然它确实识别出日志文件中的字符串已找到,但它只是重复找到它,直到内置计时器完成然后向前移动。因此,该过程将类似于“读取此文件,如果找到字符串,则继续前进。如果未找到字符串,则等待 30 秒并重新扫描文件。如果找到,则继续前进,如果未找到,则再等待 30 秒,然后重新扫描(我可以连续重复)< 执行此操作,直到找到字符串。示​​例:在此处输入图像描述

任何建议将不胜感激,因为我认为我可能会从错误的角度来处理这个问题......

-- 我省略了此脚本之前的大部分脚本,只包含 If/Else 语句,因为这是它检查文件的地方。

$SEL = Select-String -Path \\$Server\$RootDir\folder\anotherfolder\A-Log-File.log -Pattern "Switching to status: STARTED"
if ($SEL -ne $null)
{
    Write-Host "FOUND: Switching to status: STARTED" -ForegroundColor Yellow -BackgroundColor DarkGreen
}
else
    {
        Write-Host **** Waiting 60 seconds for cache to build ****
            [int]$Time = 60
            $Lenght = $Time / 100
            For ($Time; $Time -gt 0; $Time--) {
            $min = [int](([string]($Time/60)).split('.')[0])
            $text = " …
Run Code Online (Sandbox Code Playgroud)

powershell

3
推荐指数
1
解决办法
1002
查看次数

在 Office 插件生成器 Yeoman 中运行“yo office”时出现执行策略错误

我想使用 yeoman 为带有 Angular 的办公室创建一个插件。在power shell中安装了nodeJs、Angular、yeoman、generator-office等需求工具后,我尝试运行此代码

yo office 
Run Code Online (Sandbox Code Playgroud)

但我收到了这个错误:

 yo : File C:\Users\ME\AppData\Roaming\npm\yo.ps1 cannot be loaded. 
The file C:\Users\ME\AppData\Roaming\npm\yo.ps1 is not digitally signed. 
You cannot run this script on the current system. 
For more information about running scripts and setting execution policy, 
see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ yo office
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess  
Run Code Online (Sandbox Code Playgroud)

powershell office-addins yeoman angular project-web-addins

3
推荐指数
1
解决办法
863
查看次数

PowerShell Invoke 返回数组而不是 int

我有以下 PowerShell 片段:

$property = @{
    Getter = { 80 };
}

$value = $property.Getter.Invoke() 
$value.GetType() # Shows Name = Collection'1 instead of int
Run Code Online (Sandbox Code Playgroud)

我希望$value.GetType()返回Int32,但它返回一个集合。

我不能只获取元素[0],因为有时 Getter 函数会返回一个数组。

我怎样才能解决这个问题?

powershell

3
推荐指数
1
解决办法
219
查看次数

PowerShell - 如何在 REST 调用的 JSON 字符串中转义 {}

我正在读取 HTML 文件,需要将其作为字符串参数传递给 JSON 调用。HTML 中有用于 css/样式的大括号。我正在看这个问题,但我的问题更多的是围绕 JSON 特殊字符,其中一个是其他转义字符。该文件还可能包含 [] 字符。

$HtmlFromFile2 = @"
<html>
    <style type="text/css">.LetterList {font-family:"arial"}</style>
    <body>
        To [firstname]:
        This is a normal body with special JSON characters. 
    </body>
</html>
"@
$HtmlFromFile2Stripped = $HtmlFromFile2.Replace("`r", "").Replace("`n", "").Replace("`t","") 
#$HtmlFromFileFixed = % { [System.Text.RegularExpressions.Regex]::Unescape($HtmlFromFile2Stripped) }
$HtmlFromFileFixed = $HtmlFromFile2Stripped.Replace("{","\{").Replace("}","\}")

Write-Host "After RegEx Fix"
Write-Host $HtmlFromFileFixed 

$templateID = "Test_Temp7"


$body = @"
{   "uuid": "$templateID",
    "subject": "My Email Subject",
    "body": "$HtmlFromFileFixed"
}
"@

# This also tests if our JSON is …
Run Code Online (Sandbox Code Playgroud)

powershell

3
推荐指数
1
解决办法
1155
查看次数

如何扩展变量中的属性

如果我走

$c = Resolve-DnsName facebook.com -Type TXT -Server '8.8.8.8'
Run Code Online (Sandbox Code Playgroud)

当我进入时$c我得到

Name                                     Type   TTL   Section    Strings
----                                     ----   ---   -------    -------
facebook.com                             TXT    7200  Answer     {v=spf1 redirect=_spf.facebook.com}        
facebook.com                             TXT    7200  Answer     {google-site-verification=A2WZWCNQHrGV_TW  
                                                                 wKh6KHY90tY0SHZo_RnyMJoDaG0s}
facebook.com                             TXT    7200  Answer     {google-site-verification=wdH5DTJTc9AYNwV  
                                                                 unSVFeK0hYDGUIEOGb-RReU6pJlY}
Run Code Online (Sandbox Code Playgroud)

我该如何扩展$c.strings?

我知道我可以得到扩展的字符串并失去其余的

Resolve-DnsName facebook.com -Type TXT -Server '8.8.8.8' | Select-Object -ExpandProperty strings
Run Code Online (Sandbox Code Playgroud)

如何扩展整个答案?

powershell

3
推荐指数
1
解决办法
454
查看次数

Powershell `-replace` 正则表达式与换行符不匹配

我正在尝试使用正则表达式清理一些 html 文件(是的,我看过这篇文章。我不打算一般解析 html),并且我想删除所有不包含标签的行。我的脚本如下:

Remove-Item $args[1]
$text = (Get-Content -Path $args[0] -Raw)
$text = $text -replace "^\s*\r?\n"
New-Item -Path $args[1] -ItemType File -Force -Value $text
Run Code Online (Sandbox Code Playgroud)

我想更换很多其他东西,但我主要是在尝试修复

我可以验证内部正则表达式是否有效:VSCode(使用 JS 正则表达式而不是 powershell 的 .NET 正则表达式)使用提供的正则表达式正确匹配(并替换)有问题的行。

我知道Powershell 是 Special,所以我已将 的输出转换Get-Content为带有嵌入换行符的原始字符串。这并没有帮助。

我可以验证其他函数(即remove-item和new-item)是否工作得很好,并且其他正则表达式可以通过将正则表达式文本从"^\s*\r?\n"to更改为工作"p", "abc"并看到p标签全部变成abc标签来验证。

此外,正则表达式\s*\r?\n可以工作,所以并不是正则表达式找不到换行符。

正则表达式\A\s*\r?\n也不起作用,这意味着它与 PowerShell 如何查找字符串的开头\结尾有关。

这是怎么回事?


Remove-Item $args[1]
$text = (Get-Content -Path $args[0] -Raw)
$text = $text -replace "^\s*\r?\n"
New-Item …
Run Code Online (Sandbox Code Playgroud)

html regex powershell

3
推荐指数
1
解决办法
1233
查看次数

如何在保留当前工作目录并维护传递给脚本的所有参数的同时提升 Powershell?

function Test-IsAdministrator
{
    $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
    $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}

function Test-IsUacEnabled
{
    (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}

if (!(Test-IsAdministrator))
{
    if (Test-IsUacEnabled)
    {
        [string[]]$argList = @('-NoProfile', '-NoExit', '-File', $MyInvocation.MyCommand.Path)
        $argList += $MyInvocation.BoundParameters.GetEnumerator() | ForEach-Object {"-$($_.Key)", "$($_.Value)"}
        $argList += $MyInvocation.UnboundArguments
        Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList 
        return
    }
    else
    {
        throw "You must be an administrator to run this script."
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我运行上面的脚本,它会成功生成另一个具有提升权限的 PowerShell 实例,但当前工作目录会丢失并自动设置为C:\Windows\System32. 绑定参数也会丢失或错误解析。

在阅读类似的问题后,我了解到,当将 Start-Process 与 -Verb RunAs 一起使用时,仅当目标可执行文件是 …

powershell admin elevation

3
推荐指数
1
解决办法
4355
查看次数