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
Toast Museum
Dec 3, 2005

30% Iron Chef
Powershell 7 Release Candidate is out

Adbot
ADBOT LOVES YOU

Cold on a Cob
Feb 6, 2006

i've seen so much, i'm going blind
and i'm brain dead virtually

College Slice
Is there a way to set the DateTime properties of a symlink (i.e. NOT the referenced file of one) in PowerShell? I know how to create, identify, and remove them but I can't update the properties of them. I have a feeling it's not possible, but figured I'd ask this here anyway.

CzarChasm
Mar 14, 2009

I don't like it when you're watching me eat.
I might be missing something really obvious. I'm trying to install the Exchange Powershell V2 module using directions found here: https://docs.microsoft.com/en-us/po...iew=exchange-ps

According to what I see, it says to run the following command from an elevated Powershell session (as Adminstrator)
code:
Install-Module PowershellGet -Force
When I enter that I get the following error:
Could not retrieve modules repository from 'https://github.com/psget/psget/raw/master/Directory.xml'. Status code:
At C:\windows\system32\windowspowershell\v1.0\Modules\PsGet\PsGet.psm1:519 char:13
+ throw "Could not retrieve modules repository from '$DirectoryUrl'. S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Could not retri.... Status code: :String) [], RuntimeException
+ FullyQualifiedErrorId : Could not retrieve modules repository from 'https://github.com/psget/psget/raw/master/Directory.xml'. Status code:


If I try to get it form GitHub directly I get a line to copy:
code:
Install-Module -Name ExchangeOnlineManagement
And that tells me that it can't find a match to the Name property

What am I doing wrong?

Pile Of Garbage
May 28, 2007



Cold on a Cob posted:

Is there a way to set the DateTime properties of a symlink (i.e. NOT the referenced file of one) in PowerShell? I know how to create, identify, and remove them but I can't update the properties of them. I have a feeling it's not possible, but figured I'd ask this here anyway.

No, symlinks do not have attributes and are simply designed to transparently redirect all write operations to the target path.

CzarChasm posted:

I might be missing something really obvious. I'm trying to install the Exchange Powershell V2 module using directions found here: https://docs.microsoft.com/en-us/po...iew=exchange-ps

What am I doing wrong?

What version of PowerShell are you using (Just check $PSVersionTable)?

Cold on a Cob
Feb 6, 2006

i've seen so much, i'm going blind
and i'm brain dead virtually

College Slice

Pile Of Garbage posted:

No, symlinks do not have attributes and are simply designed to transparently redirect all write operations to the target path.


They do have the attributes I'm interested in being able to change, but it appears there is no way to change them in PS - LastWriteTime for example:

code:
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
la---          2019-12-27  9:04 AM              0 bar -> foo
-a---          2019-12-26 12:00 AM              0 foo
The interesting thing is I can even modify the LastWriteTime in WSL2 using touch.

code:
$ touch -h -m -d 2020-01-01 bar
$ stat bar
  File: bar -> foo
  Size: 3               Blocks: 0          IO Block: 4096   symbolic link
Device: eh/14d  Inode: 21673573206817728  Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1000/     coac)   Gid: ( 1000/     coac)
Access: 2019-12-27 09:04:19.251413900 -0500
Modify: 2020-01-01 00:00:00.000000000 -0500
Change: 2019-12-27 09:09:53.515552700 -0500
 Birth: -
Back to powershell to see the results there as well:

code:
C:\temp> ls


    Directory: C:\temp

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
la---          2020-01-01 12:00 AM              0 bar -> foo
-a---          2019-12-26 12:00 AM              0 foo
Edit: For what it's worth C# also automatically dereferences symbolic links. I don't have a problem with the behaviour but I'd love to be able to override it somehow.

Cold on a Cob fucked around with this message at 15:21 on Dec 27, 2019

Pile Of Garbage
May 28, 2007



