标签: powershell

如何将 PowerShell 模式从受限模式更改为全语言模式?

我打开 PS 或 PSISE,它们都是我不期望的约束语言模式。

我不知道为什么它是 ConstrainedLanguage。两天前,只是 PSISE 处于受约束模式,而 PS 处于全语言模式。现在在我重新启动计算机后,它们都是受约束的模式,这让我很困扰,因为我真的需要使用完整模式..

我试图以管理员身份启动 PS,但不起作用。尝试创建一个新的环境变量 __PSLockdownPolicy 并将其设置为 1 或 0,仍然无法正常工作。

我试过“powershell.exe -version 2”,它是fulllanguage,但版本2太低,我不能使用一些高级模块。

PS C:\windows\system32> $ExecutionContext.SessionState.LanguageMode
ConstrainedLanguage

PS C:\windows\system32> $ExecutionContext.SessionState.LanguageMode = 'fulllanguage'
Cannot set property. Property setting is supported only on core types in this language mode.
At line:1 char:1
+ $ExecutionContext.SessionState.LanguageMode = 'fulllanguage'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertySetterNotSupportedInConstrainedLanguage

Run Code Online (Sandbox Code Playgroud)

我希望我可以在全语言模式下打开 PS。感谢你的帮助!

powershell windows-7

3
推荐指数
2
解决办法
3万
查看次数

如果您知道原因,如何使警告静音或什至更好:已分配但从不

$global:ProjectName = $null

function RunFirst(){
  RunSecund
  Write-Host $global:ProjectName
}

function RunSecund(){
    $global:ProjectName = "a name"
}
Run Code Online (Sandbox Code Playgroud)

在 RunSecund 我得到:

变量“ProjectName”已分配但从未使用。PSScriptAnalyzer(PSUseDeclaredVarsMoreThanAssignments)

powershell

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

从 PowerShell 脚本中提取时出错

我有一个简单的 PowerShell 脚本来使文件夹与其 git 存储库保持同步。

Param(
    [Parameter(Mandatory = $true)][string]$branch,
    [string]$location,
    [int]$depth
)

Get-ChildItem -Recurse -Directory -Depth $depth -Filter _$branch -Name -Path $location | 
ForEach-Object {
    Write-Output "`n$("{0:MM/dd/yy} {0:HH:mm:ss}" -f (Get-Date)): Getting latest from $location$_"
    git -C $location$_ pull
} *>> logs\$branch.log
Run Code Online (Sandbox Code Playgroud)

当存储库已经是最新的时,它可以正常工作。但是,如果不是,则输出如下:

07/29/19 14:47:27:从某个路径获取最新信息
git :来自 https://gitlab.com/someplace
在某个地方\UpdateBranch.ps1:10 字符:5
+ git -C $location$_ 拉
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (来自 https://gi...n/somerepo:String) [], RemoteException
    + FullQualifiedErrorId : NativeCommandError

   b34e5d0..3ec9561 开发 -> 起源/开发
   b6d33b1..65fb520 功能/功能 1 -> 原点/功能/功能 1
 * [新分支] …

git powershell

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

如何在powershell中为herestring/heredoc设置编码?

我正在尝试更新 Windows 服务器上的主机文件,并尝试使用 powershell 中的 heredoc 来完成。

我不明白为什么我的结果在每个主机条目中的每个字符之间都有额外的空格。

我正在从 Linux 移植一些脚本。

PS C:\Users\Administrator> cat C:\Users\Administrator\AppData\Local\Temp\etchosts.ps1
@"
127.0.0.1 src.example.com
127.0.0.2 builds.example.com
127.0.0.3 ti.example.com
127.0.0.4 jira.example.com
"@ >>C:\Windows\System32\drivers\etc\hosts



PS C:\Users\Administrator> powershell C:\Users\Administrator\AppData\Local\Temp\etchosts.ps1
PS C:\Users\Administrator> cat C:\Windows\System32\drivers\etc\hosts
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address …
Run Code Online (Sandbox Code Playgroud)

powershell encoding heredoc herestring

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

Powershell Switch Break Label 未执行

作为更大脚本的一部分,我已经实现了switch下面的详细内容。目的是当脚本执行时,用户可以选择

  1. 在屏幕上输入要迁移的用户,或
  2. 从文件导入。

如果选择了从文件导入选项 - 我想测试文件是否存在 - 如果没有,我想突破并返回到开关标签:choose。但是,当我选择从文件导入选项并提供不存在的路径时,脚本会继续运行并且不会中断或返回标签。我哪里错了?

$chooseInputMethod = @"
This script migrates one or more user accounts between two trusted domains in a forest e.g. from domain1 to domain2 (or vice versa)

Select method to specify user(s) to migrate:

1. Enter name(s) on-screen (default)
2. Import name(s) from file

Enter selection number
"@

$choosePath = @"
Enter path to file..

Notes

  - Filename: 
    If file is located in script directory ($pwd) you can enter …
Run Code Online (Sandbox Code Playgroud)

powershell break

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

使用 sAMAccountname 过滤来自 Get-ADUser 的结果

我想使用Get-ADUser. 我遇到的问题是当使用sAMAaccount名称作为过滤器时,如果在多个条目中找到该值,我会得到多个结果。举例说明,如果我samaccountname的名字是“a123b”,而我同事的名字是“c1234d”,当我运行这个命令时,我会得到我们的名字:

get-aduser -ldapFilter "(samaccountname=*123*)"| select Name
Run Code Online (Sandbox Code Playgroud)

我只想根据“123”而不是“1234”返回我的信息

我已经尝试了以下方法也无济于事:

get-aduser -Filter "samaccountname -like '*123*'" | select Name
Run Code Online (Sandbox Code Playgroud)

powershell active-directory

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

获取 Text.RegularExpressions.Regex 匹配的行号

我使用 PowerShell 解析日志文件目录并从日志文件中提取所有 XML 条目。这工作得很好。但是,由于日志文件可以包含许多这些 xml 片段,我想将找到它的特定匹配的行号也放在我编写的 XML 文件的文件名中,因此我可以打开日志文件并跳转到那个特定的行做一些根本原因分析。

有一个字段“索引”是我认为的字符数,这可能应该引导我到行号,但我认为“索引”以某种方式包含其他内容作为 Measure-Object -Character 因为索引的值大于用 Measure-Object-Character 找到的大小,例如 $m.groups[0].Captures[0].Index 是 9963166 但日志目录中的 Measure-Object -Character 整体文件给出 9838833 作为最大值,所以我认为它也计算换行符.

所以问题可能是:如果匹配将“索引”作为属性提供给我,我怎么知道“索引”包含多少换行符?我是否必须从文件中获取“索引”字符,然后检查它包含多少换行符,然后我有该行?大概。

$tag = 'data_json'
$input_dir = $absolute_root_dir + $specific_dir
$output_dir = $input_dir  + 'ParsedDataFiles\'
$OFS = "`r`n"
$nice_specific_dir = $specific_dir.Replace('\','_')
$nice_specific_dir = $nice_specific_dir.Replace(':','_')
$regex = New-Object Text.RegularExpressions.Regex "<$tag>(.+?)<\/$tag>", ('singleline', 'multiline')
New-Item -ItemType Directory -Force -Path $output_dir
Get-ChildItem -Path $input_dir -Name -File | % {   
    $output_file = $output_dir + $nice_specific_dir + $_ + '.'
    $content = Get-Content …
Run Code Online (Sandbox Code Playgroud)

regex powershell logging regex-group

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

如何在 PowerShell 中转义特殊字符?

当我的 PowerShell 脚本运行时,它会提示用户输入密码参数。该密码可以包含任意数量的特殊字符,如 *\~;(%?.:@/ 然后该密码用作 .exe 命令的参数,但由于某些特殊字符没有正确转义,它通常不正确。

一个过去的密码示例是 $(?-.?-(。我需要转义的唯一字符是 '(',我将其替换为 '`(' 以使其工作。但是,该密码现在已过期。新密码类似于 *\~;~(%?.:@/ *注意:这些密码也混合了随机数字和字母,但已被编辑。

新密码中的唯一字符不是第一个是 *\~;%:@/ 是否有一种简单的方法可以转义所有字符并按原样接受任何用户输入?如果没有,有人介意帮我逃脱这些特殊字符吗?


param (
    [Parameter(Mandatory=$true)][string]$password
)
Run Code Online (Sandbox Code Playgroud)

上面的代码位于脚本的前面,使控制台提示用户输入。

Invoke-Expression -Command "<path_to_exe> -install $user $password"
Run Code Online (Sandbox Code Playgroud)

^这是使用该密码参数的命令


我在 Stack Overflow、Reddit 和其他各种编码论坛/博客上尝试了许多其他建议,但都没有奏效。任何帮助深表感谢!

parameters powershell escaping

3
推荐指数
2
解决办法
2万
查看次数

如何从 Remove-Item 中捕获错误并发出警告?

在持续集成管道 (Azure DevOps) 中使用的部署后脚本中,我正在删除旧文件。

基本上,它是一个 PowerShell 脚本,可删除部署目录中的除当前文件夹之外的所有发布文件夹。

有时,Remove-Item 由于某种原因而失败(例如,旧文件仍由部署机器上的某个人打开)

没什么大不了的。我不希望出现错误,说我的整个部署因此而失败。但是,我想要一个警告,所以我知道它发生了。

例如(MCVE):

Remove-Item INEXISTENT_FILE
Run Code Online (Sandbox Code Playgroud)

问题:它会导致错误。


尝试 1:

Remove-Item INEXISTENT_FILE -ErrorAction SilentlyContinue
Run Code Online (Sandbox Code Playgroud)

问题:它完全消除了错误,这不是我想要的(我想要一个警告)


尝试 2:我尝试按照此处的建议使用 ErrorVariable:https ://devblogs.microsoft.com/powershell/erroraction-and-errorvariable/

Remove-Item INEXISTENT_FILE -ErrorAction SilentlyContinue -ErrorVariable $removeItemError
if ($removeItemError) {
    Write-Warning "Warning, something failed!"
}
Run Code Online (Sandbox Code Playgroud)

问题:它不起作用,它不显示if零件。如果我删除“SilentlyContinue”错误操作,它只会发出一个错误,并且在任何情况下都不会进入该if部分。


尝试 3:我也尝试使用此处建议的 Try Catch 块:PowerShell -ErrorAction SilentlyContinue 不适用于 Get-ADUser

Try {
    Remove-Item INEXISTENT_FILE
}
Catch {
    Write-Warning "Warning, something failed!"
}
Run Code Online (Sandbox Code Playgroud)

问题:它也永远不会进入 catch 块(!?)


如果 Remove-Item 失败,任何人都有另一种选择来显示警告而不是错误?

error-handling powershell azure-devops

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

函数内部的 Powershell 别名在外部不可用

我在文件 myfunc.ps1 中有一个 powershell 函数

function Set-Util ($utilPath ) {

    if(Test-Path($utilPath) ){
      $fullPath = Join-Path -Path $utilPath "util.exe"
      set-alias MyUtil $fullPath
      #echo  "Path set to $fullPath"
    }else {
        throw  (" Error: File not found! File path '$fullPath' does not exist.")
    }
}
Run Code Online (Sandbox Code Playgroud)

我点从命令行调用它

. .\myfunc.ps1

然后打电话

Set-Util somedirectory

别名在函数中设置正确,但我无法在这里访问它

我的实用程序

我应该导出别名,因为范围仅在方法中吗?我尝试使用 Export-ModuleMember 执行此操作,但出现错误,提示该 cmdlet 只能从模块中调用。

powershell alias function

2
推荐指数
1
解决办法
403
查看次数