gpt4 book ai didi

powershell - ScriptBlock 中的变量 - Powershell

转载 作者:行者123 更新时间:2023-12-02 01:43:39 34 4
gpt4 key购买 nike

我的 powershell 脚本有一个 GUI。如果 C: 中的文件夹“Temp”不存在 - 创建文件夹并记录条目“Path C:\Temp 不存在 - 创建文件夹”。

这是我的代码的摘录:

$infofolder=$global:dText.AppendText("Path C:\Temp does not exist - create folder`n")

###create C:\Temp if does not exist
Invoke-Command -Session $session -ScriptBlock {
$temp= "C:\Temp"
if (!(Test-Path $temp)) {
$Using:infofolder
New-Item -Path $temp -ItemType Directory}
}

我必须使用在 ScriptBlock 外部定义的变量,因此我使用“$Using”。但变量 $infofolder 只能在脚本 block 中执行。不幸的是,它之前已经执行过,这没有意义,因为日志条目也是在文件夹存在时创建的。

而且我无法使用 $using:global:dText.AppendText("Path C:\Temp does not Exist - createfolder`n")。

谢谢!!

最佳答案

您无法跨远程 session 共享“事件对象” - 这意味着您无法像您一样跨 session 边界调用方法(例如AppendText())”我正在尝试做。

相反,使用管道使用 Invoke-Command 的输出并在调用 session 中调用 AddText():

Invoke-Command -Session $session -ScriptBlock {
$temp= "C:\Temp"
if (!(Test-Path $temp)) {
Write-Output "Path '$temp' does not exist - create folder"
New-Item -Path $temp -ItemType Directory |Out-Null
}
# ... more code, presumably
} |ForEach-Object {
# append output to textbox/stringbuilder as it starts rolling in
$global:dText.AppendText("$_`n")
}

关于powershell - ScriptBlock 中的变量 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71221685/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com