PowerShell: Pass local variable to function -
i have following powershell code:
function readconfigdata { $workingdir = (get-location).path $file = "" if ($global:use_local_server) { $file = $workingdir + '\configs\localhost.ini' } else { $file = $workingdir + '\configs\' + $env:computername + '.ini' } write-host 'inifile: ' $file if (!$file -or ($file = "")) { throw [system.exception] "ini fil är inte satt." } if (!(test-path -path $file)) { throw [system.exception] "kan inte hitta ini fil." } } readconfigdata
how should declare local variable $file
can passed function test-path
. local variable $file populated when place argument other function it's out of scope.
i read about scopes article wasn't able figure out.
currently error:
inifile: d:\projects\scripts\configs\hbox.ini test-path : cannot bind argument parameter 'path' because empty string. @ d:\projects\freelancer.com\nero2000\cmd script powershell\script.ps1:141 char:27 + if (!(test-path -path $file)) + ~~~~~ + categoryinfo : invaliddata: (:) [test-path], parameterbindingvalidationexception + fullyqualifiederrorid : parameterargumentvalidationerroremptystringnotallowed,microsoft.powershell.commands.testpathcommand
if (!$file -or ($file = ""))
should replaced by
if (!$file -or ($file -eq ""))
you assign $file empty string in first if clause , therefore variable empty in test-path call.
edit: there alternatives: how can check if string null or empty in powershell?
you either use
if([string]::isnullorempty($file))
or just
if(!$file)
Comments
Post a Comment