Well poo poo. That's pretty wild. Intuitively I would have thought NTFS symlinks would transparently redirect all writes including those to attributes. I suspect that it's possible in WSL due to the weird POSIX emulation or whatever it does. Willing to admit that I'm wrong here and not 100% sure.

mystes
May 31, 2006

I think the API for symlinks on Windows just isn't there because nobody was using them until extremely recently (because you had to be admin). You could try filing a bug, but .net would probably have to get it first before they can add it to powershell (right now it appears you have to use pinvoke and there's no native way to do it in .net).

Cold on a Cob
Feb 6, 2006

i've seen so much, i'm going blind
and i'm brain dead virtually

College Slice

Pile Of Garbage posted:

Well poo poo. That's pretty wild. Intuitively I would have thought NTFS symlinks would transparently redirect all writes including those to attributes. I suspect that it's possible in WSL due to the weird POSIX emulation or whatever it does. Willing to admit that I'm wrong here and not 100% sure.

Yeah I was worried that was the case until I tried touch with WSL2. I also did some more reading and with Win32 you actually have to dereference them manually. I'm happy C# and PS don't make us do that and it's a pretty small edge case so no big deal.

I was actually trying to fully recreate touch in PS on a lark. I guess I'll change -h to not dereference symlinks by skipping them entirely. Still better than all the touch implementations I've seen in the wild.

Pile Of Garbage
May 28, 2007



mystes posted:

I think the API for symlinks on Windows just isn't there because nobody was using them until extremely recently (because you had to be admin). You could try filing a bug, but .net would probably have to get it first before they can add it to powershell (right now it appears you have to use pinvoke and there's no native way to do it in .net).

Anecdotally I've used symlinks in the past with PowerShell by invoking mklink as an insane means of bypassing the MAX_PATH limit. It was a script meant to copy files out of garbage locations into more reasonable locations (We were ingesting files from SMB shares into a DMS, said DMS couldn't deal with an arbitrary set of characters or source-paths over MAX_PATH). Iterate through a CSV, if source path is over MAX_PATH then just nest symlinks until it isn't and then replace characters on the copy :lol:. Sounds crazy but it fuckin worked. Of course I stressed to them that it was a one-off thing and should never be used again...

Edit: it's actually surprising how quickly symlinks can be created/destroyed. My blocking logging to console of said creation/destruction actually slowed it down...

Pile Of Garbage fucked around with this message at 16:04 on Dec 27, 2019

CzarChasm
Mar 14, 2009

I don't like it when you're watching me eat.

Pile Of Garbage posted:

What version of PowerShell are you using (Just check $PSVersionTable)?

I'm on 4.0, thought I was on 5. I'll do the update to 5 after the weekend and see if that fixes it.

Inspector_666
Oct 7, 2003

benny with the good hair

CzarChasm posted:

I'm on 4.0, thought I was on 5. I'll do the update to 5 after the weekend and see if that fixes it.

Try

code:
Find-Module powershellget | Install-Module
instead of just Install-Module. I get the same error as you if I try to just use Install, but the piped command works without issue. This goes for pretty much all of the modules I need to download.

Inspector_666 fucked around with this message at 18:25 on Dec 27, 2019

Pile Of Garbage
May 28, 2007



That said the doco indicates that only v5.0/5.1 is supported so maybe just upgrade and not try to get it going on an unsupported version.

Inspector_666
Oct 7, 2003

benny with the good hair
I mean yeah, update PShell regardless, but even in 5.1 I have to use the piped command.

Secx
Mar 1, 2003


Hippopotamus retardus
I have a simple PS using HtmlAgilityPack doing web scraping. This works as expected:

code:
$doc = $WebGrabber.Load($url)

$rows = $doc.DocumentNode.SelectNodes("//table[@id='a1']//tr")

foreach ($row in $rows) {
    Write-host $row.SelectSingleNode("td")[0].innerText.replace("`r`n", " ").Trim()  
}
But as soon as I assign it to a variable, I get an error: "Cannot index into a null array"

code:
foreach ($row in $rows) {
    $medicinalIngredient = ""
    $medicinalIngredient = $row.SelectSingleNode("td")[0].innerText.replace("`r`n", " ").Trim()
}
What I'm trying to as assign should be a string. Confirmed by calling GetType:

code:
$row.SelectSingleNode("td")[0].innerText.replace("`r`n", " ").Trim().GetType().Name
#This returns "String"
If I try to do my variable assignment outside the foreach loop (i.e. via the PS terminal), it works as expected.

What stupid thing am I overlooking?

mllaneza
Apr 28, 2007

Veteran, Bermuda Triangle Expeditionary Force, 1993-1952




Pile Of Garbage posted:

Well poo poo. That's pretty wild. Intuitively I would have thought NTFS symlinks would transparently redirect all writes including those to attributes. I suspect that it's possible in WSL due to the weird POSIX emulation or whatever it does. Willing to admit that I'm wrong here and not 100% sure.

A lot of Unix commands have an absurd amount of parameters for how they should handle symlinks this time.

Pile Of Garbage
May 28, 2007



Secx posted:

I have a simple PS using HtmlAgilityPack doing web scraping. This works as expected:

code:
$doc = $WebGrabber.Load($url)

$rows = $doc.DocumentNode.SelectNodes("//table[@id='a1']//tr")

foreach ($row in $rows) {
    Write-host $row.SelectSingleNode("td")[0].innerText.replace("`r`n", " ").Trim()  
}
But as soon as I assign it to a variable, I get an error: "Cannot index into a null array"

The Cannot index into a null array error occurs when you try to use the array index selector ([0]) on a null object. e.g.

code:
PS C:\> $null[0]
Cannot index into a null array.
At line:1 char:1
+ $null[0]
+ ~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray
Looking at the doco the SelectSingleNode() method is only meant to return either a single HtmlAgilityPack.HtmlNode object or null if none are found. This means that you shouldn't need the index array selector at all and instead just need to check whether or not null was returned. Maybe something like this:

code:
foreach ($row in $rows) {
    $RowTdNode = $row.SelectSingleNode("td")

    if ($RowTdNode) {
        $medicinalIngredient = $RowTdNode.innerText.replace("`r`n", " ").Trim()
    }
}
Also you should probably remove the $medicinalIngredient = "" line as that's just going to cause unnecessary type coercion.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
Anyone ever encounter this? I'm trying to run a stored procedure on a PostgreSQL database (AWS Redshift) via PowerShell and it's giving me the weirdest error.

code:
$DBConn = New-Object System.Data.Odbc.OdbcConnection
$DBConn.ConnectionString = "Driver={PostgreSQL UNICODE(x64)};Server=*******;Database=******;Port=5439;Uid=*****;Pwd=*****"
$DBConn.Open()
$DBCmd = $DBConn.CreateCommand()
$DBCmd.CommandText = "EXEC [foo].[bar]"
$DBCmd.ExecuteNonQuery()
Error:
code:
Exception calling "ExecuteNonQuery" with "0" argument(s): "ERROR [42809] ERROR: foo.bar() is a procedure;
Error while executing the query"
At line:1 char:1
+ $DBCmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OdbcException
Yes, I know it's a procedure, I'm trying to execute it? :confused:

Nth Doctor
Sep 7, 2010

Darkrai used Dream Eater!
It's super effective!


PierreTheMime posted:

Anyone ever encounter this? I'm trying to run a stored procedure on a PostgreSQL database (AWS Redshift) via PowerShell and it's giving me the weirdest error.

