新项目扰乱了我的变量PowerShell



我写了一个非常简单的脚本来获取一个随机的免费驱动器号。该函数查找一个随机的空闲字母,创建一个具有该驱动器号名称的新的空文本文件,例如Q.txt然后,我将值返回为$new_letter,但当它从函数中出来时,不知何故,新创建的文件路径是变量C:AppPackLogsQ.txt Q的一部分

New-Item把我的$new_letter变量搞砸了吗?


function get_drive_letter()
{
$letter_acquired = $false
Do
{
$new_letter = Get-ChildItem function:[h-z]: -Name | ForEach-Object { if (!(Test-Path $_)){$_} } | random -Count 1 | ForEach-Object {$_ -replace ':$', ''}
write-host ("RIGHT AFTER " + $new_letter)
if (!(test-path "C:AppPackLogs$new_letter.txt"))
{    
New-Item -Path C:AppPackLogs -Name "$new_letter.txt" -ItemType "file" 
write-host ("FROM FUNCTION " + $new_letter)
$letter_acquired = $true
return $new_letter
}


else
{
write-host ("LETTER USED ALREADY")
write-host ($new_letter)
}
}
while($letter_acquired = $false)
}
$drive_letter = $null
$drive_letter = get_drive_letter
write-host ("RIGHT AFTER FUNCTION " + $drive_letter)

输出:

RIGHT AFTER Q
FROM FUNCTION Q
RIGHT AFTER FUNCTION C:AppPackLogsQ.txt Q

PowerShell函数输出所有,而不仅仅是return之后的表达式的结果!

您看到的附加文件路径是New-Item ...的输出——它为您刚刚创建的文件返回一个FileInfo对象。

您可以通过将输出分配给特殊的$null变量来抑制输出:

# Output from New-Item will no longer "bubble up" to the caller
$null = New-Item -Path C:AppPackLogs -Name "$new_letter.txt" -ItemType "file"
return $new_letter

或通过管道连接至Out-Null:

New-Item ... |Out-Null

或者通过将整个管道铸造到[void]:

[void](New-Item ...)

尽管我建议在调用站点明确处理不需要的输出,但也可以使用提升技巧来解决此行为。

为了证明,考虑这个伪函数——假设我们";inherit";它来自一位同事,他并不总是编写最直观的代码:

function Get-RandomSquare {
"unwanted noise"
$randomValue = 1..100 |Get-Random
"more noise"
$square = $randomValue * $randomValue
return $square
}

上面的函数将输出3个对象——两个垃圾字符串一个接一个,然后是我们真正感兴趣的结果:

PS ~> $result = Get-RandomSquare
PS ~> $result
unwanted noise
more noise
6400

假设我们被告知要尽可能少地进行修改,但我们确实需要抑制垃圾输出。

要做到这一点,请将整个函数体嵌套在一个新的脚本块文本中,然后使用点源运算符(.(调用整个块-这将迫使PowerShell在函数的本地范围中执行它,这意味着任何变量分配都将持续:

function Get-RandomSquare {
# suppress all pipeline output
$null = . {
"unwanted noise"
$randomValue = 1..100 |Get-Random 
"more noise"
$square = $randomValue
return $square
}
# variables assigned in the block are still available
return $square
}

最新更新