gpt4 book ai didi

powershell - 嵌套变量问题

转载 作者:行者123 更新时间:2023-12-03 01:21:21 26 4
gpt4 key购买 nike

该脚本是不言自明的,但我不知道如何使其工作。我想弄清楚如何将变量$ComputerPath传递给函数,并在该脚本中设置$ComputerPath

Function CheckPath {
While (!$args[0]) {
Write-Host "`nVariable Undefined"
$Args[0] = Read-Host "Enter Valid Path"
}
while (!(test-path $Args[0])) {
Write-Host "Unable To Location Files, Please Check Again."
$args[0] = Read-Host "Enter Valid Path"
}
}

$ComputersPath = "missingfile.txt"

$ComputersPath
CheckPath $ComputersPath
$ComputersPath

我的结果
PS Z:\Powershell Scripting\Test Lab> .\TestFunction.ps1
missingfile.txt
Unable To Location Files, Please Check Again.
Enter Valid Path: log.txt
missingfile.txt
PS Z:\Powershell Scripting\Test Lab>

最佳答案

尝试将变量传递给这样的函数:

CheckPath $ComputersPath

Powershell将单引号中的 $视为文字“美元符号”,而不是变量限定符

并更改这些行:
$args[0] = Read-Host "Enter Valid Path"
CheckPath


CheckPath (Read-Host "Enter Valid Path")

编辑:

试试这个:
Function CheckPath {    
IF (!$args[0]) {
Write-Host
Write-Host "Variable Undefined"
$args[0] = Read-Host "Enter Valid Path"
}
else
{
"Found"
$global:ComputersPath = $args[0]
}

IF (!(Test-Path ($Args[0]))) {
Write-Host
Write-Host "Unable To Location Files, Please Check Again."
CheckPath (Read-Host "Enter Valid Path")
}

}

编辑:

要设置您在函数中使用的任何变量,我举一个例子:
function test 
{
$myvar = $MyInvocation.line.split(' ')[1].replace('$','')
"`$$myvar value now is $($args[0])"

Invoke-Expression "`$global:$myvar = 'yahoo'"

"{0} value now is {1}" -f "`$$myvar", (invoke-expression "`$$myvar")
}

在您可以尝试以下方法之后:
PS C:\ps> $a="google" #or whatever variable you want...
PS C:\ps> test $a
$a value now is google
$a value now is yahoo
PS C:\ps> $a
yahoo

现在,您可以在此函数中使用代码,并根据目标逻辑输入 CheckPath function

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

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