标签: scriptblock

管道进入 ScriptBlock

我试图在 PowerShell 中找到一些灵活更改/替换管道元素的方法:

Function Where-DirectlyReportsTo {
    Param (
        [Parameter(
            ValueFromPipeline = $true,
            HelpMessage = "The ADUser object to be tested"
        )]
        [Microsoft.ActiveDirectory.Management.ADUser] $ADUser,
        [Parameter( 
            Mandatory = $true,
            ValueFromPipeline = $false,
            Position = 0
        )]
        [String] $mgrDN
    )
    Process {
        If ($ADUser) {
            If ($ADUser.Manager -eq $mgrDN) { Return $ADUser }
        }
    }
}

$Properties = @("Manager")
$users = Get-ADUser -Filter * -SearchBase $OU -Properties $Properties
[ScriptBlock] $sb = {Where-DirectlyReportsTo "CN=Colonel Foobar,$OU"}
$DNs = $users | $sb | %{$_.DistinguishedName}
Run Code Online (Sandbox Code Playgroud)

我想返回向 Foobar …

powershell pipe scriptblock

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

解释从PowerShell闭包调用的函数的范围

以下PowerShell代码显示从闭包调用的函数的意外作用域行为.你能解释一下这是"按设计"还是缺陷?

function runblock($block) {
    $x = 4
    & $block
}

function printx() {
    "  in printx: x=" + $x
}

"PSVersion $($PSVersionTable.PSVersion)"

$x = 1
$b = {"In block x=" + $x ; $x = 3 ; printx}
$x = 2
runblock $b

$x = 1
$b = {"In closure x=" + $x ; $x = 3 ; printx}.GetNewClosure()
$x = 2
runblock $b
Run Code Online (Sandbox Code Playgroud)

以上输出是

PSVersion 3.0
In block x=4
  in printx: x=3
In closure x=1
  in printx: x=4
Run Code Online (Sandbox Code Playgroud)

大部分输出对我有意义: …

powershell closures scriptblock

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

对于 PowerShell cmdlet,我可以始终将脚本块传递给字符串参数吗?

我正在查看 PowerShell 的Rename-Itemcmdlet的文档,有一个这样的例子。

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt','.log' }
Run Code Online (Sandbox Code Playgroud)

此示例说明如何使用 Replace 运算符重命名多个文件,即使 NewName 参数不接受通配符也是如此。

此命令将当前目录中的所有 .txt 文件重命名为 .log。

该命令使用 Get-ChildItem cmdlet 获取当前文件夹中具有 .txt 文件扩展名的所有文件。然后,它使用管道运算符 (|) 将这些文件发送到 Rename-Item 。

NewName 的值是在将值提交给 NewName 参数之前运行的脚本块。

注意最后一句话:

NewName 的值是在将值提交给 NewName 参数之前运行的脚本块

实际上NewName是一个字符串:

[-NewName] <String>
Run Code Online (Sandbox Code Playgroud)

那么这是否意味着当所需的参数类型是字符串时,我总是可以使用脚本块?

parameters powershell cmdlets scriptblock delay-bind

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

我不能在ForEach-Object中使用begin/process/end块?

我有以下代码:

function f()
{
    begin{$count=0}
    process{$count+=10}
    end{$count}
}
1..10|f # OK
1..10|%{
    begin{$count=0}
    process{$count+=10}
    end{$count}
} # Error
Run Code Online (Sandbox Code Playgroud)

第一个"f"调用成功,而%{}块显示错误:

100
% : The script block cannot be invoked because it contains more than one clause. The Invoke() method can only be used on script blocks that contain a single clause.
At D:\Untitled1.ps1:13 char:7
+ 1..10|%{
+       ~~
    + CategoryInfo          : InvalidOperation: (:) [ForEach-Object], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.ForEachObjectCommand
Run Code Online (Sandbox Code Playgroud)

但为什么?ForEach-Object不支持begin/ process/ end块?

powershell foreach scriptblock

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

使用 C# 执行 Powershell 命令时在 ScriptBlock 中设置参数

我正在尝试在 C# 中执行以下 powershell 命令

Invoke-Command -Session $session -ScriptBlock {
  Get-MailboxPermission -Identity ${identity} -User ${user}
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下 C# 代码,但无法设置身份和用户参数。

var command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", ScriptBlock.Create("Get-MailboxPermission -Identity ${identity} -User ${user}"));
command.AddParameter("identity", mailbox);
command.AddParameter("user", user);
Run Code Online (Sandbox Code Playgroud)

当我在创建 ScriptBlock 时对值进行硬编码时,它工作正常。如何动态设置参数。

有没有更好的方法来做到这一点,而不是像下面那样连接值。

command.AddParameter("ScriptBlock", ScriptBlock.Create("Get-MailboxPermission -Identity " + mailbox + " -User " + user));
Run Code Online (Sandbox Code Playgroud)

c# powershell scriptblock

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

如何在 C# 中使用 powershell 调用命令?

如果我在 Powershell 中运行以下命令,它会按预期工作

invoke-command -computername [name] -scriptblock { ipconfig.exe > c:\ipconfig.txt }

但是当我尝试将其合并到 ac# 函数中时,我收到此错误

{“无法绑定参数“ScriptBlock”。无法将“System.String”类型的“ipconfig.exe > c:\ipconfig.txt”值转换为“System.Management.Automation.ScriptBlock”类型。 ”}

即使我将 scriptblock 参数值转换为 System.Management.Automation.ScriptBlock 对象?我做错了什么?

    private void btnInstallTest_Click(object sender, EventArgs e)
    {
        List<string> commands = new List<string>();

        commands.Add("invoke-command");
        List<Tuple<String, String>> parameters = new List<Tuple<string, string>>();
        parameters.Add(new Tuple<string, string>("computername", @"server"));
        parameters.Add(new Tuple<string, string>("ScriptBlock", @"ipconfig.exe > c:\ipconfig.txt"));

        Collection<PSObject> psobject = runRemotePowerShellCommands(commands, parameters, "server", @"domain\user", convertToSecureString("password"));          
    }

    private Collection<PSObject> runRemotePowerShellCommands(List<string> commands, List<Tuple<String, String>> parameters, string remoteMachineName, string domainAndUsername, SecureString securePW)
    {
        Collection<PSObject> psobjs = …
Run Code Online (Sandbox Code Playgroud)

c# powershell runspace scriptblock

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