Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Potato Salad
Oct 23, 2014

nobody cares


NPR Journalizard posted:

Im trying to use the PowerBI cmdlet to do a survey of the datasets in my tenant. I can get a list of datasets fairly easily with Get-PowerBIDataset, but I also want to get a list of what tables each dataset uses. Supposedly Get-PowerBITable does this, but no matter what parameters I pass, or what login I use, including a service admin account, I cant get anything out of it other than an error message saying not found.

Have tried searching the web for this but cant really find an answer from a reliable source, other than one post on the community forums that I hope is wrong.

out of curiosity, are you the owner proper of any of these datasets?

Adbot
ADBOT LOVES YOU

NPR Journalizard
Feb 14, 2008

Yeah

I originally got the first step done over the while tenant, and then decided to try and only get the tables from My Workspace so I didn't screw too much with the whole system.

Even putting in specific datasetid and workspaceids came back with a not found error

Toshimo
Aug 23, 2012

He's outta line...

But he's right!
Losing my drat mind on this one. Got a bunch of folders I was looking to zip up (and I'll wind up doing with 7zip because this isn't working).

Reduced it to the very basic level (I've tried a dozen flavors of this):
PowerShell code:
gci  . | ForEach-Object -Process { Compress-Archive $_ $_ -Verbose }
The first instance of $_ just returns (or is interpreted as) nothing. Second one is fine.

Output:

VERBOSE: Preparing to compress...
VERBOSE: Performing the operation "Compress-Archive" on target "".
VERBOSE: The partially created archive file 'v:\Marvel\Alias\Alias - 022 [2003].zip' is deleted as it is not usable.
VERBOSE: The archive file path 'v:\Marvel\Alias\Alias - 023 [2003]' supplied to the DestinationPath patameter does not include .zip extension. Hence .zip is appended to the supplied DestinationPath path and the archive file would be created at 'v:\Marvel\Alias\Alias - 023 [2003].zip'.

Mario
Oct 29, 2006
It's-a-me!

Toshimo posted:

Losing my drat mind on this one. Got a bunch of folders I was looking to zip up (and I'll wind up doing with 7zip because this isn't working).

Reduced it to the very basic level (I've tried a dozen flavors of this):
PowerShell code:
gci  . | ForEach-Object -Process { Compress-Archive $_ $_ -Verbose }
The first instance of $_ just returns (or is interpreted as) nothing. Second one is fine.

Output:

VERBOSE: Preparing to compress...
VERBOSE: Performing the operation "Compress-Archive" on target "".
VERBOSE: The partially created archive file 'v:\Marvel\Alias\Alias - 022 [2003].zip' is deleted as it is not usable.
VERBOSE: The archive file path 'v:\Marvel\Alias\Alias - 023 [2003]' supplied to the DestinationPath patameter does not include .zip extension. Hence .zip is appended to the supplied DestinationPath path and the archive file would be created at 'v:\Marvel\Alias\Alias - 023 [2003].zip'.


It's the square brackets -- use LiteralPath instead of Path:
PowerShell code:
Get-ChildItem -Path . -Directory | ForEach-Object -Process { Compress-Archive -LiteralPath $_ -DestinationPath $_ -Verbose }
https://superuser.com/questions/212808/powershell-bug-in-copy-move-rename-when-filename-contains-square-bracket-charac

Also added -Directory to the Get-ChildItem so that it doesn't match the (newly created) zip files.

Toshimo
Aug 23, 2012

He's outta line...

But he's right!

Mario posted:

It's the square brackets -- use LiteralPath instead of Path:
PowerShell code:
Get-ChildItem -Path . -Directory | ForEach-Object -Process { Compress-Archive -LiteralPath $_ -DestinationPath $_ -Verbose }
https://superuser.com/questions/212808/powershell-bug-in-copy-move-rename-when-filename-contains-square-bracket-charac

Also added -Directory to the Get-ChildItem so that it doesn't match the (newly created) zip files.

Thanks, bud. Now, if only they hadn't hard-coded Compress-Archive to require a .zip extension.

kumba
Nov 8, 2003

I posted my food for USPOL Thanksgiving!

enjoy the ride

Lipstick Apathy
Performance improvement question:

I'm a SQL guy that is starting to dabble in powershell and I have a script that works but is unbelievably slow and I'm hoping for some pointers because some of this is obviously not well-constructed

Goal: I have a huge slew of .html files on a network drive buried in subfolders upon subfolders - each individual file is the result of a chat conversation between an existing/potential customer and the agent handling the chat. I want to extract the contents of these html files, remove all the bullshit/extraneous html nonsense, and be left with a list of english words that I can use to generate a simple word cloud to get an idea of the most common types of questions, objections, etc that we're facing

This is what I have so far:

code:
#Create empty txt file
Set-Content -Path C:\temp\chats\test.txt ""
#Get all .html files in all subfolders that have to do with Chat - Unfortunately doing a string search is my only reliable way to identify these from the other items in these folders
Get-ChildItem -Path Z:\ -Include "*_CS Chat_*.html" -File -Recurse | ForEach-Object {
    $contents = Get-Content -Path $_.FullName.ToString() 
    $arrayToParse = $contents.Split(' ')
    $newArray = @()
#There's gotta be a better way to do this than this a of exclusions, right?
    $exclusions = @('number','number?','number.','number,','chatting','contacting','account','account.','account?','account,','please','thank','display:','.attachmentIcon','inline-block;','background-size:','background-image:','styleheadbodybCampaign','width:','height:','16px;')
    foreach($word in $arrayToParse) 
    {
#There are also *shudder* pdfs embedded in some of these .html files so I need to remove huge strings of alphanumeric characters, hence the length limitation, among other things
        if(($word.Length -gt 30) -and ($word.Length -gt 0) -and (-not $word.Contains("https")) -and (-not $word.Contains("Omni")) -and (-not $word.Contains("<")) -and (-not $word.Contains(">")))
            {
            if ($word -in $exclusions)
                {
                #Write-Host "Skipping " $word
                }
            else    
                {
                #Write-Host $word
                $word = $word -replace '[\W]',''
                $newArray = $newArray +=$word
                }
            }
    }
    Add-Content -Path C:\temp\chats\test.txt -Value $newArray
}
My primary question has to do with the filtering of text. There's a large amount of bullshit formatting in these documents that I need to strip out to make sense of it and the above was my way of brute forcing it after running it and identifying things that needed removing. Surely there must be a better way to do this??

My first immediate thought is doing the regex first before comparing to the $exclusions array so I can at least get rid of the silly duplicates with formatting but I'm not sure where to go from there. Any pointers would be super appreciated :)

e: i guess also most of the delay is probably from it being several gigs of data on a network drive instead of on my local machine so any performance improvement will probably be limited

kumba fucked around with this message at 18:58 on Nov 16, 2022

Mario
Oct 29, 2006
It's-a-me!
I'd really want to use a library to deal with the HTML garbage -- e.g. HTML Agility Pack. Remember that PowerShell is .NET Framework or Core (depending on version), so there are lots of helper libraries out there.

Toshimo
Aug 23, 2012

He's outta line...

But he's right!

kumba posted:

Performance improvement question:

There's a lot to unpack here, but (a) as mentioned, HTML parsing is generally better done a different way, but if you want to do it this sort of way (b) avoid arrays and definitely avoid using "+=" to add things to arrays because it's a massive performance hit.

There's probably a lot of ways that others will find to improve this, but here's a first pass (it's not going to give you all your pretty host output:

PowerShell code:
[psobject]$exclusions = @('number','number?','number.','number,','chatting','contacting','account','account.','account?','account,','please','thank','display:','.attachmentIcon','inline-block;','background-size:','background-image:','styleheadbodybCampaign','width:','height:','16px;')
Get-ChildItem -Path Z:\ -Include "*_CS Chat_*.html" -File -Recurse | ForEach-Object {
    (Get-Content -Path $_.FullName.ToString()).Split(' ').Trim('.',"`'","`"",",") | Where-Object { ($_.Length -lt 30) -and  
                                                                        ($_.Length -gt 0) -and 
                                                                        (-not ($_ -match "[`<`>]")) -and
                                                                        (-not ($_ -match "https|Omni")) -and
                                                                        (-not ($_ -in $exclusions))
                                                         }  
    } | ForEach-Object { $_ -replace '[\W]','' } | Set-Content -Path C:\temp\output.txt
Let me know if that's at least a little faster/more accurate.

Toshimo fucked around with this message at 22:12 on Nov 16, 2022

Toshimo
Aug 23, 2012

He's outta line...

But he's right!
If you want to skip ahead and just group up your words and count them so you can just feed that into something else, go with the following for your last line:

PowerShell code:
    } | ForEach-Object { $_ -replace '[\W]','' } | Group-Object | Select-Object Name,Count | Sort-Object Name | Set-Content -Path C:\temp\output.txt

kumba
Nov 8, 2003

I posted my food for USPOL Thanksgiving!

enjoy the ride

Lipstick Apathy
Thank you all for the suggestions!!

I posted it more as a learning exercise because this is one of those things I only really needed to use once and while it took an hour to run, my feeble script got the job done :D

I appreciate the feedback and have learned a bunch already!!

nielsm
Jun 1, 2009



I'm working on a module to provide an interface for calling a webservice and do batch changes to some data.
However, this webservice has some annoying rate limits, but does support batching multiple operations into a single request. So if I can batch my changes, I can work through any data much faster.

Do anyone know of tools or techniques to split a pipeline of individual objects in PowerShell into blocks of some size, say 20 or 100 objects per block, and then process them per block instead of individually?

The Fool
Oct 16, 2003


the naive way to do it would be to increment a marker variable while iterating through your list of items

when that marker variable hits your intended batch size, send it, then reset and repeat until you finish your list

I can throw up an example in a little bit

There are more clever ways to do batching, but this will do what you need

The Claptain
May 11, 2014

Grimey Drawer
Hello Goons, I have two problems I'd appreciate some input on.

First: I am tracking some stuff related to weekly releases via Azure App Config feature flags. Feature flags are in a format of $environmentName-$releaseVersion, where releaseVersion is a string of format YYYY-WW, so for example this week's one would be 2023-14. I would like to delete the feature flags older than 5 releases.

That format is something that is easy to construct from get-date cmdlet, as the get-date -UFormat %V will give the week number, and (get-date).year will return the, uhh, year. But converting that string to something that can be compared to date-time object escapes me. Looking at the docs for DateTime struct, it is read-only, so I cannot just construct it at will. So how do I go by comparing two strings that represent YYYY-WW format? Comparing weeks is easy enough, but I have no idea how to handle year rollovers on subtraction/addition.

Second: This one is possibly more Azure related than powershell, but here it goes. I have a custom class which needs to represent app service. It has properties name, which is a string, and SKU, which is Microsoft.Azure.Management.WebSites.Models.SkuDescription. I thought it would be easier to use that type, as then I could more easily compare the SKU on my object with what I get from Get-AzAppServicePlan, and boy was I wrong. When I try running the script, I get the Unable to find type Microsoft.Azure.Management.WebSites.Models.SkuDescription. I have "using namespace Microsoft.Azure.Management.WebSites.Models" at the beginning of the script( according to the documentation, that is what the namespace's called, but I tried Microsoft.Azure.Management.WebSites as well, and I am importing Az.Websites module, but the error is still happening. I only get access to the class if I run any command from Az.Websites modules, but since this is supposed to be an Azure runbook, that's not going to work. This one is driving me crazy so much that I decided to:
a) gently caress Azure.Management assemblies and namespaces, It is less effort to write a custom class for SKU
b) gently caress Az powershell modules and their inconsistencies, I should probably rewrite this to use REST API and use an Azure function instead of the runbook

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

The Claptain posted:

Hello Goons, I have two problems I'd appreciate some input on.

First: I am tracking some stuff related to weekly releases via Azure App Config feature flags. Feature flags are in a format of $environmentName-$releaseVersion, where releaseVersion is a string of format YYYY-WW, so for example this week's one would be 2023-14. I would like to delete the feature flags older than 5 releases.

That format is something that is easy to construct from get-date cmdlet, as the get-date -UFormat %V will give the week number, and (get-date).year will return the, uhh, year. But converting that string to something that can be compared to date-time object escapes me. Looking at the docs for DateTime struct, it is read-only, so I cannot just construct it at will. So how do I go by comparing two strings that represent YYYY-WW format? Comparing weeks is easy enough, but I have no idea how to handle year rollovers on subtraction/addition.

you say that you want to keep the last 5, not keep them based on some property of the dates themselves; and they are in YYYY-WW format. so why not just compare the strings? you don't need to turn them into dates to do what you describe. they will compare the correct way lexicographically

The Claptain
May 11, 2014

Grimey Drawer

Hammerite posted:

you say that you want to keep the last 5, not keep them based on some property of the dates themselves; and they are in YYYY-WW format. so why not just compare the strings? you don't need to turn them into dates to do what you describe. they will compare the correct way lexicographically

I totally forgot you could do that. It works perfectly, and I was way overthinking it.
Thanks!

e: the main reason I was thinking about the dates is because that way it would be easy to subtract five weeks and than do comparisons, but I can work around that.

The Claptain fucked around with this message at 12:10 on Apr 3, 2023

Necrobama
Aug 4, 2006

by the sex ghost
Forgive me, this is probably pretty basic stuff, but my experience with PS mostly boils down to "someone made this script to grab a bunch of database tables and throw them in a series of CSV files" which has served me well under the conditions that I'm using a trusted connection and not directly supplying credentials to the database server (ex loading a .bak into my local instance of SSMS and spitting out all 700 tables into CSV files).

In working on something I came across a bit of SQL script that was generating PS commands and...they included plaintext storage of the username and password of the user who was going to run the SQL and PS code because for whatever reason, these servers aren't using trusted auth.

code:
bcp "Select [##SOME_COLUMN_NAMES##] from [##DB##].[dbo].##TableName## order by k1" queryout "C:\Path\To\File.csv" -U ##Username## -P ##Password##  -S ##ServerName## -c -t','
This works fine. It works exactly as expected - but I have a problem with it because the comments of course say NOT to save your credentials when you push the to the repo but I don't like leaving it up to chance.

I've messed around a bit with what I can find through google searches, and come up with an almost ideal solution:

code:
[string]$pwd = read-host -Prompt "Password"
and

code:
bcp "Select [##SOME_COLUMN_NAMES##] from [##DB##].[dbo].##TableName## order by k1" queryout "C:\Path\To\File.csv" -U ##Username## -P $pwd  -S ##ServerName## -c -t','
work fine. It's ok - but what's making me absolutely bonkers is that I can't use -AsSecureString for $pwd because when I feed the variable into the -P argument, I get the message back that authentication has failed.

I'll admit I might be suffering from google exhaustion and this may be an incredibly easy thing to figure out for you all but...I'm at my wit's end!

The Fool
Oct 16, 2003


Secure strings are their own object type and you can read it from the user using Get-Credential

Pile Of Garbage
May 28, 2007



Necrobama posted:

what's making me absolutely bonkers is that I can't use -AsSecureString for $pwd because when I feed the variable into the -P argument, I get the message back that authentication has failed.

The primary difference between the String class and the SecureString class is that the latter overloads the ToString() method so that instead of returning the value of the string it instead returns the name of the class:

code:
PS C:\> $String = Read-Host -Prompt 'String'
String: test
PS C:\> $String.ToString()
test
code:
PS C:\> $SecureString = Read-Host -Prompt 'SecureString' -AsSecureString
SecureString: ****
PS C:\> $SecureString.ToString()
System.Security.SecureString
That is why authentication is failing, because the actual value of the SecureString isn't being returned.

Realistically there's no advantage to using SecureString other than it making it slightly more difficult to get the object's value. The contents of the object are not encrypted in memory so it's not really secure at all. In fact Microsoft are discouraging people from using it altogether: https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md.

Also here's some further reading about the SecureString class: https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring?view=net-7.0#remarks

Pile Of Garbage fucked around with this message at 09:44 on Apr 22, 2023

mllaneza
Apr 28, 2007

Veteran, Bermuda Triangle Expeditionary Force, 1993-1952




For a lot of things you can do with PowerShell, you can just RunAs the terminal window. User context matters a lot in Windows, make it work for you if you can.

nielsm
Jun 1, 2009



Yes if you can, connecting to MS SQL Server with Integrated Authentication is often the easiest and most secure. Then you just need your process to run under the appropriate user token, such as a service or batch job account, or you can use Run As to start as another user.

Necrobama
Aug 4, 2006

by the sex ghost
Our product version 7 databases use Windows authentication. Our product version 8 databases use credential authentication.

:shrug:

Thanks for the tips!

Boywhiz88
Sep 11, 2005

floating 26" off da ground. BURR!
Hello! I’m a total loving idiot who last programmed 20 years ago!

But! I’ve been exposed to enough powershell scripts at my job that I want to get elbow deep.

Right now, I’m trying to develop a script that will take a username, check against the first two characters, and then create a folder, modify its permissions, create a sub folder and then modify that subfolder’s inherited permissions.

Like I said, total idiot with no experience. So I’m trying to construct this step by step

I’ve started by defining $username via a Read-Host prompt. After which, a Switch command runs.

Depending on the first two characters, I want it to set a location, check against if a folder with $username exists already, and then create the folder if it doesn’t.

The switch is set for wildcard, and checks against those first two characters, it displays an acknowledgement and then runs the set location, followed by a test-path -path $username, then the NewItem command. I was going to have these be a per entry option for set-location.

I’m mostly checking to see if I’m on the right path or if I should be looking into a different function than switch, and if trying to change commands per input is the best path.

Thank you!

Submarine Sandpaper
May 27, 2007


ACLs sorta suck unless they've changed things in PowerShell. Last I did it I needed to be a local file system admin and you needed to pull the acl, modify it, then set via a method. Local admin maybe a lie but I thought i needed it for some reason. You may be best set by using old cmd liners and invoking them on a directory.

Toshimo
Aug 23, 2012

He's outta line...

But he's right!
It's a maybe. You probably don't need Set-Location at all, but it doesn't hurt.

What are you doing with the switch, exactly? Like, what does checking the first 2 characters do?

It would probably be rasiest if you just gave us a dummy name like "JDoe" and said like:

  1. Creates R:\JDoe
  2. Sets JDoe to have Full Control of R;\JDoe
  3. Creates R:\JDoe\Public
  4. Sets Authenticated Users to have Full Control on R:\JDoe\Public

Or whatever you are doing

Toshimo
Aug 23, 2012

He's outta line...

But he's right!

Submarine Sandpaper posted:

ACLs sorta suck unless they've changed things in PowerShell.

They kinda did but they still suck and I'll dig out what I used last time but I think I was still calling .Net methods

Boywhiz88
Sep 11, 2005

floating 26" off da ground. BURR!

Toshimo posted:

It's a maybe. You probably don't need Set-Location at all, but it doesn't hurt.

What are you doing with the switch, exactly? Like, what does checking the first 2 characters do?

It would probably be rasiest if you just gave us a dummy name like "JDoe" and said like:

  1. Creates R:\JDoe
  2. Sets JDoe to have Full Control of R;\JDoe
  3. Creates R:\JDoe\Public
  4. Sets Authenticated Users to have Full Control on R:\JDoe\Public

Or whatever you are doing

For sure!

So the input is

$username = Read-Host -Prompt 'Provide username'
switch -wildcard ($username)

The first two letters correspond w/ the office. so AZJOND for an Arizona user, for example.

It sees the AZ* then it literally goes "This is an Arizona user"; $path = "C:\Test\AZ\$username'; test-path -path $path -isvalid; set-location 'C:\Test\AZ': New-Item -Itemtype directory -path $username

The bold part is what I've been working on tonight. I want to be sure to validate the location ahead of time to avoid issues of overwriting, etc.

I've thought about maybe that the Test-Path occurs as part of the switch, which would then move forward if it's "False" and then break out into a standard script that would use a $path defined within the switch as well.

So it would look like This is an Arizona user, $path = " "; test-path -path $path -isvalid"

New-Item -ItemType Directory -path $path

THEN into the more standardized subfolders and permissions actions.

I also am not expecting anyone to do my homework, so if you would want to guide me towards certain cmdlets or concepts to look into, I'm down. I think I am doing ok with the logic of how I want things to work, but just working on syntax and understanding how variables, etc are referenced.

Edit: Re-reading the documentation and realizing isvalid doesn't do what i think it does haha. oops.

Boywhiz88 fucked around with this message at 03:06 on May 25, 2023

Inspector_666
Oct 7, 2003

benny with the good hair
I think the easiest thing would be to just use the Test-Path part in a simple if statement in the directory creation segment of the script rather than trying to integrate it into the switch.

Toshimo
Aug 23, 2012

He's outta line...

But he's right!
The way you've described it, you want something like this:

PowerShell code:
$username = Read-Host -Prompt 'Provide username'
$office_code = $username.Substring(0,2)
$user_path = "C:\Test\$office_code\$username"

if( -not (Test-Path -Path $user_path)) {
    New-Item -Itemtype Directory -Path $user_path
} else {
    Write-Output "Collision detected at path `"$user_path`""
}

Pile Of Garbage
May 28, 2007



Probably posted this before but I highly recommend specifying the PathType parameter whenever you're using Test-Path: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/test-path?view=powershell-5.1#-pathtype.

It's a minor thing for a probably unlikely edge-case but it can easily help to avoid confusion and issues when you put your things into prod.

Toshimo
Aug 23, 2012

He's outta line...

But he's right!

Pile Of Garbage posted:

Probably posted this before but I highly recommend specifying the PathType parameter whenever you're using Test-Path: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/test-path?view=powershell-5.1#-pathtype.

It's a minor thing for a probably unlikely edge-case but it can easily help to avoid confusion and issues when you put your things into prod.

True, but most of the time, I don't bother because I'd set it to Any because of how many compatibility issues I have if a file and a folder with the same name exist, so I just bail on either.

Pile Of Garbage
May 28, 2007



Toshimo posted:

True, but most of the time, I don't bother because I'd set it to Any because of how many compatibility issues I have if a file and a folder with the same name exist, so I just bail on either.

Genuinely interested, what environment are you in where that is a compatibility issue? Windows and POSIX has no issues with files and folders having the same name, what monstrosity are you using which doesn't?

Toshimo
Aug 23, 2012

He's outta line...

But he's right!

Pile Of Garbage posted:

Genuinely interested, what environment are you in where that is a compatibility issue? Windows and POSIX has no issues with files and folders having the same name, what monstrosity are you using which doesn't?

Oh, it's always some in-house piece of poo poo or something from a garbage mom-and-pop vendor who didn't account for it.

Pile Of Garbage
May 28, 2007



Toshimo posted:

Oh, it's always some in-house piece of poo poo or something from a garbage mom-and-pop vendor who didn't account for it.

Guessing you work for an MSP, unless you consider say Atlassian or SAP to be mom-and-pops lol. Whether you're uplifting existing code or integrating with legacy code it's still beneficial to use strict path checking with the PathType parameter. Pro-tip: you can use Test-Path in ValidateScript statements. See also: the Uri class that you can use to vaidate URIs to make sure they're well-formed. https://learn.microsoft.com/en-us/dotnet/api/system.uri?view=net-7.0

Toshimo
Aug 23, 2012

He's outta line...

But he's right!

Pile Of Garbage posted:

Guessing you work for an MSP, unless you consider say Atlassian or SAP to be mom-and-pops lol. Whether you're uplifting existing code or integrating with legacy code it's still beneficial to use strict path checking with the PathType parameter. Pro-tip: you can use Test-Path in ValidateScript statements. See also: the Uri class that you can use to vaidate URIs to make sure they're well-formed. https://learn.microsoft.com/en-us/dotnet/api/system.uri?view=net-7.0

No, I work for a monolithic agency in the US Feddral Government.

Pile Of Garbage
May 28, 2007



My condolences.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Pile Of Garbage posted:

Genuinely interested, what environment are you in where that is a compatibility issue? Windows and POSIX has no issues with files and folders having the same name, what monstrosity are you using which doesn't?

??????

Only registered members can see post attachments!

Pile Of Garbage
May 28, 2007



lmao you're right I'm dumb as poo poo! I've no idea why I thought that was allowed.

Pile Of Garbage
May 28, 2007



I still think it's worth using the PathType parameter but I also apologise to Hammerite and Toshimo and the rest of the thread because I clearly hosed up and clowned myself big time.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
Being mistaken happens to the best of us.

Yes I think I would agree and generalise what you're saying as: it is useful to keep in mind the need to be aware whether you're testing for existence of files, directories, or both. One reason is to want to know whether a filesystem object is created and is specifically a directory, so (ignoring security for the moment) you would expect to be able to create things inside it. I'm more likely to be writing C# than Powershell code, and using Directory.Exists() or File.Exists(). But there too I might want to check both, to avoid leaving the silly edge case where I test whether a directory existed, and it didn't, but the program will still blow up when I try to create the directory because a file existed with that name.

Adbot
ADBOT LOVES YOU

Volguus
Mar 3, 2009

Hammerite posted:

Being mistaken happens to the best of us.

Yes I think I would agree and generalise what you're saying as: it is useful to keep in mind the need to be aware whether you're testing for existence of files, directories, or both. One reason is to want to know whether a filesystem object is created and is specifically a directory, so (ignoring security for the moment) you would expect to be able to create things inside it. I'm more likely to be writing C# than Powershell code, and using Directory.Exists() or File.Exists(). But there too I might want to check both, to avoid leaving the silly edge case where I test whether a directory existed, and it didn't, but the program will still blow up when I try to create the directory because a file existed with that name.

The program can blow up when trying to create a file or directory for a ton of reasons, some of them related to security, some of them not (write to a file and the disk is full, for example).

You should always expect that to happen when doing I/O and take precautions ( at least a try/catch with some readable message).

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply