标签: powershell

如何向 PowerShell PSDrive“function:”上的函数对象添加属性?

我尝试使用 $function:foo 值和 get-item function:foo。所有尝试都成功修改了临时函数对象,但在重新分配给存储函数时(通过 $function:foo = ... 或 set-item function:foo ...),附加属性丢失。

以下是我尝试的结果(全部失败):

设置

$=>函数 foo { "foo" }
$=>$f = $函数:foo
$=>$f = $f | 添加成员注释属性栏 BARvalue -pass
$=>$f | 通用汽车*

   类型名称:System.Management.Automation.ScriptBlock

名称 成员类型 定义
---- ---------- ----------
bar NoteProperty System.String bar=BARvalue

#1

$=>设置项函数:f $f -force
$=>$函数:foo | 通用汽车*
>

#2

$=>$函数:f = $f
$=>$函数:foo | 通用汽车*
>

#3

$=>$f = 获取项目函数:foo
$=>$f | 通用汽车

   类型名称:System.Management.Automation.FunctionInfo

名称 成员类型 定义
---- ---------- ----------
等于方法 System.Boolean Equals(Object obj)
GetHashCode 方法 System.Int32 …

powershell properties

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

如何检查 powershell 脚本是否是从托管 API 签名的?

我想使用 .net Powershell SDK 执行 powershell。我这个工作正常。在执行之前,我想检查脚本是否已由我的代码签名证书签名 - 这很容易在 powershell 本身内使用 Get-AuthenticodeSignature 完成,但我想在选择执行此脚本之前在代码中执行此操作。

解决方案:

        Runspace runSpace = RunspaceFactory.CreateRunspace();
        runSpace.Open();

        Pipeline shell = runSpace.CreatePipeline();
        shell.Commands.AddScript(String.Format("Get-AuthenticodeSignature '{0}'", Filename));

        Signature sig = (shell.Invoke()[0]).BaseObject as Signature;
        bool isValid = sig.Status == SignatureStatus.Valid;
Run Code Online (Sandbox Code Playgroud)

powershell

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

select-xml 不返回任何结果

我正在尝试使用 powershell 命令 select-xml 从 xml 文件中选择数据。当我运行下面的命令时,没有返回结果或错误。我希望屏幕上返回版本列表。这有什么问题吗?

PS C:\> select-xml -path "C:\t.xml" -xpath "//edition" | foreach {$_.node.InnerXML}
PS C:\>
Run Code Online (Sandbox Code Playgroud)

XML 文件 (C:\t.xml) 是:

 <?xml version="1.0" encoding="utf-8"?>
  <Book>
    <projects>
      <project name="Book1" date="2009-01-20">
        <editions>
           <edition language="English">En.Book1.com</edition>
           <edition language="German">Ge.Book1.Com</edition>
           <edition language="French">Fr.Book1.com</edition>
           <edition language="Polish">Pl.Book1.com</edition>
        </editions>
      </project>
    </projects>
  </Book>
Run Code Online (Sandbox Code Playgroud)

powershell

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

Powershell 如何在字符串和双精度之间进行比较?

我刚刚意识到 PowerShell 可以在字符串和数字之间进行比较,我不明白这一点,因为它们是不同的类型。PowerShell 如何比较它们?

PS C:\> Get-Host | Select-Object Version

Version
-------
5.1.19041.1023


PS C:\> $version = (Get-WmiObject -Class Win32_Product | where name -eq 'AWS Command Line Interface v2').Version
PS C:\> $version
2.0.7.0
PS C:\> $version -is [string]
True
PS C:\> 2.0 -is [double]
True
PS C:\> $version -gt 2.0
True
PS C:\> $version -gt 2.1
False
PS C:\> $version -gt 2.0.9
True
Run Code Online (Sandbox Code Playgroud)

powershell

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

获取 Powershell 的剪贴板:'-Raw' 选项?

从微软文档手册中,我找到了 PowerShell 的“Get-Clipboard”选项。
选项是 '-Raw' :

-Raw :获取剪贴板的全部内容。多行文本作为单个多行字符串而不是字符串数组返回。

但是我找不到添加“-Raw”的任何区别。
例如,

powershell.exe "Get-Clipboard -Format text " > MyText.txt
Run Code Online (Sandbox Code Playgroud)

和

powershell.exe "Get-Clipboard -Format text -Raw" > MyText.txt
Run Code Online (Sandbox Code Playgroud)

给出相同的结果。(不管剪贴板的内容如何)你能给我举个例子,让'-Raw'选项的使用有所不同吗?

clipboard powershell command-line text

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

在 PowerShell 中将十六进制字符串转换为 base 64

我正在尝试在 PowerShell 中复制以下 Python 代码段的功能:

allowed_mac_separators = [':', '-', '.']
for sep in allowed_mac_separators:
    if sep in mac_address:
        test = codecs.decode(mac_address.replace(sep, ''), 'hex')
        b64_mac_address = codecs.encode(test, 'base64')
        address = codecs.decode(b64_mac_address, 'utf-8').rstrip()
Run Code Online (Sandbox Code Playgroud)

