[Question] New-Item cmdlet

rated by 0 users
This post has 3 Replies | 0 Followers

Top 50 Contributor
Posts 60
Swatto Posted: 04-19-2012 12:44 PM

Hi,

I wrote a tiny script to iterate through folders and create a txt file within them folders but this doesn't work:

# Iterate through folders and create txt file

$location = Get-ChildItem -Path '\\path\to\directory'

ForEach ($folder in $location)
{
    New-Item -Path "\\path\to\directory\$folder" -ItemType file "IgnoreArchiveBitTrigger.txt"
    }

and I am a little confused about why it doesn't - I get an error about not being able to assign "IgnoreArchiveBitTrigger.txt" to a parameter.

Instead I have to write the script like this (which works):

# Iterate through folders and create txt file

$location = Get-ChildItem -Path '\\path\to\directory'

ForEach ($folder in $location)
{
    New-Item -ItemType file "\\path\to\directory\$folder\IgnoreArchiveBitTrigger.txt"
    }

Just wondering if you can explain to me why my other script above doesn't work - it has been driving me nuts.

ThankyoumSmile

Top 10 Contributor
Posts 640

You're treating $folder as if it were just a folder name (like C:\Windows), but it isn't. It's an entire Folder object. Rather than using $folder, you probably want to use something like $folder.Name.

Likewise, $location isn't a folder - it's a collection of Folder objects.

Inside your ForEach loop, add:

$folder | gm

And you'll see what $folder actually contains. Right now, what's working is only working because PowerShell's doing some finagling under the hood for you. It's a bad idea to rely on that - it'd be better to explicitly tell it what part of $folder to use.

Also, you need to provide a parameter name for all of your parameters. You've got -Path and -ItemType, but I suspect you meant to put "-Name "IgnoreArchiveBitTrigger.txt". Because you're just putting that value there, PowerShell is trying to assign the value to a parameter positionally, and there's nothing that makes sense for that.

It works the second time, I'm guessing, because you've put the value in the second position, and PowerShell knows what to do with that. If you'd use parameter names for every parameter, it'd work regardless.

Top 50 Contributor
Posts 60

Thankyou very much Don, that makes alot more sense now - your right, i was treating $folder as if it was a folder name instead of an object with multiple properties (am I right in thinking everything in powershell is an object?) I see it is definitely worth using get-member to see what an object contains. Smile

Top 10 Contributor
Posts 640

Yup, EVERYTHING - even a simple String - is an object.

Page 1 of 1 (4 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.