code:
$DBConn = New-Object System.Data.Odbc.OdbcConnection
$DBConn.ConnectionString = "Driver={PostgreSQL UNICODE(x64)};Server=*******;Database=******;Port=5439;Uid=*****;Pwd=*****"
$DBConn.Open()
$DBCmd = $DBConn.CreateCommand()
$DBCmd.CommandText = "EXEC [foo].[bar]"
$DBCmd.ExecuteNonQuery()
Error:
code:
Exception calling "ExecuteNonQuery" with "0" argument(s): "ERROR [42809] ERROR: foo.bar() is a procedure;
Error while executing the query"
At line:1 char:1
+ $DBCmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OdbcException
Yes, I know it's a procedure, I'm trying to execute it? :confused:

Does the sproc have required parameters?
How about does it return a result set?

Both of those could be issues

E: I'm on my phone but could your command type need to be set to stored procedure or something?

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

Nth Doctor posted:

Does the sproc have required parameters?
How about does it return a result set?

Both of those could be issues

E: I'm on my phone but could your command type need to be set to stored procedure or something?

It doesn't have any parameters, it's supposed to create a temporary table elsewhere to be queried.

The PostgreSQL documentation (https://www.postgresql.org/docs/12/errcodes-appendix.html) shows 42809 is "wrong_object_type" but I'm not quite sure how else I should handle this? I've tried using the normal query-like command (queries work, by the way) and specifying the commandtype as procedure ($DBCmd.CommandType = [System.Data.CommandType]::StoredProcedure) with no change.

Nth Doctor
Sep 7, 2010

Darkrai used Dream Eater!
It's super effective!


PierreTheMime posted:

It doesn't have any parameters, it's supposed to create a temporary table elsewhere to be queried.

The PostgreSQL documentation (https://www.postgresql.org/docs/12/errcodes-appendix.html) shows 42809 is "wrong_object_type" but I'm not quite sure how else I should handle this? I've tried using the normal query-like command (queries work, by the way) and specifying the commandtype as procedure ($DBCmd.CommandType = [System.Data.CommandType]::StoredProcedure) with no change.

Your problem has been bothering me for the past couple of days and I did some digging. Your command text may be the problem here since you're using an ODBC command to execute a sproc instead of an ADO command object.

Here's the object documentation: https://docs.microsoft.com/en-us/dotnet/api/system.data.odbc.odbccommand.commandtext?view=netframework-4.8

OdbcCommand.CommandText Property Documentation posted:

A procedure is an executable object stored at the data source. Generally, it is one or more SQL statements that have been precompiled. The escape sequence for calling a procedure is

code:
{[?=]call procedure-name[([parameter][,[parameter]]...)]}

Instead of
code:
$DBCmd.CommandText = "EXEC [foo].[bar]"
Try:
code:
$DBCmd.CommandText = "call [foo].[bar]"
You may need trailing "()" after the sproc name but ODBC has a different syntax that trips folks up.

Guess who used to maintain my company's ODBC platform.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

code:
$DBCmd.CommandText = "call [foo].[bar]()"
$DBCmd.ExecuteNonQuery()
Works! Thanks so much for researching that for me, it seems like such a simple thing but I had searched around and hadn't found a satisfactory answer.

Edit:
I've been formatting CSV reports all day--is this a decent way to get a MMM-formatted list of months in the proper monthly (Jan-Dec) order from an array of Strings or is there a simpler way to go about it?
code:
($StringArray | Sort-Object { $_ -As [DateTime] }) | ForEach-Object { (Get-Date $_).ToString("MMM") } | Get-Unique

PierreTheMime fucked around with this message at 21:16 on Jan 8, 2020

Toast Museum
Dec 3, 2005

30% Iron Chef

PierreTheMime posted:

Edit:
I've been formatting CSV reports all day--is this a decent way to get a MMM-formatted list of months in the proper monthly (Jan-Dec) order from an array of Strings or is there a simpler way to go about it?
code:
($StringArray | Sort-Object { $_ -As [DateTime] }) | ForEach-Object { (Get-Date $_).ToString("MMM") } | Get-Unique

Are you looking to produce a sorted list of all month names, or just the ones that appear in the CSV?

If it's the former,
code:
(Get-Culture).DateTimeFormat.AbbreviatedMonthGenitiveNames
or
code:
[cultureinfo]::GetCultureInfo($CultureIntOrName).DateTimeFormat.AbbreviatedMonthGenitiveNames
if you want more flexibility around who's running the script and/or which language the list should be in.


If it's the latter, this is the way I like best so far, but I feel like there's probably a better way.

code:
[datetime[]]$StringArray | Sort-Object -Property Month | ForEach-Object {"{0:MMM}" -f $_} | Get-Unique
Edit: typo

Toast Museum fucked around with this message at 03:04 on Jan 9, 2020

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
The ask is based around sorting small arrays of M/d/yyyy date strings like @(“1/31/2020”,”2/1/2020”) and appending the summary of the months in MMM format to the end of a filename in the correct order using a join. So if all the dates are in January, it’s just appending “Jan”, but in the the two month example above it would be “Jan-Feb”.

It’s one of those things that’s pretty simple to do, but I’m always interested in the “right” way.

Toast Museum
Dec 3, 2005

30% Iron Chef

PierreTheMime posted:

The ask is based around sorting small arrays of M/d/yyyy date strings like @(“1/31/2020”,”2/1/2020”) and appending the summary of the months in MMM format to the end of a filename in the correct order using a join. So if all the dates are in January, it’s just appending “Jan”, but in the the two month example above it would be “Jan-Feb”.

It’s one of those things that’s pretty simple to do, but I’m always interested in the “right” way.

Gotcha. I'm not ready to claim that it's the best or right way, but here's a function to return the string you're after.

code:
function ReportMonths ([string[]]$dates) 
{
    ([datetime[]]$dates | Sort-Object -Property Month | ForEach-Object {"{0:MMM}" -f $_} | Get-Unique) -join "-"
}
I kept wanting to use [cultureinfo]::InvariantCulture.DateTimeFormat.GetAbbreviatedMonthName, but I don't think it actually adds much value in this case.

Zaepho
Oct 31, 2013

PierreTheMime posted:

The ask is based around sorting small arrays of M/d/yyyy date strings like @(“1/31/2020”,”2/1/2020”) and appending the summary of the months in MMM format to the end of a filename in the correct order using a join. So if all the dates are in January, it’s just appending “Jan”, but in the the two month example above it would be “Jan-Feb”.

It’s one of those things that’s pretty simple to do, but I’m always interested in the “right” way.

I would think pulling and formatting the first and last date in ascending order to just pull the Month part should get you want you're looking for pretty simply. Granted it complicates the single month scenario so maybe not the best idea after all.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
I'm trying to automate some IIS stuff and I'm getting stuck trying to assign an SSL certificate to an HTTPS binding. I'm using the following command:
code:
(Get-WebBinding -Name $name -Protocol "https" -HostHeader $header).AddSslCertificate($cert.Thumbprint, "WebHosting")
$cert is an X509Certificate2 that I've already imported to the WebHosting store for LocalMachine.

The error I'm getting is: A specified logon session does not exist. It may already have been terminated.

sloshmonger
Mar 21, 2013

a hot gujju bhabhi posted:

I'm trying to automate some IIS stuff and I'm getting stuck trying to assign an SSL certificate to an HTTPS binding. I'm using the following command:
code:
(Get-WebBinding -Name $name -Protocol "https" -HostHeader $header).AddSslCertificate($cert.Thumbprint, "WebHosting")
$cert is an X509Certificate2 that I've already imported to the WebHosting store for LocalMachine.

The error I'm getting is: A specified logon session does not exist. It may already have been terminated.


Try this:
code:
netsh http add sslcert hostnameport="${FQDNName}:443" appid="$guid" certhash="$($Cert.Thumbprint)" certstorename=MY
New-WebBinding -name $iisSite -Protocol https  -HostHeader $FQDNName -Port 443 -SslFlags 1 -Force

Woof Blitzer
Dec 29, 2012

[-]
Is there any way to take something icky like a server IP list in a text file and make it into json?

slartibartfast
Nov 13, 2002
:toot:

Woof Blitzer posted:

Is there any way to take something icky like a server IP list in a text file and make it into json?
Basically, it's this:
code:
Get-Content servers.txt | ConvertTo-Json
If you post more specifics about how your text file is laid out, and how you want your JSON to look, you'll get a better answer.

Toast Museum
Dec 3, 2005

30% Iron Chef
PowerShell 7 RC 2 is out

Antigravitas
Dec 8, 2019

Die Rettung fuer die Landwirte:
I've been hacking away at some logging code to make it easier to send our logs to our syslog servers like the majority of our infra does…

code:
Write-Debug : Object reference not set to an instance of an object.
At .\netsyslog.psm1:81 char:43
+         ([netsyslog.Severity]::DEBUG)   { Write-Debug "???"; Break }
+                                           ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Debug], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.WriteDebugCommand
:smith:
I don't get it. Only Write-Debug throws an exception and only when in a switch statement.

slartibartfast
Nov 13, 2002
:toot:
The "?" character is special in Powershell. Try replacing the "???" string with "OHSHIT" instead and see if you get a different result.

Antigravitas
Dec 8, 2019

Die Rettung fuer die Landwirte:
It's an actual variable in the actual code, I just did some redacting. It shows the exact same exception with "foo".

Toast Museum
Dec 3, 2005

30% Iron Chef

Antigravitas posted:

I've been hacking away at some logging code to make it easier to send our logs to our syslog servers like the majority of our infra does…

code:
Write-Debug : Object reference not set to an instance of an object.
At .\netsyslog.psm1:81 char:43
+         ([netsyslog.Severity]::DEBUG)   { Write-Debug "???"; Break }
+                                           ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Debug], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.WriteDebugCommand
:smith:
I don't get it. Only Write-Debug throws an exception and only when in a switch statement.

