我正在尝试制作一个脚本,该脚本具有比较整齐的布局功能,可以比较两个文件夹项目。该程序:
作为测试,我一直在比较同一文件夹与其自身(输出应该为false,false)。当将步骤1(
$referencepath
)设为函数(FolderPrompt
)时,我的程序无法正常运行,这意味着我几乎每次运行它都会得到不同的答案。这有效:
$referencePath = Read-Host -Prompt "Enter new DTNA folder path to check"
NameDisc
SizeDisc
function NameDisc {
write-host "Name Discrepancy: " -NoNewline
if (Compare-Object -Property name (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
{return $true}
else
{return $false}
}
function SizeDisc {
write-host "Size Discrepancy: " -NoNewline
if (Compare-Object -Property length (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
{return $true}
else
{return $false}
}
但这不是:
FolderPrompt
NameDisc
SizeDisc
function FolderPrompt {
$referencePath = Read-Host -Prompt "Enter new DTNA folder path to check"
}
function NameDisc {
write-host "Name Discrepancy: " -NoNewline
if (Compare-Object -Property name (Get-ChildItem $referencePath) -DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
{return $true}
else
{return $false}
}
function SizeDisc {
write-host "Size Discrepancy: " -NoNewline
if (Compare-Object -Property length (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
{return $true}
else
{return $false}
}
,我尝试过:
$referencePath = 0
重置值认为这是问题
Return $referencePath
放在不同函数的末尾我最好的猜测是,我需要执行类似
function <name> ($referencePath)
的操作来传递变量(?)。 最佳答案
一旦将$referencepath
分配给该函数,它就会成为该函数的本地变量,因此它的值会丢失,因为您不返回它。您说您尝试过在“各种函数”中返回它,但尚不清楚它是什么样的。
您也不应依赖从其父作用域继承变量的函数。理想情况下,您将传递任何需要的信息作为参数。
在PowerShell中调用函数时,请勿在参数中使用括号和逗号,而应使用空格。
function FolderPrompt {
Read-Host -Prompt "Enter new DTNA folder path to check"
}
function NameDisc {
param($referencePath)
write-host "Name Discrepancy: " -NoNewline
if (Compare-Object -Property name (Get-ChildItem $referencePath) -DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
{return $true}
else
{return $false}
}
function SizeDisc {
param($referencePath)
write-host "Size Discrepancy: " -NoNewline
if (Compare-Object -Property length (Get-ChildItem $referencePath) - DifferenceObject (Get-ChildItem P:\DTNA_201805081923))
{return $true}
else
{return $false}
}
$refPath = FolderPrompt
NameDisc -referencePath $refPath
SizeDisc -referencePath $refPath
这就是修改后的代码的外观。
关于function - Powershell:为什么此功能不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50517567/