它需要一个 MAC 地址,删除分隔符,将其转换为十六进制,然后是 base64。(我没有编写 Python 函数,也无法控制它或它是如何工作的。)

例如,MAC 地址AA:BB:CC:DD:E2:00将转换为AABBCCDDE200,然后转换为,b'\xaa\xbb\xcc\xdd\xe2\x00'最后作为输出b'qrvM3eIA'。我尝试做类似的事情:

$bytes = 'AABBCCDDE200' | Format-Hex
[System.BitConverter]::ToString($bytes);
Run Code Online (Sandbox Code Playgroud)

但这会产生MethodException: Cannot find an overload for "ToString" and the argument count: "1".,我不确定它在寻找什么。我发现的所有使用该调用的示例都只有一个参数。这有效:

[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes('AABBCCDDE200'))

但显然不会先将其转换为十六进制,从而产生不正确的结果。任何帮助表示赞赏。

powershell base64 hex

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

如果使用 -Wait 参数运行,如何在 powershell 中更改进程的优先级?

我正在使用预定的 PowerShell 脚本在循环中多次使用各种参数启动相同的进程。过程计算量很大,运行时间很长,我有数千次迭代。我注意到,因为它是一个预定脚本,所以它以低于正常的优先级运行。即使我碰到它,任何产生的进程仍然低于正常。因此,由于我在循环中运行此过程数千次,因此我需要-Wait像这样使用:

foreach($list in $lists){

        Start-Process -FilePath $path_to_EXE -ArgumentList $list -NoNewWindow -Wait

}
Run Code Online (Sandbox Code Playgroud)

现在,我想提高优先级,我发现的一种方法是这样做:

($MyProcess = Start-Process -FilePath $path_to_EXE -ArgumentList $list  -NoNewWindow -Wait -PassThru).PriorityClass = [System.Diagnostics.ProcessPriorityClass]::AboveNormal
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用,因为它需要等到进程完成,然后执行括号外的任何内容:(...).PriorityClass = ... 我不能让它继续循环并产生数千个进程,我需要一次运行一个,但是我如何告诉它提高优先级,然后等待?

powershell wait start-process

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

将参数字符串转换为 Here 字符串

我想用 Start-Process 和 -Wait 调用 ffmpeg,$ArgumentList 有问题

function convertgif {
  
  $ArgumentList = @'
 -i $($args[0]) -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" "$([IO.Path]::ChangeExtension($args[0], 'mp4'))"
'@
  Start-Process -FilePath "C:\ffmpeg\bin\ffmpeg.exe" -ArgumentList $ArgumentList -Wait -NoNewWindow;
}
Run Code Online (Sandbox Code Playgroud)

我找不到如何修复错误

$args[0]: No such file or directory
Run Code Online (Sandbox Code Playgroud)

powershell

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

Cmdlet 实例持续多久?

对派生的 Cmdlet 的自定义实现会是什么样子感兴趣,真的想看看涉及多少工作。模拟了以下内容:

using System.Management.Automation;

namespace EMSEngineering
{
    [Cmdlet(VerbsDiagnostic.Test, "Cmdlet")]
    public class TestCmdlet : Cmdlet
    {
        static int nextIndex = 0;

        private int index = nextIndex;

        public TestCmdlet()
        {
            System.Console.WriteLine("instantiating {0}", index);
            nextIndex++;
        }

        ~ TestCmdlet()
        {
            System.Console.WriteLine("terminating {0}", index);
        }

        [Parameter(Mandatory = true, ValueFromPipeline = true)]
        public string[] SomeParameter { get; set; }

        protected override void BeginProcessing()
        {
            if (SomeParameter != null)
                WriteVerbose(string.Format("begin processing {0} params", SomeParameter.Length));
        }

        protected override void ProcessRecord()
        {
            foreach (string param in SomeParameter)
                WriteObject(string.Format("processing …
Run Code Online (Sandbox Code Playgroud)

powershell

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

返回不像我期望的那样

我正在解决问题

这是我首先提出的解决方案

using namespace System.Linq
$DebugPreference = "Continue"
 
class kata{
    static [string] FirstNonRepeatingLetter ([String]$string_){
        [Enumerable]::GroupBy([char[]]$string_, [func[char, char]]{$args[0]}).Foreach{
            if ($_.Count -eq 1){
                Write-Debug ($_.key)
                return $_.Key 
            }
        }
        return "~~~"
    }
}
 
Write-Debug ([kata]::FirstNonRepeatingLetter("stress"))
Run Code Online (Sandbox Code Playgroud)

回来了

DEBUG: t
DEBUG: r
DEBUG: e
DEBUG: ~~~
Run Code Online (Sandbox Code Playgroud)

这不是我所期望的 我试试这个

using namespace System.Linq
$DebugPreference = "Continue"
 
class kata{
    static [string] FirstNonRepeatingLetter ([String]$string_){
        $groups = [Enumerable]::GroupBy([char[]]$string_, [func[char, char]]{$args[0]})
        foreach ($group in $groups)
        {
            if ($group.Count -eq 1){
                return $group.Key 
            }
        }
        return "~~~"
    }
}
 
Write-Debug …
Run Code Online (Sandbox Code Playgroud)

linq powershell

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