我有一个用于powershell脚本的GUI。如果C:中的文件夹"Temp“不存在-创建文件夹和日志条目”路径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只应该在Scriptblock中执行。不幸的是,它之前已经被执行了,这是没有意义的,因为日志记录条目也是在文件夹存在时创建的。
我不能使用$using:global:dText.AppendText(“路径C:\Temp不存在-创建文件夹”)。
谢谢!!
发布于 2022-02-22 12:59:27
您不能在远程会话之间共享“活动对象”--这意味着您无法像您正在尝试的那样,跨会话边界调用方法(如AppendText())。
相反,使用管道来使用来自Invoke-Command的输出并在调用会话中调用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")
}https://stackoverflow.com/questions/71221685
复制相似问题