When you say that only Write-Debug does it, do you mean that it doesn't happen with Write-Error, Write-Verbose, etc.?

Maybe a scope issue? Switch statement scriptblocks have their own scope. The most granular way I know of to specify variable scope is with Get-Variable

Antigravitas
Dec 8, 2019

Die Rettung fuer die Landwirte:
Write-Warning, Write-Verbose, Write-Error don't show the behaviour, it's literally only Write-Debug.

I suspected scoping issues first but a string literal is the most in-scope I can think of.

Toast Museum
Dec 3, 2005

30% Iron Chef
Ah, poo poo, I forgot the part where you said that it does the same with a string. So much for that idea.

The Fool
Oct 16, 2003


Any chance it's an encoding issue?

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!
Does the script do something weird with scoping $DebugPreference?

Pile Of Garbage
May 28, 2007



Antigravitas posted:

I've been hacking away at some logging code to make it easier to send our logs to our syslog servers like the majority of our infra does…

code:
Write-Debug : Object reference not set to an instance of an object.
At .\netsyslog.psm1:81 char:43
+         ([netsyslog.Severity]::DEBUG)   { Write-Debug "???"; Break }
+                                           ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Debug], NullReferenceException
    + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.WriteDebugCommand
:smith:
I don't get it. Only Write-Debug throws an exception and only when in a switch statement.

Can you post the code?

Adbot
ADBOT LOVES YOU

Antigravitas
Dec 8, 2019

Die Rettung fuer die Landwirte:

Jethro posted:

Does the script do something weird with scoping $DebugPreference?

Bingo. It's a new day, just got into the office, did a git diff on a lark, and found this piece of code within the module:

code:
$DebugPreference = 
Here's how you, too, can suffer. Save this code as a .psm1 and import-module it:

code:
Set-StrictMode -Version "2.0"
$ErrorActionPreference = "Stop"
$DebugPreference =
function Write-Log {
    Write-Debug "Test"
} 
Then invoking Write-Log will throw the exception (PSVersion 5.1 FWIW)

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