Sign in to follow this  
Followers 0
haze1434

[PowerShell] Require assistance with split variables and null array error

3 posts in this topic

Posted (edited)

Hi guys,

 

I have the following PowerShell code;

$FolderPath = "\\server\folder1\folder2\~folder3"

$SplitFolder = $FolderPath -split '\\'

 

I can then echo each split using;

echo $SplitFolder[2]
server
echo $SplitFolder[3]
folder1
echo $SplitFolder[4]
folder2

 

but when I get to echo $SplitFolder[5], because the folder name begins with a tilde (~), it fails;

echo $SplitFolder[5]


Cannot index into a null array.
At line:1 char:1
+ echo $SplitFolder[5]
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

 

Any ideas why the -split fails to set the variable correctly, for the folder beginning with a tilde?

 

Please note that I am planning on making the folder path an input from the user, so they may put in any path. Therefore, I cannot simply escape the one character, as it will be different each time.

 

Thank you.

Edited by haze1434
0

Share this post


Link to post
Share on other sites

That looks very odd to me, as when I try it in powershell it works fine.

PS > $folderPath="\\server\folder1\folder2\~folder3"
PS > $splitFolder = $folderPath -split '\\'

PS > echo $splitFolder[2]
server

PS > echo $splitFolder[3]
folder1

PS > echo $splitFolder[4]
folder2

PS > echo $splitFolder[5]
~folder3

In fact if I ask for an array index that doesn't exist I still don't get the error

PS > echo $splitFolder[6]
PS >

I can get the same error you get by misspelling the variable name (e.g. by dropping the 'e' in folder)

PS > echo $splitFoldr[6]
Cannot index into a null array.
At line:1 char:1
+ echo $splitFoldr[6]
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

I'd suggest check the spelling (though I can't see any difference in your example) and trying again.

1

Share this post


Link to post
Share on other sites
1 hour ago, Jason Cooper said:

I can get the same error you get by misspelling the variable name.

Bingo.

Doh!

Thanks :)

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Recently Browsing   0 members

    No registered users viewing this page.